// Translates service port to target port
// It rewrites ports as needed if the Service port declares targetPort.
// It returns an error when a named targetPort can't find a match in the pod, or the Service did not declare
// the port.
348294
func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod corev1.Pod) ([]string, error) {
	var translated []string
	for _, port := range ports {
		localPort, remotePort := splitPort(port)

		portnum, err := strconv.Atoi(remotePort)
		if err != nil {
			svcPort, err := util.LookupServicePortNumberByName(svc, remotePort)
			if err != nil {
				return nil, err
			}
			portnum = int(svcPort)

			if localPort == remotePort {
				localPort = strconv.Itoa(portnum)
			}
		}
		containerPort, err := util.LookupContainerPortNumberByServicePort(svc, pod, int32(portnum))
		if err != nil {
			// can't resolve a named port, or Service did not declare this port, return an error
			return nil, err
		}

		if int32(portnum) != containerPort {
			translated = append(translated, fmt.Sprintf("%s:%d", localPort, containerPort))
		} else {
			translated = append(translated, port)
		}
	}
	return translated, nil
}
79999
func hostport_list_from_zk(zc zk.ZK, containers_path, service_port string) ([]interface{}, error) {
	n, err := zk.Follow(zc, registry.Path(containers_path))
	if err != nil {
		return nil, err
	}

	all, err := n.VisitChildrenRecursive(func(z *zk.Node) bool {
		_, port := ParseHostPort(z.GetBasename())
		return port == service_port && z.IsLeaf()
	})
	if err != nil {
		return nil, err
	}

	list := make([]interface{}, 0)
	for _, c := range all {
		host, port := ParseHostPort(c.GetValueString())
		list = append(list, struct {
			Host string
			Port string
		}{
			Host: host,
			Port: port,
		})
	}
	return list, nil
}
1315432
func (p *Port) WriteTo(w io.Writer) (int64, error) {
	name := make([]byte, portNameLen)
	copy(name, []byte(p.Name))

	return encoding.WriteTo(w, p.PortNo, pad4{}, p.HWAddr, pad2{},
		name, p.Config, p.State, p.Curr, p.Advertised, p.Supported,
		p.Peer, p.CurrSpeed, p.MaxSpeed,
	)
}
470952
func (proxier *Proxier) ensurePortals() {
	// NB: This does not remove rules that should not be present.
	for name, info := range proxier.serviceMap {
		err := proxier.openPortal(name, info)
		if err != nil {
			klog.Errorf("Failed to ensure portal for %q: %v", name, err)
		}
	}
}
319959
func (s *Service) AddPort(application string, portAddr string, usetls bool, protocol string, isEnabled bool) (*servicedefinition.Port, error) {
	portAddr = ScrubPortString(portAddr)
	if s.Endpoints != nil {
		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				var ports = make([]servicedefinition.Port, 0)
				portAddrLower := strings.ToLower(portAddr)
				for _, port := range ep.PortList {
					if strings.ToLower(port.PortAddr) != portAddrLower {
						ports = append(ports, port)
					}
				}
				port := &servicedefinition.Port{PortAddr: portAddr, Enabled: isEnabled, UseTLS: usetls, Protocol: protocol}
				ep.PortList = append(ports, *port)
				return port, nil
			}
		}
	}

	return nil, fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}
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
}
83760
func (lxd *lxdInstance) OpenPorts(ctx context.ProviderCallContext, machineId string, rules []network.IngressRule) error {
	return fmt.Errorf("not implemented")
}
582458
func findAppPort(manifest *schema.PodManifest, portName types.ACName) (*types.Port, error) {
	var foundPort *types.Port

	for _, app := range manifest.Apps {
		for _, port := range app.App.Ports {
			if portName == port.Name {
				if foundPort != nil { // error: ambiguous
					return nil, fmt.Errorf("port name %q defined multiple apps", portName)
				}
				p := port // duplicate b/c port gets overwritten
				foundPort = &p
			}
		}
	}
	return foundPort, nil
}
824401
func buildPortFor(port *docker.APIPort, container *docker.APIContainers, ip string) Port {
	// We look up service port labels by convention in the format "ServicePort_80=8080"
	svcPortLabel := fmt.Sprintf("ServicePort_%d", port.PrivatePort)

	// You can override the default IP by binding your container on a specific IP
	if port.IP != "0.0.0.0" && port.IP != "" {
		ip = port.IP
	}

	returnPort := Port{Port: port.PublicPort, Type: port.Type, IP: ip}

	if svcPort, ok := container.Labels[svcPortLabel]; ok {
		svcPortInt, err := strconv.Atoi(svcPort)
		if err != nil {
			log.Errorf("Error converting label value for %s to integer: %s",
				svcPortLabel,
				err.Error(),
			)
			return returnPort
		}

		// Everything was good, set the service port
		returnPort.ServicePort = int64(svcPortInt)
	}

	return returnPort
}
1015687
func (sc *ServiceCheck) RequiresPort() bool {
	switch sc.Type {
	case ServiceCheckGRPC, ServiceCheckHTTP, ServiceCheckTCP:
		return true
	default:
		return false
	}
}
1315519
func (container *Container) ServicePortIndex(port int) (int, error) {
	if container.PortMappings == nil || len(*container.PortMappings) == 0 {
		return 0, errors.New("The container does not contain any port mappings to search")
	}

	// step: iterate and find the port
	for index, containerPort := range *container.PortMappings {
		if containerPort.ContainerPort == port {
			return index, nil
		}
	}

	// step: we didn't find the port in the mappings
	return 0, fmt.Errorf("The container port %d was not found in the container port mappings", port)
}
850239
func (ds *dockerService) PortForward(_ context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {
	if ds.streamingServer == nil {
		return nil, streaming.NewErrorStreamingDisabled("port forward")
	}
	_, err := checkContainerStatus(ds.client, req.PodSandboxId)
	if err != nil {
		return nil, err
	}
	// TODO(tallclair): Verify that ports are exposed.
	return ds.streamingServer.GetPortForward(req)
}
184142
func (a *NetAddr) Port(defaultPort int) int {
	_, port, err := net.SplitHostPort(a.Addr)
	if err != nil {
		return defaultPort
	}
	porti, err := strconv.Atoi(port)
	if err != nil {
		return defaultPort
	}
	return porti
}
448282
func getListenerForPort(existingListeners []listeners.Listener, port v1.ServicePort) *listeners.Listener {
	for _, l := range existingListeners {
		if listeners.Protocol(l.Protocol) == toListenersProtocol(port.Protocol) && l.ProtocolPort == int(port.Port) {
			return &l
		}
	}

	return nil
}
1004465
func (c *Client) UsePort(port int) error {
	_, err := c.ExecCmd(NewCmd("use").WithArgs(NewArg("port", port)))
	return err
}
1172382
func (pf *PortForwarder) listenOnPort(port *ForwardedPort) error {
	var errors []error
	failCounters := make(map[string]int, 2)
	successCounters := make(map[string]int, 2)
	for _, addr := range pf.addresses {
		err := pf.listenOnPortAndAddress(port, addr.protocol, addr.address)
		if err != nil {
			errors = append(errors, err)
			failCounters[addr.failureMode]++
		} else {
			successCounters[addr.failureMode]++
		}
	}
	if successCounters["all"] == 0 && failCounters["all"] > 0 {
		return fmt.Errorf("%s: %v", "Listeners failed to create with the following errors", errors)
	}
	if failCounters["any"] > 0 {
		return fmt.Errorf("%s: %v", "Listeners failed to create with the following errors", errors)
	}
	return nil
}
403969
func (s *ServiceCache) addPorts(e *common.Service, record *entry, local bool) error {
	if !local {
		return nil
	}

	for _, spec := range s.localPorts {
		if spec.ports.Overlaps(e.Ports) {
			return fmt.Errorf("service port overlap in the global port list: %+v %s", e.Addresses, e.Ports.String())
		}
	}

	s.localPorts = append(s.localPorts, record)

	return nil
}