github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/drivers/docker/ports.go (about) 1 package docker 2 3 import ( 4 "strconv" 5 6 docker "github.com/fsouza/go-dockerclient" 7 "github.com/hashicorp/go-hclog" 8 "github.com/hashicorp/nomad/helper/pluginutils/hclutils" 9 ) 10 11 // publishedPorts is a utility struct to keep track of the port bindings to publish. 12 // After calling add for each port, the publishedPorts and exposedPorts fields can be 13 // used in the docker container and host configs 14 type publishedPorts struct { 15 logger hclog.Logger 16 publishedPorts map[docker.Port][]docker.PortBinding 17 exposedPorts map[docker.Port]struct{} 18 } 19 20 func newPublishedPorts(logger hclog.Logger) *publishedPorts { 21 return &publishedPorts{ 22 logger: logger, 23 publishedPorts: map[docker.Port][]docker.PortBinding{}, 24 exposedPorts: map[docker.Port]struct{}{}, 25 } 26 } 27 28 // addMapped adds the port to the structures the Docker API expects for declaring mapped ports 29 func (p *publishedPorts) addMapped(label, ip string, port int, portMap hclutils.MapStrInt) { 30 // By default we will map the allocated port 1:1 to the container 31 containerPortInt := port 32 33 // If the user has mapped a port using port_map we'll change it here 34 if mapped, ok := portMap[label]; ok { 35 containerPortInt = mapped 36 } 37 38 p.add(label, ip, port, containerPortInt) 39 } 40 41 // add adds a port binding for the given port mapping 42 func (p *publishedPorts) add(label, ip string, port, to int) { 43 // if to is not set, use the port value per default docker functionality 44 if to == 0 { 45 to = port 46 } 47 48 // two docker port bindings are created for each port for tcp and udp 49 cPortTCP := docker.Port(strconv.Itoa(to) + "/tcp") 50 cPortUDP := docker.Port(strconv.Itoa(to) + "/udp") 51 binding := getPortBinding(ip, strconv.Itoa(port)) 52 53 if _, ok := p.publishedPorts[cPortTCP]; !ok { 54 // initialize both tcp and udp binding slices since they are always created together 55 p.publishedPorts[cPortTCP] = []docker.PortBinding{} 56 p.publishedPorts[cPortUDP] = []docker.PortBinding{} 57 } 58 59 p.publishedPorts[cPortTCP] = append(p.publishedPorts[cPortTCP], binding) 60 p.publishedPorts[cPortUDP] = append(p.publishedPorts[cPortUDP], binding) 61 p.logger.Debug("allocated static port", "ip", ip, "port", port, "label", label) 62 63 p.exposedPorts[cPortTCP] = struct{}{} 64 p.exposedPorts[cPortUDP] = struct{}{} 65 p.logger.Debug("exposed port", "port", port, "label", label) 66 }