// reserveSpecificPort tries to reserve the given port on all given protocols.
430795
func (s *PortManager) reserveSpecificPort(networks []tcpip.NetworkProtocolNumber, transport tcpip.TransportProtocolNumber, addr tcpip.Address, port uint16, reuse bool) bool {
	if !s.isPortAvailableLocked(networks, transport, addr, port, reuse) {
		return false
	}

	// Reserve port on all network protocols.
	for _, network := range networks {
		desc := portDescriptor{network, transport, port}
		m, ok := s.allocatedPorts[desc]
		if !ok {
			m = make(bindAddresses)
			s.allocatedPorts[desc] = m
		}
		if n, ok := m[addr]; ok {
			n.refs++
			m[addr] = n
		} else {
			m[addr] = portNode{reuse: reuse, refs: 1}
		}
	}

	return true
}
849565
func (u *Unit) ClosePorts(protocol string, fromPort, toPort int) error {
	var result params.ErrorResults
	args := params.EntitiesPortRanges{
		Entities: []params.EntityPortRange{{
			Tag:      u.tag.String(),
			Protocol: protocol,
			FromPort: fromPort,
			ToPort:   toPort,
		}},
	}
	err := u.st.facade.FacadeCall("ClosePorts", args, &result)
	if err != nil {
		return err
	}
	return result.OneError()
}
607556
func (a *IPRangeAllocator) Reserve(ip net.IP) {
	a.mutex.Lock()
	defer a.mutex.Unlock()

	// ensure the specified IP is within the range
	if !a.ipRange.Contains(ip) {
		return
	}

	// calculate the idx from the start
	ipBig := big.NewInt(0)
	ipBig.SetBytes(ip)
	idx := ipBig.Sub(ipBig, a.startBig).Int64()

	// if it isn't already reserved, then mark it reserved and decrement the
	// remaining count
	if !a.reserved[idx] {
		a.reserved[idx] = true
		a.remaining--
	}
}
1186790
func reserve(dst []byte, nbytes int) []byte {
	c := cap(dst)
	n := len(dst)

	if avail := c - n; avail < nbytes {
		c *= 2
		if (c - n) < nbytes {
			c = n + nbytes
		}
		b := make([]byte, n, c)
		copy(b, dst)
		dst = b
	}

	return dst
}
442639
func (s *DescribeReservationOutput) SetResourceSpecification(v *ReservationResourceSpecification) *DescribeReservationOutput {
	s.ResourceSpecification = v
	return s
}
1106147
func (m *Maestro) GetSpecificHost(service string, container string) (string, error) {
	envKey := fmt.Sprintf("%s_%s_HOST", m.toEnvVarName(service), m.toEnvVarName(container))
	envVal := m.osGetenv(envKey)
	if envVal == "" {
		return "", ErrNoSpecificHostDefined
	}
	return envVal, nil
}
702398
func (p *TreePool) reserve() *tree {
	p.lock.Lock()
	defer p.lock.Unlock()
	var t *tree
	if p.count == p.Capacity {
		return <-p.c
	}
	select {
	case t = <-p.c:
	default:
		t = newTree(p.SegmentSize, p.Depth, p.hasher)
		p.count++
	}
	return t
}
1177495
func (s *SetLoadBalancerListenerSSLCertificateInput) SetLoadBalancerPort(v int64) *SetLoadBalancerListenerSSLCertificateInput {
	s.LoadBalancerPort = &v
	return s
}
662828
func portsConflict(existingPorts schedulernodeinfo.HostPortInfo, wantPorts []*v1.ContainerPort) bool {
	for _, cp := range wantPorts {
		if existingPorts.CheckConflict(cp.HostIP, string(cp.Protocol), cp.HostPort) {
			return true
		}
	}

	return false
}
294355
func (c *ContainerServer) ReservePodName(id, name string) (string, error) {
	if err := c.podNameIndex.Reserve(name, id); err != nil {
		err = fmt.Errorf("error reserving pod name %s for id %s", name, id)
		logrus.Warn(err)
		return "", err
	}
	return name, nil
}
448399
func (d *FsDevice) Reserve(deviceIDs []string) (*device.ContainerReservation, error) {
	if len(deviceIDs) == 0 {
		return nil, status.New(codes.InvalidArgument, "no device ids given").Err()
	}

	deviceDir, err := filepath.Abs(d.deviceDir)
	if err != nil {
		return nil, status.Newf(codes.Internal, "failed to load device dir abs path").Err()
	}

	resp := &device.ContainerReservation{}

	for _, id := range deviceIDs {
		// Check if the device is known
		if _, ok := d.devices[id]; !ok {
			return nil, status.Newf(codes.InvalidArgument, "unknown device %q", id).Err()
		}

		// Add a mount
		resp.Mounts = append(resp.Mounts, &device.Mount{
			TaskPath: fmt.Sprintf("/tmp/task-mounts/%s", id),
			HostPath: filepath.Join(deviceDir, id),
			ReadOnly: false,
		})
	}

	return resp, nil
}
126828
func (s *PortManager) PickEphemeralPort(testPort func(p uint16) (bool, *tcpip.Error)) (port uint16, err *tcpip.Error) {
	count := uint16(math.MaxUint16 - FirstEphemeral + 1)
	offset := uint16(rand.Int31n(int32(count)))

	for i := uint16(0); i < count; i++ {
		port = FirstEphemeral + (offset+i)%count
		ok, err := testPort(port)
		if err != nil {
			return 0, err
		}

		if ok {
			return port, nil
		}
	}

	return 0, tcpip.ErrNoPortAvailable
}
411575
func ParseExportCache(exportCaches, legacyExportCacheOpts []string) ([]client.CacheOptionsEntry, error) {
	var exports []client.CacheOptionsEntry
	if len(legacyExportCacheOpts) > 0 {
		if len(exportCaches) != 1 {
			return nil, errors.New("--export-cache-opt requires exactly single --export-cache")
		}
	}
	for _, exportCache := range exportCaches {
		legacy := !strings.Contains(exportCache, "type=")
		if legacy {
			logrus.Warnf("--export-cache <ref> --export-cache-opt <opt>=<optval> is deprecated. Please use --export-cache type=registry,ref=<ref>,<opt>=<optval>[,<opt>=<optval>] instead.")
			attrs, err := attrMap(legacyExportCacheOpts)
			if err != nil {
				return nil, err
			}
			if _, ok := attrs["mode"]; !ok {
				attrs["mode"] = "min"
			}
			attrs["ref"] = exportCache
			exports = append(exports, client.CacheOptionsEntry{
				Type:  "registry",
				Attrs: attrs,
			})
		} else {
			if len(legacyExportCacheOpts) > 0 {
				return nil, errors.New("--export-cache-opt is not supported for the specified --export-cache. Please use --export-cache type=<type>,<opt>=<optval>[,<opt>=<optval>] instead.")
			}
			ex, err := parseExportCacheCSV(exportCache)
			if err != nil {
				return nil, err
			}
			exports = append(exports, ex)
		}
	}
	return exports, nil

}
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
}
207888
func (r DockerImageReference) RegistryHostPort(insecure bool) (string, string) {
	registryHost := r.AsV2().DockerClientDefaults().Registry
	if strings.Contains(registryHost, ":") {
		hostname, port, _ := net.SplitHostPort(registryHost)
		return hostname, port
	}
	if insecure {
		return registryHost, "80"
	}
	return registryHost, "443"
}
230190
func checkHostPortConflicts(containers []core.Container, fldPath *field.Path) field.ErrorList {
	allPorts := sets.String{}
	return AccumulateUniqueHostPorts(containers, &allPorts, fldPath)
}
429990
func parsePorts(ports []networkingv1.NetworkPolicyPort) []api.PortRule {
	portRules := []api.PortRule{}
	for _, port := range ports {
		if port.Protocol == nil && port.Port == nil {
			continue
		}

		protocol := api.ProtoTCP
		if port.Protocol != nil {
			protocol, _ = api.ParseL4Proto(string(*port.Protocol))
		}

		portStr := ""
		if port.Port != nil {
			portStr = port.Port.String()
		}

		portRule := api.PortRule{
			Ports: []api.PortProtocol{
				{Port: portStr, Protocol: protocol},
			},
		}

		portRules = append(portRules, portRule)
	}

	return portRules
}