// Adds a port public endpoint to a service.
187566
func (c *Client) AddPublicEndpointPort(serviceid, endpointName, portAddr string, usetls bool,
	protocol string, isEnabled bool, restart bool) (*servicedefinition.Port, error) {
	request := &PublicEndpointRequest{
		Serviceid:    serviceid,
		EndpointName: endpointName,
		Name:         portAddr,
		UseTLS:       usetls,
		Protocol:     protocol,
		IsEnabled:    isEnabled,
		Restart:      restart,
	}
	var result servicedefinition.Port
	err := c.call("AddPublicEndpointPort", request, &result)
	return &result, err
}
340447
func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) {
	// A single concatenation would break ARM compilation.
	message := "<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n" +
		"<NewRemoteHost></NewRemoteHost><NewExternalPort>" + strconv.Itoa(externalPort)
	message += "</NewExternalPort><NewProtocol>" + strings.ToUpper(protocol) + "</NewProtocol>"
	message += "<NewInternalPort>" + strconv.Itoa(internalPort) + "</NewInternalPort>" +
		"<NewInternalClient>" + n.ourIP + "</NewInternalClient>" +
		"<NewEnabled>1</NewEnabled><NewPortMappingDescription>"
	message += description +
		"</NewPortMappingDescription><NewLeaseDuration>" + strconv.Itoa(timeout) +
		"</NewLeaseDuration></u:AddPortMapping>"

	response, err := soapRequest(n.serviceURL, "AddPortMapping", message)
	if err != nil {
		return
	}

	// TODO: check response to see if the port was forwarded
	// If the port was not wildcard we don't get an reply with the port in
	// it. Not sure about wildcard yet. miniupnpc just checks for error
	// codes here.
	mappedExternalPort = externalPort
	_ = response
	return
}
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
}
631529
func (b *serverBuilder) AddPublicNWConnectedNIC() {
	b.nicConnections = append(b.nicConnections, "shared")
	b.displayIPAddresses = append(b.displayIPAddresses, "")
}
400508
func (a *api) AddService(config ServiceConfig) (*service.ServiceDetails, error) {
	client, err := a.connectDAO()
	if err != nil {
		return nil, err
	}

	endpoints := make([]servicedefinition.EndpointDefinition, len(*config.LocalPorts)+len(*config.RemotePorts))
	i := 0
	for _, e := range *config.LocalPorts {
		e.Purpose = "local"
		endpoints[i] = e
		i++
	}
	for _, e := range *config.RemotePorts {
		e.Purpose = "remote"
		endpoints[i] = e
		i++
	}

	sd := &servicedefinition.ServiceDefinition{
		Name:      config.Name,
		Command:   config.Command,
		Instances: domain.MinMax{Min: 1, Max: 1, Default: 1},
		ImageID:   config.ImageID,
		Launch:    commons.AUTO,
		Endpoints: endpoints,
	}

	var serviceID string
	if err := client.DeployService(dao.ServiceDeploymentRequest{ParentID: config.ParentServiceID, Service: *sd}, &serviceID); err != nil {
		return nil, err
	}

	return a.GetServiceDetails(serviceID)
}
914013
func (c *Client) EnablePublicEndpointPort(serviceid, endpointName, portAddr string, isEnabled bool) error {
	request := &PublicEndpointRequest{
		Serviceid:    serviceid,
		EndpointName: endpointName,
		Name:         portAddr,
		IsEnabled:    isEnabled,
	}
	return c.call("EnablePublicEndpointPort", request, nil)
}
556064
func (s *Server) AddEndpointFunc(method, path string, handler func(w http.ResponseWriter, r *http.Request)) {
	s.AddEndpoint(method, path, ApiHandlerFunc(handler))
}
1317774
func AddEndpoint(owner endpoint.Owner, ep *endpoint.Endpoint, reason string) (err error) {
	alwaysEnforce := policy.GetPolicyEnabled() == option.AlwaysEnforce
	ep.SetDesiredIngressPolicyEnabled(alwaysEnforce)
	ep.SetDesiredEgressPolicyEnabled(alwaysEnforce)

	if ep.ID != 0 {
		return fmt.Errorf("Endpoint ID is already set to %d", ep.ID)
	}
	return Insert(ep)
}
885366
func NewPublicPortListener(hostID string, handler PublicPortHandler) *PublicPortListener {
	return &PublicPortListener{
		hostID:  hostID,
		handler: handler,
	}
}
715381
func (client *WANPPPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
	// Request structure.
	request := &struct {
		NewRemoteHost             string
		NewExternalPort           string
		NewProtocol               string
		NewInternalPort           string
		NewInternalClient         string
		NewEnabled                string
		NewPortMappingDescription string
		NewLeaseDuration          string
	}{}
	// BEGIN Marshal arguments into request.

	if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
		return
	}
	if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
		return
	}
	if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
		return
	}
	if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
		return
	}
	if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
		return
	}
	if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
		return
	}
	if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
		return
	}
	if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
		return
	}
	// END Marshal arguments into request.

	// Response structure.
	response := interface{}(nil)

	// Perform the SOAP call.
	if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "AddPortMapping", request, response); err != nil {
		return
	}

	// BEGIN Unmarshal arguments from response.

	// END Unmarshal arguments from response.
	return
}
1235765
func AddLoadBalancer(endpoints []HNSEndpoint, isILB bool, sourceVIP, vip string, protocol uint16, internalPort uint16, externalPort uint16) (*PolicyList, error) {
	operation := "AddLoadBalancer"
	title := "hcsshim::PolicyList::" + operation
	logrus.Debugf(title+" endpointId=%v, isILB=%v, sourceVIP=%s, vip=%s, protocol=%v, internalPort=%v, externalPort=%v", endpoints, isILB, sourceVIP, vip, protocol, internalPort, externalPort)

	policylist := &PolicyList{}

	elbPolicy := &ELBPolicy{
		SourceVIP: sourceVIP,
		ILB:       isILB,
	}

	if len(vip) > 0 {
		elbPolicy.VIPs = []string{vip}
	}
	elbPolicy.Type = ExternalLoadBalancer
	elbPolicy.Protocol = protocol
	elbPolicy.InternalPort = internalPort
	elbPolicy.ExternalPort = externalPort

	for _, endpoint := range endpoints {
		policylist.EndpointReferences = append(policylist.EndpointReferences, "/endpoints/"+endpoint.Id)
	}

	jsonString, err := json.Marshal(elbPolicy)
	if err != nil {
		return nil, err
	}
	policylist.Policies = append(policylist.Policies, jsonString)
	return policylist.Create()
}
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)
}
165155
func buildPortsToEndpointsMap(endpoints *v1.Endpoints) map[string][]hostPortPair {
	portsToEndpoints := map[string][]hostPortPair{}
	for i := range endpoints.Subsets {
		ss := &endpoints.Subsets[i]
		for i := range ss.Ports {
			port := &ss.Ports[i]
			for i := range ss.Addresses {
				addr := &ss.Addresses[i]
				portsToEndpoints[port.Name] = append(portsToEndpoints[port.Name], hostPortPair{addr.IP, int(port.Port)})
				// Ignore the protocol field - we'll get that from the Service objects.
			}
		}
	}
	return portsToEndpoints
}
449664
func (z *zkf) GetPublicPort(portAddress string) (string, string, error) {
	logger := plog.WithField("portaddress", portAddress)

	// get the root-based connection to check the public port
	conn, err := zzk.GetLocalConnection("/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire a root-based connection to look up a public endpoint port")
		return "", "", err
	}

	// look for the public port
	key := zkr.PublicPortKey{
		HostID:      "master",
		PortAddress: portAddress,
	}
	serviceID, application, err := zkr.GetPublicPort(conn, key)
	if err != nil {
		logger.WithError(err).Debug("Could not look up public endpoint port")
		return "", "", err
	}

	logger.Debug("Searched for public endpoint port")
	return serviceID, application, err
}
808132
func (f *Facade) RemovePublicEndpointPort(ctx datastore.Context, serviceid, endpointName, portAddr string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.RemovePublicEndpointPort"))
	alog := f.auditLogger.Message(ctx, "Removing Public Endpoint Port").ID(serviceid).Action(audit.Update).
		WithFields(logrus.Fields{
			"endpointname": endpointName,
			"portaddr":     portAddr,
		})
	// Scrub the port for all checks, as this is what gets stored against the service.
	portAddr = service.ScrubPortString(portAddr)

	// Get the service for this service id.
	svc, err := f.GetService(ctx, serviceid)
	if err != nil {
		err = fmt.Errorf("Could not find service %s: %s", serviceid, err)
		glog.Error(err)
		return alog.Error(err)
	}
	alog = alog.Entity(svc)

	err = svc.RemovePort(endpointName, portAddr)
	if err != nil {
		err = fmt.Errorf("Error removing port %s from service (%s): %v", portAddr, svc.Name, err)
		glog.Error(err)
		return alog.Error(err)
	}

	glog.V(2).Infof("Removed port public endpoint %s from service %s", portAddr, svc.Name)

	if err = f.UpdateService(ctx, *svc); err != nil {
		glog.Error(err)
		return alog.Error(err)
	}

	glog.V(2).Infof("Service (%s) updated", svc.Name)
	alog.Succeeded()
	return nil
}
909059
func (s *Server) RemovePublicEndpointPort(request *PublicEndpointRequest, _ *struct{}) error {
	return s.f.RemovePublicEndpointPort(s.context(), request.Serviceid, request.EndpointName, request.Name)
}
1040147
func GetPublicPort(conn client.Connection, key PublicPortKey) (string, string, error) {
	pth := path.Join("/net/pub", key.HostID, key.PortAddress)

	logger := plog.WithFields(log.Fields{
		"hostid":      key.HostID,
		"portaddress": key.PortAddress,
		"zkpath":      pth,
	})

	pub := &PublicPort{}
	err := conn.Get(pth, pub)
	if err == client.ErrNoNode {
		logger.WithError(err).Debug("Port address not found")
		return "", "", nil
	} else if err != nil {
		logger.WithError(err).Debug("Could not look up port")
		return "", "", &RegistryError{
			Action:  "get",
			Path:    pth,
			Message: "could not look up port address",
		}
	}

	logger.WithFields(log.Fields{
		"tenantid":    pub.TenantID,
		"application": pub.Application,
	}).Debug("Found port")

	return pub.ServiceID, pub.Application, nil
}