// SyncServiceRegistry syncs all vhosts and public ports to those of a matching
// service.
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
}
1144026
func (c *ServicedCli) cmdMigrateRegistry(ctx *cli.Context) {
	endpoint := ctx.String("registry")
	override := ctx.Bool("override")
	if err := c.driver.UpgradeRegistry(endpoint, override); err != nil {
		log.WithFields(logrus.Fields{
			"registry": endpoint,
			"override": override,
		}).WithError(err).Fatal("Unable to upgrade local Docker registry")
	}
}
949432
func registerService(objClient objdb.API, ctrlIP, vtepIP, hostname string, vxlanUDPPort int) error {
	// netplugin service info
	srvInfo := objdb.ServiceInfo{
		ServiceName: "netplugin",
		TTL:         10,
		HostAddr:    ctrlIP,
		Port:        netpluginRPCPort1,
		Hostname:    hostname,
	}

	// Register the node with service registry
	err := objClient.RegisterService(srvInfo)
	if err != nil {
		log.Fatalf("Error registering service. Err: %v", err)
		return err
	}

	srvInfo = objdb.ServiceInfo{
		ServiceName: "netplugin",
		TTL:         10,
		HostAddr:    ctrlIP,
		Port:        netpluginRPCPort2,
		Hostname:    hostname,
	}

	// Register the node with service registry
	err = objClient.RegisterService(srvInfo)
	if err != nil {
		log.Fatalf("Error registering service. Err: %v", err)
		return err
	}

	// netplugn VTEP service info
	srvInfo = objdb.ServiceInfo{
		ServiceName: "netplugin.vtep",
		TTL:         10,
		HostAddr:    vtepIP,
		Port:        vxlanUDPPort,
		Hostname:    hostname,
	}

	// Register the node with service registry
	err = objClient.RegisterService(srvInfo)
	if err != nil {
		log.Fatalf("Error registering service. Err: %v", err)
		return err
	}

	log.Infof("Registered netplugin service with registry")
	return nil
}
845205
func (s *Server) UpgradeRegistry(req UpgradeDockerRequest, reply *int) error {
	return s.f.UpgradeRegistry(s.context(), req.Endpoint, req.Override)
}
593002
func RegisterEthService(stack *node.Node, cfg *eth.Config) {
	var err error
	if cfg.SyncMode == downloader.LightSync {
		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
			return les.New(ctx, cfg)
		})
	} else {
		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
			fullNode, err := eth.New(ctx, cfg)
			if fullNode != nil && cfg.LightServ > 0 {
				ls, _ := les.NewLesServer(fullNode, cfg)
				fullNode.AddLesServer(ls)
			}
			return fullNode, err
		})
	}
	if err != nil {
		Fatalf("Failed to register the Ethereum service: %v", err)
	}
}
101923
func SyncHostEntry(ip net.IP) (bool, error) {
	key := NewEndpointKey(ip)
	value, err := LXCMap.Lookup(key)
	if err != nil || value.(*EndpointInfo).Flags&EndpointFlagHost == 0 {
		err = AddHostEntry(ip)
		if err == nil {
			return true, nil
		}
	}
	return false, err
}
943739
func (s *CreateServiceInput) SetServiceRegistries(v []*ServiceRegistry) *CreateServiceInput {
	s.ServiceRegistries = v
	return s
}
884065
func NewAPIServiceRegistrationController(apiServiceInformer informers.APIServiceInformer, apiHandlerManager APIHandlerManager) *APIServiceRegistrationController {
	c := &APIServiceRegistrationController{
		apiHandlerManager: apiHandlerManager,
		apiServiceLister:  apiServiceInformer.Lister(),
		apiServiceSynced:  apiServiceInformer.Informer().HasSynced,
		queue:             workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "APIServiceRegistrationController"),
	}

	apiServiceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    c.addAPIService,
		UpdateFunc: c.updateAPIService,
		DeleteFunc: c.deleteAPIService,
	})

	c.syncFn = c.sync

	return c
}
1316899
func NewDockerRegistryServiceController(secrets informers.SecretInformer, serviceInformer informers.ServiceInformer, cl kclientset.Interface, options DockerRegistryServiceControllerOptions) *DockerRegistryServiceController {
	e := &DockerRegistryServiceController{
		client:                 cl,
		additionalRegistryURLs: options.AdditionalRegistryURLs,
		clusterDNSSuffix:       options.ClusterDNSSuffix,
		dockercfgController:    options.DockercfgController,
		registryLocationQueue:  workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
		secretsToUpdate:        workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
		dockerURLsInitialized:  options.DockerURLsInitialized,
	}

	// we're only watching two of these, but we already watch all services for the service serving cert signer
	// and this correctly handles namespaces coming and going
	serviceInformer.Informer().AddEventHandler(
		cache.FilteringResourceEventHandler{
			FilterFunc: func(obj interface{}) bool {
				switch t := obj.(type) {
				case *v1.Service:
					for _, location := range serviceLocations {
						if t.Namespace == location.namespace && t.Name == location.name {
							return true
						}
					}
				}
				return false
			},
			Handler: cache.ResourceEventHandlerFuncs{
				AddFunc: func(obj interface{}) {
					e.enqueueRegistryLocationQueue()
				},
				UpdateFunc: func(old, cur interface{}) {
					e.enqueueRegistryLocationQueue()
				},
				DeleteFunc: func(obj interface{}) {
					e.enqueueRegistryLocationQueue()
				},
			}},
	)
	e.servicesSynced = serviceInformer.Informer().HasSynced
	e.serviceLister = serviceInformer.Lister()

	e.syncRegistryLocationHandler = e.syncRegistryLocationChange

	e.secretCache = secrets.Informer().GetIndexer()
	e.secretsSynced = secrets.Informer().GetController().HasSynced
	e.syncSecretHandler = e.syncSecretUpdate

	return e
}
1238068
func SyncConfig(addr string, localDir string) (bool, error) {
	return local.SyncConfig(addr, localDir)
}
362831
func (c *ServiceClient) AllocRegistrations(allocID string) (*AllocRegistration, error) {
	// Get the internal struct using the lock
	c.allocRegistrationsLock.RLock()
	regInternal, ok := c.allocRegistrations[allocID]
	if !ok {
		c.allocRegistrationsLock.RUnlock()
		return nil, nil
	}

	// Copy so we don't expose internal structs
	reg := regInternal.copy()
	c.allocRegistrationsLock.RUnlock()

	// Query the services and checks to populate the allocation registrations.
	services, err := c.client.Services()
	if err != nil {
		return nil, err
	}

	checks, err := c.client.Checks()
	if err != nil {
		return nil, err
	}

	// Populate the object
	for _, treg := range reg.Tasks {
		for serviceID, sreg := range treg.Services {
			sreg.Service = services[serviceID]
			for checkID := range sreg.checkIDs {
				if check, ok := checks[checkID]; ok {
					sreg.Checks = append(sreg.Checks, check)
				}
			}
		}
	}

	return reg, nil
}
1057255
func (e *DockerRegistryServiceController) syncRegistryLocationChange() error {
	newLocations := e.getDockerRegistryLocations()
	newDockerRegistryLocations := sets.NewString(newLocations...)
	existingURLs := e.getRegistryURLs()
	if existingURLs.Equal(newDockerRegistryLocations) && e.initialSecretsCheckDone {
		klog.V(3).Infof("No effective update: %v", newDockerRegistryLocations)
		return nil
	}
	klog.V(1).Infof("Updating registry URLs from %v to %v", existingURLs, newDockerRegistryLocations)

	// make sure that new dockercfg secrets get the correct locations
	e.dockercfgController.SetDockerURLs(newDockerRegistryLocations.List()...)
	e.setRegistryURLs(newDockerRegistryLocations.List()...)
	e.initialSecretsCheckDone = true

	// we've changed the docker registry URL.  Add items to the work queue for all known secrets
	// new secrets will already get the updated value.
	for _, obj := range e.secretCache.List() {
		switch t := obj.(type) {
		case *v1.Secret:
			if t.Type != v1.SecretTypeDockercfg {
				continue
			}
			if t.Annotations == nil {
				continue
			}
			// Do not manage dockercfg secrets we haven't created (eg. secrets created by user for private repositories).
			if _, hasTokenSecret := t.Annotations[ServiceAccountTokenSecretNameKey]; !hasTokenSecret {
				continue
			}
		default:
			utilruntime.HandleError(fmt.Errorf("object passed to %T that is not expected: %T", e, obj))
			continue
		}
		key, err := controller.KeyFunc(obj)
		if err != nil {
			utilruntime.HandleError(fmt.Errorf("couldn't get key for object %#v: %v", obj, err))
			continue
		}

		e.secretsToUpdate.Add(key)
	}

	return nil
}
1162501
func registerService(name string, port int, ttl int) {

	reportInterval := make(chan bool, 1)
	go func() {
		for {
			time.Sleep(time.Duration(ttl) / 2 * time.Second)
			reportInterval <- true
		}
	}()

	client, err := consul.NewClient(consul.DefaultConfig())
	if nil != err {
		log.Error("Failed to get consul client")
	}
	agent := client.Agent()

	serviceRegister(name, port, ttl, agent)
	for {
		select {
		case <-reportInterval: //report registration
			{
				servicePassing(name, agent)

			}
		}
	}

}
837647
func syncServicePublicPorts(conn client.Connection, tx client.Transaction, request ServiceRegistrySyncRequest) error {
	logger := plog.WithField("serviceid", request.ServiceID)
	pth := "/net/pub"

	for _, pubKey := range request.PortsToDelete {
		addrpth := path.Join(pth, pubKey.HostID, pubKey.PortAddress)
		addrLogger := logger.WithFields(log.Fields{
			"hostid":      pubKey.HostID,
			"portaddress": pubKey.PortAddress,
			"zkpath":      addrpth,
		})
		tx.Delete(addrpth)
		addrLogger.Debug("Deleted public port address")
	}

	// Build a list of unique parent directory paths which need to be created
	pathsToBuild := map[string]string{}
	for pubKey, _ := range request.PortsToPublish {
		if _, ok := pathsToBuild[pubKey.HostID]; ok {
			continue
		}
		hostpth := path.Join(pth, pubKey.HostID)
		ok, err := conn.Exists(hostpth)
		if err != nil {
			return &RegistryError{
				Action:  "sync",
				Path:    hostpth,
				Message: "could not read parent path for public port address",
			}
		} else if !ok {
			pathsToBuild[pubKey.HostID] = hostpth
		}
	}

	// Build any missing parent directory paths
	if err := buildParentPaths(logger, conn, pathsToBuild); err != nil {
		err.Message = "could not register public port address"
		return err
	}

	for pubKey, pubValue := range request.PortsToPublish {
		addrpth := path.Join(pth, pubKey.HostID, pubKey.PortAddress)
		addrLogger := logger.WithFields(log.Fields{
			"hostid":      pubKey.HostID,
			"portaddress": pubKey.PortAddress,
			"zkpath":      addrpth,
		})

		ok, err := conn.Exists(addrpth)
		if err != nil {
			addrLogger.WithError(err).Debug("skipped public port address because of an unexpected error")
			return &RegistryError{
				Action:  "sync",
				Path:   addrpth,
				Message: "could not register public port address",
			}
		}

		publicPort := pubValue
		if !ok {
			publicPort.SetVersion(nil)
			tx.Create(addrpth, &publicPort)
			addrLogger.Debug("Created public port address")
		} else {
			existingPub := &PublicPort{}
			if err := conn.Get(addrpth, existingPub); err != nil {
				return &RegistryError{
					Action:  "sync",
					Path:    addrpth,
					Message: "could not read current public port address",
				}
			}
			publicPort.SetVersion(existingPub.Version())
			tx.Set(addrpth, &publicPort)
			addrLogger.Debug("Updated public port address")
		}
	}

	logger.Debug("Updated transaction to sync public ports for service")
	return nil
}
771653
func (s *DefaultService) ServiceConfig() *registrytypes.ServiceConfig {
	s.mu.Lock()
	defer s.mu.Unlock()

	servConfig := registrytypes.ServiceConfig{
		AllowNondistributableArtifactsCIDRs:     make([]*(registrytypes.NetIPNet), 0),
		AllowNondistributableArtifactsHostnames: make([]string, 0),
		InsecureRegistryCIDRs:                   make([]*(registrytypes.NetIPNet), 0),
		IndexConfigs:                            make(map[string]*(registrytypes.IndexInfo)),
		Mirrors:                                 make([]string, 0),
	}

	// construct a new ServiceConfig which will not retrieve s.Config directly,
	// and look up items in s.config with mu locked
	servConfig.AllowNondistributableArtifactsCIDRs = append(servConfig.AllowNondistributableArtifactsCIDRs, s.config.ServiceConfig.AllowNondistributableArtifactsCIDRs...)
	servConfig.AllowNondistributableArtifactsHostnames = append(servConfig.AllowNondistributableArtifactsHostnames, s.config.ServiceConfig.AllowNondistributableArtifactsHostnames...)
	servConfig.InsecureRegistryCIDRs = append(servConfig.InsecureRegistryCIDRs, s.config.ServiceConfig.InsecureRegistryCIDRs...)

	for key, value := range s.config.ServiceConfig.IndexConfigs {
		servConfig.IndexConfigs[key] = value
	}

	servConfig.Mirrors = append(servConfig.Mirrors, s.config.ServiceConfig.Mirrors...)

	return &servConfig
}
922012
func hostIsAzureContainerRegistry(host string) bool {
	for _, v := range []string{".azurecr.io", ".azurecr.cn", ".azurecr.de", ".azurecr.us"} {
		if strings.HasSuffix(host, v) {
			return true
		}
	}
	return false
}
972651
func (zk *zkf) buildServiceRegistryCache(conn client.Connection) error {
	publicPorts, err := zkr.GetPublicPorts(conn)
	if err != nil {
		return err
	}
	vhosts, err := zkr.GetVHosts(conn)
	if err != nil {
		return err
	}
	zk.svcRegistry.BuildCache(publicPorts, vhosts)
	return nil
}