// PodFitsHostPorts checks if a node has free ports for the requested pod ports.
199391
func PodFitsHostPorts(pod *v1.Pod, meta PredicateMetadata, nodeInfo *schedulernodeinfo.NodeInfo) (bool, []PredicateFailureReason, error) {
	var wantPorts []*v1.ContainerPort
	if predicateMeta, ok := meta.(*predicateMetadata); ok {
		wantPorts = predicateMeta.podPorts
	} else {
		// We couldn't parse metadata - fallback to computing it.
		wantPorts = schedutil.GetContainerPorts(pod)
	}
	if len(wantPorts) == 0 {
		return true, nil, nil
	}

	existingPorts := nodeInfo.UsedPorts()

	// try to see whether existingPorts and  wantPorts will conflict or not
	if portsConflict(existingPorts, wantPorts) {
		return false, []PredicateFailureReason{ErrPodNotFitsHostPorts}, nil
	}

	return true, nil, nil
}
474042
func (s *simpleProvider) isValidHostPort(port int32) bool {
	for _, hostPortRange := range s.psp.Spec.HostPorts {
		if port >= hostPortRange.Min && port <= hostPortRange.Max {
			return true
		}
	}
	return false
}
575772
func (w *pgWorker) apiServerHostPorts() map[string][]network.HostPort {
	servers := make(map[string][]network.HostPort)
	for _, m := range w.machineTrackers {
		hostPorts := network.AddressesWithPort(m.Addresses(), w.config.APIPort)
		if len(hostPorts) == 0 {
			continue
		}
		servers[m.Id()] = hostPorts
	}
	return servers
}
1079115
func defaultHostNetworkPorts(containers *[]Container) {
	for i := range *containers {
		for j := range (*containers)[i].Ports {
			if (*containers)[i].Ports[j].HostPort == 0 {
				(*containers)[i].Ports[j].HostPort = (*containers)[i].Ports[j].ContainerPort
			}
		}
	}
}
1224987
func portFromHostContainer(hostContainer string) (p Port, err error) {
	var host, container int
	parts := strings.SplitN(hostContainer, ":", 2)
	host, err = toPort(parts[0])
	if err != nil {
		return
	}
	container, err = toPort(parts[1])
	if err != nil {
		return
	}

	p.Host = host
	p.Container = container
	return
}
428470
func (hp *hostPort) networkHostPort() network.HostPort {
	return network.HostPort{
		Address: network.Address{
			Value:     hp.Value,
			Type:      network.AddressType(hp.AddressType),
			Scope:     network.Scope(hp.Scope),
			SpaceName: network.SpaceName(hp.SpaceName),
		},
		Port: hp.Port,
	}
}
116774
func constructPodPortMapping(pod *corev1.Pod, podIP net.IP) *kubehostport.PodPortMapping {
	portMappings := make([]*kubehostport.PortMapping, 0)
	for _, c := range pod.Spec.Containers {
		for _, port := range c.Ports {
			portMappings = append(portMappings, &kubehostport.PortMapping{
				Name:          port.Name,
				HostPort:      port.HostPort,
				ContainerPort: port.ContainerPort,
				Protocol:      port.Protocol,
				HostIP:        port.HostIP,
			})
		}
	}

	return &kubehostport.PodPortMapping{
		Namespace:    pod.Namespace,
		Name:         pod.Name,
		PortMappings: portMappings,
		HostNetwork:  pod.Spec.HostNetwork,
		IP:           podIP,
	}
}
37647
func (f *HostPortFilter) Check(n *NodeInfo) bool {
	for _, port := range f.t.Endpoint.Ports {
		if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
			portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort}
			if _, ok := n.usedHostPorts[portSpec]; ok {
				return false
			}
		}
	}

	return true
}
689311
func (st *State) APIHostPortsForClients() ([][]network.HostPort, error) {
	isCAASCtrl, err := st.isCAASController()
	if err != nil {
		return nil, errors.Trace(err)
	}
	if isCAASCtrl {
		// TODO(caas): add test for this once we have the replacement for Jujuconnsuite.
		return st.apiHostPortsForCAAS(true)
	}

	hp, err := st.apiHostPortsForKey(apiHostPortsKey)
	if err != nil {
		err = errors.Trace(err)
	}
	return hp, err
}
785901
func networkHostsPorts(hsps [][]hostPort) [][]network.HostPort {
	netHostsPorts := make([][]network.HostPort, len(hsps))
	for i, hps := range hsps {
		netHostsPorts[i] = make([]network.HostPort, len(hps))
		for j, hp := range hps {
			netHostsPorts[i][j] = hp.networkHostPort()
		}
	}
	return netHostsPorts
}
1193038
func (h *hostportSyncer) SyncHostports(natInterfaceName string, activePodPortMappings []*PodPortMapping) error {
	start := time.Now()
	defer func() {
		klog.V(4).Infof("syncHostportsRules took %v", time.Since(start))
	}()

	hostportPodMap, err := gatherAllHostports(activePodPortMappings)
	if err != nil {
		return err
	}

	// Ensure KUBE-HOSTPORTS chains
	ensureKubeHostportChains(h.iptables, natInterfaceName)

	// Get iptables-save output so we can check for existing chains and rules.
	// This will be a map of chain name to chain with rules as stored in iptables-save/iptables-restore
	existingNATChains := make(map[utiliptables.Chain][]byte)
	iptablesData := bytes.NewBuffer(nil)
	err = h.iptables.SaveInto(utiliptables.TableNAT, iptablesData)
	if err != nil { // if we failed to get any rules
		klog.Errorf("Failed to execute iptables-save, syncing all rules: %v", err)
	} else { // otherwise parse the output
		existingNATChains = utiliptables.GetChainLines(utiliptables.TableNAT, iptablesData.Bytes())
	}

	natChains := bytes.NewBuffer(nil)
	natRules := bytes.NewBuffer(nil)
	writeLine(natChains, "*nat")
	// Make sure we keep stats for the top-level chains, if they existed
	// (which most should have because we created them above).
	if chain, ok := existingNATChains[kubeHostportsChain]; ok {
		writeBytesLine(natChains, chain)
	} else {
		writeLine(natChains, utiliptables.MakeChainLine(kubeHostportsChain))
	}

	// Accumulate NAT chains to keep.
	activeNATChains := map[utiliptables.Chain]bool{} // use a map as a set

	for port, target := range hostportPodMap {
		protocol := strings.ToLower(string(port.Protocol))
		hostportChain := hostportChainName(port, target.podFullName)
		if chain, ok := existingNATChains[hostportChain]; ok {
			writeBytesLine(natChains, chain)
		} else {
			writeLine(natChains, utiliptables.MakeChainLine(hostportChain))
		}

		activeNATChains[hostportChain] = true

		// Redirect to hostport chain
		args := []string{
			"-A", string(kubeHostportsChain),
			"-m", "comment", "--comment", fmt.Sprintf(`"%s hostport %d"`, target.podFullName, port.HostPort),
			"-m", protocol, "-p", protocol,
			"--dport", fmt.Sprintf("%d", port.HostPort),
			"-j", string(hostportChain),
		}
		writeLine(natRules, args...)

		// Assuming kubelet is syncing iptables KUBE-MARK-MASQ chain
		// If the request comes from the pod that is serving the hostport, then SNAT
		args = []string{
			"-A", string(hostportChain),
			"-m", "comment", "--comment", fmt.Sprintf(`"%s hostport %d"`, target.podFullName, port.HostPort),
			"-s", target.podIP, "-j", string(iptablesproxy.KubeMarkMasqChain),
		}
		writeLine(natRules, args...)

		// Create hostport chain to DNAT traffic to final destination
		// IPTables will maintained the stats for this chain
		args = []string{
			"-A", string(hostportChain),
			"-m", "comment", "--comment", fmt.Sprintf(`"%s hostport %d"`, target.podFullName, port.HostPort),
			"-m", protocol, "-p", protocol,
			"-j", "DNAT", fmt.Sprintf("--to-destination=%s:%d", target.podIP, port.ContainerPort),
		}
		writeLine(natRules, args...)
	}

	// Delete chains no longer in use.
	for chain := range existingNATChains {
		if !activeNATChains[chain] {
			chainString := string(chain)
			if !strings.HasPrefix(chainString, kubeHostportChainPrefix) {
				// Ignore chains that aren't ours.
				continue
			}
			// We must (as per iptables) write a chain-line for it, which has
			// the nice effect of flushing the chain.  Then we can remove the
			// chain.
			writeBytesLine(natChains, existingNATChains[chain])
			writeLine(natRules, "-X", chainString)
		}
	}
	writeLine(natRules, "COMMIT")

	natLines := append(natChains.Bytes(), natRules.Bytes()...)
	klog.V(3).Infof("Restoring iptables rules: %s", natLines)
	err = h.iptables.RestoreAll(natLines, utiliptables.NoFlushTables, utiliptables.RestoreCounters)
	if err != nil {
		return fmt.Errorf("Failed to execute iptables-restore: %v", err)
	}

	h.cleanupHostportMap(hostportPodMap)
	return nil
}
848418
func (r *ringDescriber) GetHosts() ([]*HostInfo, string, error) {
	r.mu.Lock()
	defer r.mu.Unlock()

	hosts, err := r.getClusterPeerInfo()
	if err != nil {
		return r.prevHosts, r.prevPartitioner, err
	}

	var partitioner string
	if len(hosts) > 0 {
		partitioner = hosts[0].Partitioner()
	}

	return hosts, partitioner, nil
}
105869
func (h *hostportSyncer) OpenPodHostportsAndSync(newPortMapping *PodPortMapping, natInterfaceName string, activePodPortMappings []*PodPortMapping) error {
	// try to open pod host port if specified
	if err := h.openHostports(newPortMapping); err != nil {
		return err
	}

	// Add the new pod to active pods if it's not present.
	var found bool
	for _, pm := range activePodPortMappings {
		if pm.Namespace == newPortMapping.Namespace && pm.Name == newPortMapping.Name {
			found = true
			break
		}
	}
	if !found {
		activePodPortMappings = append(activePodPortMappings, newPortMapping)
	}

	return h.SyncHostports(natInterfaceName, activePodPortMappings)
}
67694
func (s *ServerRPC) PodStats(c context.Context, req *types.PodStatsRequest) (*types.PodStatsResponse, error) {
	statsObject, err := s.daemon.GetPodStats(req.PodID)
	if err != nil {
		return nil, err
	}

	stats := statsObject.(*runvtypes.PodStats)

	return &types.PodStatsResponse{
		PodStats: convertRunvStatsToGrpcTypes(stats),
	}, nil
}
1035667
func (e *PodEndpoint) SetHostPort(port int) *PodEndpoint {
	e.HostPort = port
	return e
}
912228
func NewPodAffinityPredicate(info NodeInfo, podLister algorithm.PodLister) FitPredicate {
	checker := &PodAffinityChecker{
		info:      info,
		podLister: podLister,
	}
	return checker.InterPodAffinityMatches
}
458286
func gatherAllHostports(activePodPortMappings []*PodPortMapping) (map[*PortMapping]targetPod, error) {
	podHostportMap := make(map[*PortMapping]targetPod)
	for _, pm := range activePodPortMappings {
		if pm.IP.To4() == nil {
			return nil, fmt.Errorf("Invalid or missing pod %s IP", getPodFullName(pm))
		}
		// should not handle hostports for hostnetwork pods
		if pm.HostNetwork {
			continue
		}

		for _, port := range pm.PortMappings {
			if port.HostPort != 0 {
				podHostportMap[port] = targetPod{podFullName: getPodFullName(pm), podIP: pm.IP.String()}
			}
		}
	}
	return podHostportMap, nil
}