/
port_util.go
89 lines (72 loc) · 1.75 KB
/
port_util.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package prommer
import (
"strconv"
dockertypes "github.com/docker/engine-api/types"
)
// FindPortOptions holds the optional parameters for FindPort
type FindPortOptions struct {
Label *string
}
// FindPort finds a port for a container
type FindPort func(dockertypes.Container, *FindPortOptions) int
// FindPortFromContainer attempts to find the correct port from the container
func FindPortFromContainer(c dockertypes.Container, options *FindPortOptions) int {
var (
portFromLabels int
//publicPorts []dockertypes.Port
amountOfPorts int
port *dockertypes.Port
)
portFromLabels = findPortFromLabels(c, options)
if portFromLabels != 0 {
return portFromLabels
}
//publicPorts = onlyPublicPorts(c.Ports)
amountOfPorts = len(c.Ports)
if amountOfPorts == 0 {
return 0
}
if amountOfPorts == 1 {
return c.Ports[0].PrivatePort
}
// If there are multiple ports
// prefer the one that forwards to port 80
port = findPortEighty(c.Ports)
if port == nil {
port = &c.Ports[0]
}
if port == nil {
return 0
}
return port.PrivatePort
}
func findPortFromLabels(c dockertypes.Container, options *FindPortOptions) int {
if options != nil && options.Label != nil {
portString := c.Labels[*options.Label]
if &portString != nil {
port, err := strconv.Atoi(portString)
if err != nil {
return 0
}
return port
}
}
return 0
}
func onlyPublicPorts(ports []dockertypes.Port) []dockertypes.Port {
var publicPorts []dockertypes.Port
for _, port := range ports {
if port.PublicPort != 0 {
publicPorts = append(publicPorts, port)
}
}
return publicPorts
}
func findPortEighty(ports []dockertypes.Port) *dockertypes.Port {
for _, port := range ports {
if port.PrivatePort == 80 {
return &port
}
}
return nil
}