// LocateServiceInstance returns host and container information about a service
// instance
499437
func (f *Facade) LocateServiceInstance(ctx datastore.Context, serviceID string, instanceID int) (*service.LocationInstance, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.LocateServiceInstance"))
	logger := plog.WithFields(log.Fields{
		"serviceid":  serviceID,
		"instanceid": instanceID,
	})

	svc, err := f.serviceStore.Get(ctx, serviceID)
	if err != nil {
		logger.WithError(err).Debug("Could not look up service")
		return nil, err
	}

	state, err := f.zzk.GetServiceState(ctx, svc.PoolID, svc.ID, instanceID)
	if err != nil {
		logger.WithError(err).Debug("Could not locate service instance")
		return nil, err
	}

	logger.Debug("Found service instance")
	return &service.LocationInstance{
		HostID:      state.HostID,
		HostIP:      state.HostIP,
		ContainerID: state.ContainerID,
	}, nil
}
1164292
func (c *ServicedCli) searchForService(keyword string, prefix bool) (*service.ServiceDetails, int, error) {

	// If the last segment is an integer, it is an instance ID
	servicepath, instanceIDString := path.Split(keyword)
	instanceID := -1
	if num, err := strconv.Atoi(instanceIDString); err != nil {
		// It's not an integer, so just use the original path
		servicepath = keyword
	} else {
		instanceID = num
	}

	matches, err := c.driver.ResolveServicePath(servicepath, prefix)
	if err != nil {
		return nil, 0, err
	}

	// check the number of matches
	if count := len(matches); count == 0 {
		return nil, 0, errors.New("service not found")
	} else if count == 1 {
		return &matches[0], instanceID, nil
	}

	// more than one match, display a dialog
	var svcpath func(*service.ServiceDetails) string
	svcpath = func(svc *service.ServiceDetails) string {
		parent := svc.Parent
		if parent != nil {
			return path.Join(svcpath(parent), svc.Name)
		}
		return path.Join(svc.DeploymentID, svc.Name)
	}

	t := NewTable("Name,ServiceID,DepID/Path")
	t.Padding = 6
	for _, row := range matches {
		t.AddRow(map[string]interface{}{
			"Name":       row.Name,
			"ServiceID":  row.ID,
			"PoolID":     row.PoolID,
			"DepID/Path": svcpath(&row),
		})
	}
	t.Print()
	return nil, 0, fmt.Errorf("multiple results found; select one from list")
}
1333314
func (a *Application) ServiceInfo() (CloudService, error) {
	svc, err := a.st.CloudService(a.Name())
	if err != nil {
		return CloudService{}, errors.Trace(err)
	}
	return *svc, nil
}
550839
func (k *kubernetesClient) GetService(appName string, includeClusterIP bool) (*caas.Service, error) {
	services := k.client().CoreV1().Services(k.namespace)
	servicesList, err := services.List(v1.ListOptions{
		LabelSelector:        applicationSelector(appName),
		IncludeUninitialized: true,
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	var result caas.Service
	// We may have the stateful set or deployment but service not done yet.
	if len(servicesList.Items) > 0 {
		service := servicesList.Items[0]
		result.Id = string(service.GetUID())
		result.Addresses = getSvcAddresses(&service, includeClusterIP)
	}

	deploymentName := k.deploymentName(appName)
	statefulsets := k.client().AppsV1().StatefulSets(k.namespace)
	ss, err := statefulsets.Get(deploymentName, v1.GetOptions{})
	if err == nil {
		if ss.Spec.Replicas != nil {
			scale := int(*ss.Spec.Replicas)
			result.Scale = &scale
		}
		message, ssStatus, err := k.getStatefulSetStatus(ss)
		if err != nil {
			return nil, errors.Annotatef(err, "getting status for %s", ss.Name)
		}
		result.Status = status.StatusInfo{
			Status:  ssStatus,
			Message: message,
		}
		return &result, nil
	}
	if !k8serrors.IsNotFound(err) {
		return nil, errors.Trace(err)
	}

	deployments := k.client().AppsV1().Deployments(k.namespace)
	deployment, err := deployments.Get(deploymentName, v1.GetOptions{})
	if err != nil && !k8serrors.IsNotFound(err) {
		return nil, errors.Trace(err)
	}
	if err == nil {
		if deployment.Spec.Replicas != nil {
			scale := int(*deployment.Spec.Replicas)
			result.Scale = &scale
		}
		message, ssStatus, err := k.getDeploymentStatus(deployment)
		if err != nil {
			return nil, errors.Annotatef(err, "getting status for %s", ss.Name)
		}
		result.Status = status.StatusInfo{
			Status:  ssStatus,
			Message: message,
		}
	}

	return &result, nil
}
93459
func newAWSInstance(ec2Service EC2, instance *ec2.Instance) *awsInstance {
	az := ""
	if instance.Placement != nil {
		az = aws.StringValue(instance.Placement.AvailabilityZone)
	}
	self := &awsInstance{
		ec2:              ec2Service,
		awsID:            aws.StringValue(instance.InstanceId),
		nodeName:         mapInstanceToNodeName(instance),
		availabilityZone: az,
		instanceType:     aws.StringValue(instance.InstanceType),
		vpcID:            aws.StringValue(instance.VpcId),
		subnetID:         aws.StringValue(instance.SubnetId),
	}

	return self
}
14438
func (s *ServiceCache) findHost(host string, port int, local bool) interface{} {
	hostCache := s.remoteHosts
	if local {
		hostCache = s.localHosts
	}

	entries, ok := hostCache[host]
	if !ok {
		return nil
	}
	for _, e := range entries {
		if e.ports.IsIncluded(port) {
			return e.data
		}
	}

	return nil
}
638928
func (client *Client) GetServiceInstanceSharedTos(serviceInstanceGUID string) ([]ServiceInstanceSharedTo, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetServiceInstanceSharedToRequest,
		URIParams:   Params{"service_instance_guid": serviceInstanceGUID},
	})

	if err != nil {
		return nil, nil, err
	}

	var fullSharedToList []ServiceInstanceSharedTo
	warnings, err := client.paginate(request, ServiceInstanceSharedTo{}, func(item interface{}) error {
		if instance, ok := item.(ServiceInstanceSharedTo); ok {
			fullSharedToList = append(fullSharedToList, instance)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   ServiceInstanceSharedTo{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullSharedToList, warnings, err
}
433486
func Service(
	apiVersion string,
	namespace Namespace,
	service composetypes.ServiceConfig,
	networkConfigs map[string]composetypes.NetworkConfig,
	volumes map[string]composetypes.VolumeConfig,
	secrets []*swarm.SecretReference,
	configs []*swarm.ConfigReference,
) (swarm.ServiceSpec, error) {
	name := namespace.Scope(service.Name)

	endpoint, err := convertEndpointSpec(service.Deploy.EndpointMode, service.Ports)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	mounts, err := Volumes(service.Volumes, volumes, namespace)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	resources, err := convertResources(service.Deploy.Resources)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	restartPolicy, err := convertRestartPolicy(
		service.Restart, service.Deploy.RestartPolicy)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	healthcheck, err := convertHealthcheck(service.HealthCheck)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	networks, err := convertServiceNetworks(service.Networks, networkConfigs, namespace, service.Name)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	dnsConfig, err := convertDNSConfig(service.DNS, service.DNSSearch)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	var privileges swarm.Privileges
	privileges.CredentialSpec, err = convertCredentialSpec(
		namespace, service.CredentialSpec, configs,
	)
	if err != nil {
		return swarm.ServiceSpec{}, err
	}

	var logDriver *swarm.Driver
	if service.Logging != nil {
		logDriver = &swarm.Driver{
			Name:    service.Logging.Driver,
			Options: service.Logging.Options,
		}
	}

	serviceSpec := swarm.ServiceSpec{
		Annotations: swarm.Annotations{
			Name:   name,
			Labels: AddStackLabel(namespace, service.Deploy.Labels),
		},
		TaskTemplate: swarm.TaskSpec{
			ContainerSpec: &swarm.ContainerSpec{
				Image:           service.Image,
				Command:         service.Entrypoint,
				Args:            service.Command,
				Hostname:        service.Hostname,
				Hosts:           convertExtraHosts(service.ExtraHosts),
				DNSConfig:       dnsConfig,
				Healthcheck:     healthcheck,
				Env:             sortStrings(convertEnvironment(service.Environment)),
				Labels:          AddStackLabel(namespace, service.Labels),
				Dir:             service.WorkingDir,
				User:            service.User,
				Mounts:          mounts,
				StopGracePeriod: composetypes.ConvertDurationPtr(service.StopGracePeriod),
				StopSignal:      service.StopSignal,
				TTY:             service.Tty,
				OpenStdin:       service.StdinOpen,
				Secrets:         secrets,
				Configs:         configs,
				ReadOnly:        service.ReadOnly,
				Privileges:      &privileges,
				Isolation:       container.Isolation(service.Isolation),
				Init:            service.Init,
				Sysctls:         service.Sysctls,
			},
			LogDriver:     logDriver,
			Resources:     resources,
			RestartPolicy: restartPolicy,
			Placement: &swarm.Placement{
				Constraints: service.Deploy.Placement.Constraints,
				Preferences: getPlacementPreference(service.Deploy.Placement.Preferences),
				MaxReplicas: service.Deploy.Placement.MaxReplicas,
			},
		},
		EndpointSpec:   endpoint,
		Mode:           mode,
		UpdateConfig:   convertUpdateConfig(service.Deploy.UpdateConfig),
		RollbackConfig: convertUpdateConfig(service.Deploy.RollbackConfig),
	}

	// add an image label to serviceSpec
	serviceSpec.Labels[LabelImage] = service.Image

	// ServiceSpec.Networks is deprecated and should not have been used by
	// this package. It is possible to update TaskTemplate.Networks, but it
	// is not possible to update ServiceSpec.Networks. Unfortunately, we
	// can't unconditionally start using TaskTemplate.Networks, because that
	// will break with older daemons that don't support migrating from
	// ServiceSpec.Networks to TaskTemplate.Networks. So which field to use
	// is conditional on daemon version.
	if versions.LessThan(apiVersion, "1.29") {
		serviceSpec.Networks = networks
	} else {
		serviceSpec.TaskTemplate.Networks = networks
	}
	return serviceSpec, nil
}
518820
func (s *StoreToEndpointsLister) GetServiceEndpoints(svc *api.Service) (ep api.Endpoints, err error) {
	for _, m := range s.Store.List() {
		ep = *m.(*api.Endpoints)
		if svc.Name == ep.Name && svc.Namespace == ep.Namespace {
			return ep, nil
		}
	}
	err = fmt.Errorf("could not find endpoints for service: %v", svc.Name)
	return
}
115041
func GetServiceStateHostID(conn client.Connection, poolID, serviceID string, instanceID int) (string, error) {
	logger := plog.WithFields(log.Fields{
		"serviceid":  serviceID,
		"instanceid": instanceID,
	})

	basepth := "/"
	if poolID != "" {
		basepth = path.Join("/pools", poolID)
	}

	spth := path.Join(basepth, "/services", serviceID)
	ch, err := conn.Children(spth)
	if err != nil && err != client.ErrNoNode {

		logger.WithError(err).Debug("Could not look up states on service")

		// TODO: wrap the error?
		return "", err
	}

	// find the matching state id
	suffix := fmt.Sprintf("-%s-%d", serviceID, instanceID)
	for _, stateID := range ch {
		if strings.HasSuffix(stateID, suffix) {
			hostID, _, _, err := ParseStateID(stateID)
			if err != nil {
				// This should never happen, but handle it anyway
				logger.WithField("stateid", stateID).WithError(err).Debug("Could not parse state")
				return "", err
			}
			logger.WithField("hostid", hostID).Debug("Found state id")
			return hostID, nil
		}
	}

	return "", ErrInstanceNotFound
}
276848
func (sp *ServiceProvider) GetSSOBindingLocation(binding string) string {
	for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors {
		for _, singleSignOnService := range idpSSODescriptor.SingleSignOnServices {
			if singleSignOnService.Binding == binding {
				return singleSignOnService.Location
			}
		}
	}
	return ""
}
35569
func (svc *Service) PortForServicePort(findPort int64, pType string) int64 {
	for _, port := range svc.Ports {
		if port.ServicePort == findPort && port.Type == pType {
			return port.Port
		}
	}

	log.Warnf("Unable to find ServicePort %d for service %s", findPort, svc.ID)
	return -1
}
1159176
func BuildServiceEndpoint(epd servicedefinition.EndpointDefinition) ServiceEndpoint {
	sep := ServiceEndpoint{}
	sep.Name = epd.Name
	sep.Purpose = epd.Purpose
	sep.Protocol = epd.Protocol
	sep.PortNumber = epd.PortNumber
	sep.PortTemplate = epd.PortTemplate
	sep.VirtualAddress = epd.VirtualAddress
	sep.Application = epd.Application
	sep.ApplicationTemplate = epd.ApplicationTemplate
	sep.AddressConfig = epd.AddressConfig
	sep.VHosts = epd.VHosts
	sep.VHostList = epd.VHostList
	sep.PortList = epd.PortList

	// run public ports through scrubber to allow for "almost correct" port addresses
	for index, port := range sep.PortList {
		sep.PortList[index].PortAddr = ScrubPortString(port.PortAddr)
	}
	return sep
}
1007222
func (sct *ServiceChangeTracker) serviceToServiceMap(service *v1.Service) ServiceMap {
	if service == nil {
		return nil
	}
	svcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
	if utilproxy.ShouldSkipService(svcName, service) {
		return nil
	}

	if len(service.Spec.ClusterIP) != 0 {
		// Filter out the incorrect IP version case.
		// If ClusterIP on service has incorrect IP version, service itself will be ignored.
		if sct.isIPv6Mode != nil && utilnet.IsIPv6String(service.Spec.ClusterIP) != *sct.isIPv6Mode {
			utilproxy.LogAndEmitIncorrectIPVersionEvent(sct.recorder, "clusterIP", service.Spec.ClusterIP, service.Namespace, service.Name, service.UID)
			return nil
		}
	}

	serviceMap := make(ServiceMap)
	for i := range service.Spec.Ports {
		servicePort := &service.Spec.Ports[i]
		svcPortName := ServicePortName{NamespacedName: svcName, Port: servicePort.Name}
		baseSvcInfo := sct.newBaseServiceInfo(servicePort, service)
		if sct.makeServiceInfo != nil {
			serviceMap[svcPortName] = sct.makeServiceInfo(servicePort, service, baseSvcInfo)
		} else {
			serviceMap[svcPortName] = baseSvcInfo
		}
	}
	return serviceMap
}
784974
func (d *Disco) DiscoverServiceURL(hostname svchost.Hostname, serviceID string) (*url.URL, error) {
	host, err := d.Discover(hostname)
	if err != nil {
		return nil, err
	}
	return host.ServiceURL(serviceID)
}
328534
func findPortForService(svcPort string, svc *service.Service) string {
	matchPort, err := strconv.ParseInt(svcPort, 10, 64)
	if err != nil {
		log.Errorf("Invalid value from template ('%s') can't parse as int64: %s", svcPort, err.Error())
		return "-1"
	}

	for _, port := range svc.Ports {
		if port.ServicePort == matchPort {
			internalPort := strconv.FormatInt(port.Port, 10)
			return internalPort
		}
	}

	return "-1"
}
1120980
func (device *Device) FindService(serviceType string) []*Service {
	var services []*Service
	device.VisitServices(func(s *Service) {
		if s.ServiceType == serviceType {
			services = append(services, s)
		}
	})
	return services
}