// SingleNodeCluster determines if hostport is the only host:port contained within
// the hostMap.
962145
func SingleNodeCluster(hostport string, hostMap map[string][]string) bool {
	// If the map contains more than one host then clearly there is more than
	// one address so we can't be a single node cluster.
	if len(hostMap) > 1 {
		return false
	}

	host := CaptureHost(hostport)

	// If hostport is not even in the map at all then it's not possible for
	// us to be a single node cluster.
	_, ok := hostMap[host]
	if !ok {
		return false
	}

	// Same as above; there is most than one host
	if len(hostMap[host]) > 1 {
		return false
	}

	// There is a single hostport in the map; check that it matches
	if hostMap[host][0] == hostport {
		return true
	}

	// There is a single hostport in the map but it doesn't match the given
	// hostport.
	return false
}
13899
func (s *PortSpec) SinglePort() (uint16, error) {
	if s.IsMultiPort() {
		return 0, errors.New("Not a single port specification")
	}

	return s.Min, nil
}
431123
func (s *Sentinel) GetCluster(name string) (c *Cluster, err error) {
	return s.getCluster(name, "")
}
1318266
func (s *ClusterService) DedicateCluster(p *DedicateClusterParams) (*DedicateClusterResponse, error) {
	resp, err := s.cs.newRequest("dedicateCluster", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DedicateClusterResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
638441
func (s *APIServer) createRemoteCluster(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	var req createRemoteClusterRawReq
	if err := httplib.ReadJSON(r, &req); err != nil {
		return nil, trace.Wrap(err)
	}
	conn, err := services.UnmarshalRemoteCluster(req.RemoteCluster)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if err := auth.CreateRemoteCluster(conn); err != nil {
		return nil, trace.Wrap(err)
	}
	return message("ok"), nil
}
1096910
func NewClientInCluster() Kubernetes {
	host := "https://" + os.Getenv("KUBERNETES_SERVICE_HOST") + ":" + os.Getenv("KUBERNETES_SERVICE_PORT")

	s, err := os.Stat(serviceAccountPath)
	if err != nil {
		log.Fatal(err)
	}
	if s == nil || !s.IsDir() {
		log.Fatal(errors.New("no k8s service account found"))
	}

	token, err := ioutil.ReadFile(path.Join(serviceAccountPath, "token"))
	if err != nil {
		log.Fatal(err)
	}
	t := string(token)

	ns, err := detectNamespace()
	if err != nil {
		log.Fatal(err)
	}

	crt, err := CertPoolFromFile(path.Join(serviceAccountPath, "ca.crt"))
	if err != nil {
		log.Fatal(err)
	}

	c := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				RootCAs: crt,
			},
			DisableCompression: true,
		},
	}

	return &client{
		opts: &api.Options{
			Client:      c,
			Host:        host,
			Namespace:   ns,
			BearerToken: &t,
		},
	}
}
1014544
func (s *StanServer) bootstrapCluster(name string, node *raft.Raft) error {
	var (
		addr = s.getClusteringAddr(name)
		// Include ourself in the cluster.
		servers = []raft.Server{raft.Server{
			ID:      raft.ServerID(s.opts.Clustering.NodeID),
			Address: raft.ServerAddress(addr),
		}}
	)
	if len(s.opts.Clustering.Peers) > 0 {
		// Bootstrap using provided cluster configuration.
		s.log.Debugf("Bootstrapping Raft group %s using provided configuration", name)
		for _, peer := range s.opts.Clustering.Peers {
			servers = append(servers, raft.Server{
				ID:      raft.ServerID(peer),
				Address: raft.ServerAddress(s.getClusteringPeerAddr(name, peer)),
			})
		}
	} else {
		// Bootstrap as a seed node.
		s.log.Debugf("Bootstrapping Raft group %s as seed node", name)
	}
	config := raft.Configuration{Servers: servers}
	return node.BootstrapCluster(config).Error()
}
1229779
func (a *AuthServer) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) {
	return a.GetCache().GetClusterConfig(opts...)
}
758748
func (daemon *Daemon) DaemonLeavesCluster() {
	// Daemon is in charge of removing the attachable networks with
	// connected containers when the node leaves the swarm
	daemon.clearAttachableNetworks()
	// We no longer need the cluster provider, stop it now so that
	// the network agent will stop listening to cluster events.
	daemon.setClusterProvider(nil)
	// Wait for the networking cluster agent to stop
	daemon.netController.AgentStopWait()
	// Daemon is in charge of removing the ingress network when the
	// node leaves the swarm. Wait for job to be done or timeout.
	// This is called also on graceful daemon shutdown. We need to
	// wait, because the ingress release has to happen before the
	// network controller is stopped.
	if done, err := daemon.ReleaseIngress(); err == nil {
		select {
		case <-done:
		case <-time.After(5 * time.Second):
			logrus.Warn("timeout while waiting for ingress network removal")
		}
	} else {
		logrus.Warnf("failed to initiate ingress network removal: %v", err)
	}

	daemon.attachmentStore.ClearAttachments()
}
509636
func (u *DockerRegistryURL) HostPort() string {
	if u.Port == "" {
		return u.Host
	}
	return net.JoinHostPort(u.Host, u.Port)

}
336142
func (engine *OrcEngine) onClusterNodeLost(nodeName string, downCount int) {
	log.Warnf("Cluster node is down, [%q], %d nodes down in all, will check if need stop the engine", nodeName, downCount)
	if downCount >= maxDownNode {
		log.Warnf("Too many cluster nodes stoped in a short period, need stop the engine")
		ntfController.Send(NewNotifySpec("Cluster", "Deployd",
			1, time.Now(), NotifyClusterAbnormal))
		engine.Stop()
	}
}
1222302
func (a *AuthServer) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) {
	return a.GetCache().GetClusterName(opts...)
}
405967
func (s *EnvoyApi) EnvoyClustersFromState() []*EnvoyCluster {
	clusters := make([]*EnvoyCluster, 0)

	s.state.RLock()
	defer s.state.RUnlock()

	svcs := s.state.ByService()
	for svcName, endpoints := range svcs {
		if len(endpoints) < 1 {
			continue
		}

		var svc *service.Service
		for _, endpoint := range endpoints {
			if endpoint.IsAlive() {
				svc = endpoint
				break
			}
		}

		if svc == nil {
			continue
		}

		for _, port := range svc.Ports {
			if port.ServicePort < 1 {
				continue
			}

			clusters = append(clusters, &EnvoyCluster{
				Name:             SvcName(svcName, port.ServicePort),
				Type:             "sds", // use Sidecar's SDS endpoint for the hosts
				ConnectTimeoutMs: 500,
				LBType:           "round_robin", // TODO figure this out!
				ServiceName:      SvcName(svcName, port.ServicePort),
			})
		}
	}

	return clusters
}
779654
func (s *ClusterService) ListClusters(p *ListClustersParams) (*ListClustersResponse, error) {
	resp, err := s.cs.newRequest("listClusters", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListClustersResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
408548
func parseCluster(itf interface{}, opts *Options) error {
	m, ok := itf.(map[string]interface{})
	if !ok {
		return fmt.Errorf("expected cluster to be a map/struct, got %v", itf)
	}
	opts.Clustering.Clustered = true
	for k, v := range m {
		name := strings.ToLower(k)
		switch name {
		case "node_id":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			opts.Clustering.NodeID = v.(string)
		case "bootstrap":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.Bootstrap = v.(bool)
		case "peers":
			if err := checkType(k, reflect.Slice, v); err != nil {
				return err
			}
			peers := make([]string, len(v.([]interface{})))
			for i, p := range v.([]interface{}) {
				peers[i] = p.(string)
			}
			opts.Clustering.Peers = peers
		case "log_path":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			opts.Clustering.RaftLogPath = v.(string)
		case "log_cache_size":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.LogCacheSize = int(v.(int64))
		case "log_snapshots":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.LogSnapshots = int(v.(int64))
		case "trailing_logs":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.TrailingLogs = v.(int64)
		case "sync":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.Sync = v.(bool)
		case "raft_logging":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.RaftLogging = v.(bool)
		case "raft_heartbeat_timeout":
			fallthrough
		case "raft_election_timeout":
			fallthrough
		case "raft_lease_timeout":
			fallthrough
		case "raft_commit_timeout":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			dur, err := time.ParseDuration(v.(string))
			if err != nil {
				return err
			}
			switch name {
			case "raft_heartbeat_timeout":
				opts.Clustering.RaftHeartbeatTimeout = dur
			case "raft_election_timeout":
				opts.Clustering.RaftElectionTimeout = dur
			case "raft_lease_timeout":
				opts.Clustering.RaftLeaseTimeout = dur
			case "raft_commit_timeout":
				opts.Clustering.RaftCommitTimeout = dur
			}
		}
	}
	return nil
}
105836
func (c *VFSClientset) CreateCluster(cluster *kops.Cluster) (*kops.Cluster, error) {
	return c.clusters().Create(cluster)
}
847673
func (_class ClusterHostClass) GetCluster(sessionID SessionRef, self ClusterHostRef) (_retval ClusterRef, _err error) {
	_method := "Cluster_host.get_cluster"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertClusterHostRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertClusterRefToGo(_method + " -> ", _result.Value)
	return
}