// addServiceOnPortInternal starts listening for a new service, returning the ServiceInfo.
// Pass proxyPort=0 to allocate a random port. The timeout only applies to UDP
// connections, for now.
497557
func (proxier *Proxier) addServiceOnPortInternal(service proxy.ServicePortName, protocol v1.Protocol, proxyPort int, timeout time.Duration) (*ServiceInfo, error) {
	sock, err := proxier.makeProxySocket(protocol, proxier.listenIP, proxyPort)
	if err != nil {
		return nil, err
	}
	_, portStr, err := net.SplitHostPort(sock.Addr().String())
	if err != nil {
		sock.Close()
		return nil, err
	}
	portNum, err := strconv.Atoi(portStr)
	if err != nil {
		sock.Close()
		return nil, err
	}
	si := &ServiceInfo{
		Timeout:             timeout,
		ActiveClients:       newClientCache(),
		isAliveAtomic:       1,
		proxyPort:           portNum,
		protocol:            protocol,
		socket:              sock,
		sessionAffinityType: v1.ServiceAffinityNone, // default
	}
	proxier.serviceMap[service] = si

	klog.V(2).Infof("Proxying for service %q on %s port %d", service, protocol, portNum)
	go func(service proxy.ServicePortName, proxier *Proxier) {
		defer runtime.HandleCrash()
		atomic.AddInt32(&proxier.numProxyLoops, 1)
		sock.ProxyLoop(service, si, proxier.loadBalancer)
		atomic.AddInt32(&proxier.numProxyLoops, -1)
	}(service, proxier)

	return si, nil
}
1212231
func (state *ServicesState) AddServiceEntry(newSvc service.Service) {
	defer metrics.MeasureSince([]string{"services_state", "AddServiceEntry"}, time.Now())

	state.Lock()
	defer state.Unlock()

	if !state.HasServer(newSvc.Hostname) {
		state.Servers[newSvc.Hostname] = NewServer(newSvc.Hostname)
	}

	server := state.Servers[newSvc.Hostname]

	// Only apply changes that are newer or services are missing
	if !server.HasService(newSvc.ID) {
		server.Services[newSvc.ID] = &newSvc
		state.ServiceChanged(&newSvc, service.UNKNOWN, newSvc.Updated)
		state.retransmit(newSvc)
	} else if newSvc.Invalidates(server.Services[newSvc.ID]) {
		// We have to set these even if the status did not change
		server.LastUpdated = newSvc.Updated

		// Store the previous newSvc so we can compare it
		oldEntry := server.Services[newSvc.ID]

		// Update the new one
		server.Services[newSvc.ID] = &newSvc

		// When the status changes, the SeviceChanged() method will
		// update all the accounting fields in the state and Server newSvc.
		if oldEntry.Status != newSvc.Status {
			state.ServiceChanged(&newSvc, oldEntry.Status, newSvc.Updated)
		}

		// We tell our gossip peers about the updated service
		// by sending them the record. We're saved from an endless
		// retransmit loop by the Invalidates() call above.
		state.retransmit(newSvc)
	}
}
996737
func (gce *Cloud) AddPortToInstanceGroup(ig *compute.InstanceGroup, port int64) (*compute.NamedPort, error) {
	for _, np := range ig.NamedPorts {
		if np.Port == port {
			glog.V(3).Infof("Instance group %v already has named port %+v", ig.Name, np)
			return np, nil
		}
	}
	glog.Infof("Adding port %v to instance group %v with %d ports", port, ig.Name, len(ig.NamedPorts))
	namedPort := compute.NamedPort{Name: fmt.Sprintf("port%v", port), Port: port}
	ig.NamedPorts = append(ig.NamedPorts, &namedPort)

	// setNamedPorts is a zonal endpoint, meaning we invoke it by re-creating a URL like:
	// {project}/zones/{zone}/instanceGroups/{instanceGroup}/setNamedPorts, so the "zone"
	// parameter given to SetNamedPorts must not be the entire zone URL.
	zoneURLParts := strings.Split(ig.Zone, "/")
	zone := zoneURLParts[len(zoneURLParts)-1]

	op, err := gce.service.InstanceGroups.SetNamedPorts(
		gce.projectID, zone, ig.Name,
		&compute.InstanceGroupsSetNamedPortsRequest{
			NamedPorts: ig.NamedPorts}).Do()
	if err != nil {
		return nil, err
	}
	if err = gce.waitForZoneOp(op, zone); err != nil {
		return nil, err
	}
	return &namedPort, nil
}
350073
func AddServices(objects Objects, firstPortOnly bool) Objects {
	svcs := []runtime.Object{}
	for _, o := range objects {
		switch t := o.(type) {
		case *appsv1.DeploymentConfig:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Selector, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *kappsv1.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *extensionsv1beta1.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		case *kappsv1beta2.DaemonSet:
			svc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)
			if svc != nil {
				svcs = append(svcs, svc)
			}
		}
	}
	return append(objects, svcs...)
}
227438
func (proxier *Proxier) addServicePortPortal(servicePortPortalName ServicePortPortalName, protocol v1.Protocol, listenIP string, port int, timeout time.Duration) (*serviceInfo, error) {
	var serviceIP net.IP
	if listenIP != allAvailableInterfaces {
		if serviceIP = net.ParseIP(listenIP); serviceIP == nil {
			return nil, fmt.Errorf("could not parse ip '%q'", listenIP)
		}
		// add the IP address.  Node port binds to all interfaces.
		args := proxier.netshIpv4AddressAddArgs(serviceIP)
		if existed, err := proxier.netsh.EnsureIPAddress(args, serviceIP); err != nil {
			return nil, err
		} else if !existed {
			klog.V(3).Infof("Added ip address to fowarder interface for service %q at %s/%s", servicePortPortalName, net.JoinHostPort(listenIP, strconv.Itoa(port)), protocol)
		}
	}

	// add the listener, proxy
	sock, err := newProxySocket(protocol, serviceIP, port)
	if err != nil {
		return nil, err
	}
	si := &serviceInfo{
		isAliveAtomic: 1,
		portal: portal{
			ip:         listenIP,
			port:       port,
			isExternal: false,
		},
		protocol:            protocol,
		socket:              sock,
		timeout:             timeout,
		activeClients:       newClientCache(),
		dnsClients:          newDNSClientCache(),
		sessionAffinityType: v1.ServiceAffinityNone, // default
	}
	proxier.setServiceInfo(servicePortPortalName, si)

	klog.V(2).Infof("Proxying for service %q at %s/%s", servicePortPortalName, net.JoinHostPort(listenIP, strconv.Itoa(port)), protocol)
	go func(service ServicePortPortalName, proxier *Proxier) {
		defer runtime.HandleCrash()
		atomic.AddInt32(&proxier.numProxyLoops, 1)
		sock.ProxyLoop(service, si, proxier)
		atomic.AddInt32(&proxier.numProxyLoops, -1)
	}(servicePortPortalName, proxier)

	return si, nil
}
741637
func (db ErroringDB) IsInternalService(c context.Context, hostname string) (bool, error) {
	logging.Errorf(c, "%s", db.Error)
	return false, db.Error
}
504879
func (s *ProxyLBSetting) AddServer(ip string, port int, enabled bool) {
	var record ProxyLBServer
	var isExist = false
	for i := range s.Servers {
		if s.Servers[i].IPAddress == ip && s.Servers[i].Port == port {
			isExist = true
			s.Servers[i].Enabled = enabled
		}
	}

	if !isExist {
		record = ProxyLBServer{
			IPAddress: ip,
			Port:      port,
			Enabled:   enabled,
		}
		s.Servers = append(s.Servers, record)
	}
}
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
}
159096
func (_m *API) AddServiceTemplate(_a0 io.Reader) (*servicetemplate.ServiceTemplate, error) {
	ret := _m.Called(_a0)

	var r0 *servicetemplate.ServiceTemplate
	if rf, ok := ret.Get(0).(func(io.Reader) *servicetemplate.ServiceTemplate); ok {
		r0 = rf(_a0)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*servicetemplate.ServiceTemplate)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(io.Reader) error); ok {
		r1 = rf(_a0)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
406563
func (s *EnvoyApi) EnvoyListenerFromService(svc *service.Service, port int64) *EnvoyListener {
	apiName := SvcName(svc.Name, port)

	listener := &EnvoyListener{
		Name:    apiName,
		Address: fmt.Sprintf("tcp://%s:%d", s.config.BindIP, port),
	}

	if svc.ProxyMode == "http" {
		listener.Filters = []*EnvoyFilter{
			{
				Name: "envoy.http_connection_manager",
				Config: &EnvoyFilterConfig{
					CodecType:  "auto",
					StatPrefix: "ingress_http",
					Filters: []*EnvoyFilter{
						{
							Name:   "router",
							Config: &EnvoyFilterConfig{},
						},
					},
					RouteConfig: &EnvoyRouteConfig{
						VirtualHosts: []*EnvoyHTTPVirtualHost{
							{
								Name:    svc.Name,
								Domains: []string{"*"},
								Routes: []*EnvoyRoute{
									{
										TimeoutMs: 0, // No timeout!
										Prefix:    "/",
										Cluster:   apiName,
									},
								},
							},
						},
					},
				},
			},
		}
	} else { // == "tcp"
		listener.Filters = []*EnvoyFilter{
			{
				Name: "envoy.tcp_proxy",
				Config: &EnvoyFilterConfig{
					StatPrefix: "ingress_tcp",
					RouteConfig: &EnvoyRouteConfig{
						Routes: []*EnvoyTCPRoute{
							{
								Cluster: apiName,
							},
						},
					},
				},
			},
		}
	}

	return listener
}
1359316
func (a *api) AddPublicEndpointPort(serviceid, endpointName, portAddr string, usetls bool,
	protocol string, isEnabled bool, restart bool) (*servicedefinition.Port, error) {
	client, err := a.connectMaster()
	if err != nil {
		return nil, err
	}

	return client.AddPublicEndpointPort(serviceid, endpointName, portAddr, usetls, protocol, isEnabled, restart)
}
900522
func (b *FusisBalancer) AddService(svc *types.Service) error {
	// Allocate a new VIP if no address provided
	if svc.Address == "" {
		if err := b.ipam.AllocateVIP(svc); err != nil {
			return err
		}
	}

	return b.store.AddService(svc)
}
709482
func addService(containers []corev1.Container, objectMeta metav1.ObjectMeta, selector map[string]string, firstPortOnly bool) *corev1.Service {
	ports := UniqueContainerToServicePorts(AllContainerPorts(containers...))
	if len(ports) == 0 {
		return nil
	}
	if firstPortOnly {
		ports = ports[:1]
	}
	svc := GenerateService(objectMeta, selector)
	svc.Spec.Ports = ports
	return svc
}
371653
func addPort(m map[string]string, taskName, ip, portLabel string, port int) {
	key := fmt.Sprintf("%s%s_%s", AddrPrefix, taskName, portLabel)
	m[key] = fmt.Sprintf("%s:%d", ip, port)
	key = fmt.Sprintf("%s%s_%s", IpPrefix, taskName, portLabel)
	m[key] = ip
	key = fmt.Sprintf("%s%s_%s", PortPrefix, taskName, portLabel)
	m[key] = strconv.Itoa(port)
}
301630
func (f *Facade) GetServiceExportedEndpoints(ctx datastore.Context, serviceID string, children bool) ([]service.ExportedEndpoint, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetServiceExportedEndpoints"))

	// get all the exported endpoints and map them to their service
	alleps, err := f.serviceStore.GetAllExportedEndpoints(ctx)
	if err != nil {
		return nil, err
	}
	epmap := make(map[string][]service.ExportedEndpoint)
	for i, ep := range alleps {
		epmap[ep.ServiceID] = append(epmap[ep.ServiceID], alleps[i])
	}

	// get all the endpoints for that service
	result, ok := epmap[serviceID]
	if ok {
		delete(epmap, serviceID)
	}

	if children {
		// get the tenant id and service path to the service in order to find
		// the service's children.
		tenantID, svcPath, err := f.getServicePath(ctx, serviceID)
		if err != nil {
			return nil, err
		}

		for id, eps := range epmap {
			// add the endpoints with the matching tenant id and share the same
			// path prefix.
			tid, spth, err := f.getServicePath(ctx, id)
			if err != nil {
				return nil, err
			}
			if tid == tenantID && strings.HasPrefix(spth, svcPath+"/") {
				result = append(result, eps...)
			}
		}
	}

	return result, nil
}
116024
func (r *Application) AddPortDefinition(portDefinition PortDefinition) *Application {
	if r.PortDefinitions == nil {
		r.EmptyPortDefinitions()
	}

	portDefinitions := *r.PortDefinitions
	portDefinitions = append(portDefinitions, portDefinition)
	r.PortDefinitions = &portDefinitions
	return r
}
1224573
func createPortAndServiceSpec(servicePort int, targetServicePort int, nodePort int, servicePortName string, extraServicePorts []corev1.ServicePort) ([]corev1.ServicePort, corev1.ServiceType) {
	//Use the Cluster IP type for the service port if NodePort isn't provided.
	//Otherwise, we will be binding the master service to a NodePort.
	servicePorts := []corev1.ServicePort{{Protocol: corev1.ProtocolTCP,
		Port:       int32(servicePort),
		Name:       servicePortName,
		TargetPort: intstr.FromInt(targetServicePort)}}
	serviceType := corev1.ServiceTypeClusterIP
	if nodePort > 0 {
		servicePorts[0].NodePort = int32(nodePort)
		serviceType = corev1.ServiceTypeNodePort
	}
	if extraServicePorts != nil {
		servicePorts = append(servicePorts, extraServicePorts...)
	}
	return servicePorts, serviceType
}