// ServiceDeregister is used to deregister a service with
// the local agent
543134
func (a *Agent) ServiceDeregister(serviceID string) error {
	r := a.c.newRequest("PUT", "/v1/agent/service/deregister/"+serviceID)
	_, resp, err := requireOK(a.c.doRequest(r))
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}
899339
func (a *Agent) vetServiceRegister(token string, service *structs.NodeService) error {
	// Resolve the token and bail if ACLs aren't enabled.
	rule, err := a.resolveToken(token)
	if err != nil {
		return err
	}
	if rule == nil {
		return nil
	}

	// Vet the service itself.
	if !rule.ServiceWrite(service.Service, nil) {
		return acl.ErrPermissionDenied
	}

	// Vet any service that might be getting overwritten.
	services := a.State.Services()
	if existing, ok := services[service.ID]; ok {
		if !rule.ServiceWrite(existing.Service, nil) {
			return acl.ErrPermissionDenied
		}
	}

	// If the service is a proxy, ensure that it has write on the destination too
	// since it can be discovered as an instance of that service.
	if service.Kind == structs.ServiceKindConnectProxy {
		if !rule.ServiceWrite(service.Proxy.DestinationServiceName, nil) {
			return acl.ErrPermissionDenied
		}
	}

	return nil
}
686577
func (c *ServiceWorker) Unregister(scopeURL string) (*gcdmessage.ChromeResponse, error) {
	var v ServiceWorkerUnregisterParams
	v.ScopeURL = scopeURL
	return c.UnregisterWithParams(&v)
}
969769
func (c *ServicedCli) cmdRestore(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restore")
		return
	}

	err := c.driver.Restore(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}
349991
func (a *Agent) DisableServiceMaintenance(serviceID string) error {
	if _, ok := a.State.Services()[serviceID]; !ok {
		return fmt.Errorf("No service registered with ID %q", serviceID)
	}

	// Check if maintenance mode is enabled
	checkID := serviceMaintCheckID(serviceID)
	if _, ok := a.State.Checks()[checkID]; !ok {
		return nil
	}

	// Deregister the maintenance check
	a.RemoveCheck(checkID, true)
	a.logger.Printf("[INFO] agent: Service %q left maintenance mode", serviceID)

	return nil
}
793389
func (r *Registrar) Deregister() {
	if err := r.client.Deregister(r.service); err != nil {
		r.logger.Log("err", err)
	} else {
		r.logger.Log("action", "deregister")
	}

	r.quitmtx.Lock()
	defer r.quitmtx.Unlock()
	if r.quit != nil {
		close(r.quit)
		r.quit = nil
	}
}
857325
func (c *ServicedCli) cmdHostRegister(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "register")
		return
	}

	var (
		data []byte
		err  error
	)
	fname := args[0]
	switch fname {
	case "-":
		data, err = ioutil.ReadAll(os.Stdin)
	default:
		data, err = ioutil.ReadFile(fname)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := c.driver.RegisterHost(data); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

}
259238
func (c *ServicedCli) cmdServiceClearEmergency(ctx *cli.Context) {
	// verify args
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "clear-emergency")
		c.exit(1)
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	count, err := c.driver.ClearEmergency(svc.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	fmt.Printf("Cleared emergency status for %d services\n", count)
	return
}
1124537
func (c *ServicedCli) cmdServiceTune(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "tune")
		c.exit(1)
		return
	}

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	service, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	// Check the arguments
	if !(ctx.IsSet("instances") || ctx.IsSet("ramCommitment") || ctx.IsSet("ramThreshold")) {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "tune")
		return
	}

	modified := false
	if ctx.IsSet("instances") {
		oldInstanceCount := service.Instances
		newInstanceCount := ctx.Int("instances")
		if oldInstanceCount != newInstanceCount {
			service.Instances = newInstanceCount
			modified = true
		}
	}

	if ctx.IsSet("ramCommitment") {
		oldCommitment := service.RAMCommitment
		newCommitment, err := utils.NewEngNotationFromString(ctx.String("ramCommitment"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		if oldCommitment.Value != newCommitment.Value {
			service.RAMCommitment = newCommitment
			modified = true
		}
	}

	if ctx.IsSet("ramThreshold") {
		oldThreshold := uint64(service.RAMThreshold)
		newThreshold := ctx.String("ramThreshold")

		suffix := newThreshold[len(newThreshold)-1:]
		if suffix != "%" {
			fmt.Fprintln(os.Stderr, fmt.Errorf("ramThreshold '%s' does not end with %%", newThreshold))
			c.exit(1)
			return
		}

		percent := newThreshold[:len(newThreshold)-1]
		val, err := strconv.ParseUint(percent, 10, 64)
		if err != nil {
			fmt.Fprintln(os.Stderr, fmt.Errorf("ramThreshold '%s' must be an integer", newThreshold))
			c.exit(1)
			return
		}

		if oldThreshold != val {
			service.RAMThreshold = uint(val)
			modified = true
		}
	}

	if modified {
		if service, err := c.driver.UpdateServiceObj(*service); err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else if service == nil {
			fmt.Fprintln(os.Stderr, "received nil service")
			c.exit(1)
			return
		} else {
			fmt.Println(service.ID)
		}
	} else {
		fmt.Printf("Service already reflects desired configured - no changes made\n\n")
		return
	}

}
1015862
func RegisterHelper(name string, helper interface{}) {
	helpersMutex.Lock()
	defer helpersMutex.Unlock()

	if helpers[name] != zero {
		panic(fmt.Errorf("Helper already registered: %s", name))
	}

	val := reflect.ValueOf(helper)
	ensureValidHelper(name, val)

	helpers[name] = val
}
551203
func RegisterEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	client := NewEchoServiceClient(conn)

	mux.Handle("POST", pattern_EchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		if cn, ok := w.(http.CloseNotifier); ok {
			go func(done <-chan struct{}, closed <-chan bool) {
				select {
				case <-done:
				case <-closed:
					cancel()
				}
			}(ctx.Done(), cn.CloseNotify())
		}
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
		}
		resp, md, err := request_EchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_EchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)

	})

	mux.Handle("GET", pattern_EchoService_Stream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		if cn, ok := w.(http.CloseNotifier); ok {
			go func(done <-chan struct{}, closed <-chan bool) {
				select {
				case <-done:
				case <-closed:
					cancel()
				}
			}(ctx.Done(), cn.CloseNotify())
		}
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
		}
		resp, md, err := request_EchoService_Stream_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_EchoService_Stream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)

	})

	mux.Handle("POST", pattern_EchoService_Heartbeats_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		if cn, ok := w.(http.CloseNotifier); ok {
			go func(done <-chan struct{}, closed <-chan bool) {
				select {
				case <-done:
				case <-closed:
					cancel()
				}
			}(ctx.Done(), cn.CloseNotify())
		}
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
		}
		resp, md, err := request_EchoService_Heartbeats_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_EchoService_Heartbeats_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)

	})

	return nil
}
494174
func SyncServiceRegistry(conn client.Connection, request ServiceRegistrySyncRequest) error {
	logger := plog.WithField("serviceid", request.ServiceID)

	if len(request.PortsToDelete) == 0 &&
	   len(request.PortsToPublish) == 0 &&
	   len(request.VHostsToDelete) == 0 &&
	   len(request.VHostsToPublish) == 0 {
		// Don't even create a transaction if there's nothing to do (which is typical for many kinds of services)
		return nil
	}

	tx := conn.NewTransaction()

	if err := syncServicePublicPorts(conn, tx, request); err != nil {
		logger.WithError(err).Debug("Could not sync public ports for service")
		return err
	}
	if err := syncServiceVHosts(conn, tx, request); err != nil {
		logger.WithError(err).Debug("Could not sync virtual hosts for service")
		return err
	}

	if err := tx.Commit(); err != nil {
		logger.WithError(err).Debug("Could not sync registry for service")
		// TODO: wrap error?
		return err
	}

	logger.Debug("Updated registry for service")
	return nil
}
273517
func (ref *EventClientRef) Unregister(reg fab.Registration) {
	if service, err := ref.get(); err != nil {
		logger.Warnf("Error unregistering event registration: %s", err)
	} else {
		service.Unregister(reg)
	}
}
1266241
func registerUnregisterService(root string) (bool, error) {

	if unregisterServiceFlag {
		if registerServiceFlag {
			return true, errors.New("--register-service and --unregister-service cannot be used together")
		}
		return true, unregisterService()
	}

	if registerServiceFlag {
		return true, registerService()
	}

	if runServiceFlag {
		if err := initPanicFile(filepath.Join(root, "panic.log")); err != nil {
			return true, err
		}

		interactive, err := svc.IsAnInteractiveSession()
		if err != nil {
			return true, err
		}

		var log *eventlog.Log
		if !interactive {
			log, err = eventlog.Open(serviceNameFlag)
			if err != nil {
				return true, err
			}
		}

		logrus.AddHook(&etwHook{log})
		logrus.SetOutput(ioutil.Discard)

	}
	return false, nil
}
1324466
func (c *ServicedCli) cmdServiceAssignIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "assign-ip")
		c.exit(1)
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	var ipAddress string
	if len(args) > 1 {
		ipAddress = args[1]
	}

	cfg := api.IPConfig{
		ServiceID: svc.ID,
		IPAddress: ipAddress,
	}

	if err := c.driver.AssignIP(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	}
	return
}
1019682
func LocalRegister(id IdentityID, authServer *AuthServer, additionalPrincipals, dnsNames []string, remoteAddr string) (*Identity, error) {
	// If local registration is happening and no remote address was passed in
	// (which means no advertise IP was set), use localhost.
	if remoteAddr == "" {
		remoteAddr = defaults.Localhost
	}
	keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{
		HostID:               id.HostUUID,
		NodeName:             id.NodeName,
		Roles:                teleport.Roles{id.Role},
		AdditionalPrincipals: additionalPrincipals,
		RemoteAddr:           remoteAddr,
		DNSNames:             dnsNames,
		NoCache:              true,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	identity, err := ReadIdentityFromKeyPair(keys)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return identity, nil
}
1096261
func (c *ServicedCli) cmdServiceRestart(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restart")
		c.exit(1)
		return
	}

	var sIds []string
	var instances []struct {
		Service  string
		Instance int
	}

	for _, arg := range args {
		svc, instanceID, err := c.searchForService(arg, ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		if instanceID < 0 {
			sIds = append(sIds, svc.ID)
		} else {
			instances = append(instances, struct {
				Service  string
				Instance int
			}{
				svc.ID,
				instanceID,
			})
		}
	}

	// Batch start services
	if len(sIds) > 0 {
		if ctx.Bool("rebalance") {
			if affected, err := c.driver.RebalanceService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		} else {
			if affected, err := c.driver.RestartService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		}
	}

	// Iterate and reschedule any instances specified
	for _, instance := range instances {
		if err := c.driver.StopServiceInstance(instance.Service, instance.Instance); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
		} else {
			fmt.Printf("Restarting instance %s/%d\n", instance.Service, instance.Instance)
		}
	}
	return
}