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