forked from moby/swarmkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
port.go
99 lines (80 loc) · 2.19 KB
/
port.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
90
91
92
93
94
95
96
97
98
99
package flagparser
import (
"strconv"
"strings"
"github.com/docker/swarmkit/api"
"github.com/pkg/errors"
"github.com/spf13/pflag"
)
func parsePorts(flags *pflag.FlagSet, spec *api.ServiceSpec) error {
if !flags.Changed("ports") {
return nil
}
portConfigs, err := flags.GetStringSlice("ports")
if err != nil {
return err
}
ports := []*api.PortConfig{}
for _, portConfig := range portConfigs {
name, protocol, port, swarmPort, err := parsePortConfig(portConfig)
if err != nil {
return err
}
ports = append(ports, &api.PortConfig{
Name: name,
Protocol: protocol,
TargetPort: port,
PublishedPort: swarmPort,
// In swarmctl all ports are by default
// PublishModeHost
PublishMode: api.PublishModeHost,
})
}
spec.Endpoint = &api.EndpointSpec{
Ports: ports,
}
return nil
}
func parsePortConfig(portConfig string) (string, api.PortConfig_Protocol, uint32, uint32, error) {
protocol := api.ProtocolTCP
parts := strings.Split(portConfig, ":")
if len(parts) < 2 {
return "", protocol, 0, 0, errors.New("insufficient parameters in port configuration")
}
name := parts[0]
portSpec := parts[1]
protocol, port, err := parsePortSpec(portSpec)
if err != nil {
return "", protocol, 0, 0, errors.Wrap(err, "failed to parse port")
}
if len(parts) > 2 {
var err error
portSpec := parts[2]
nodeProtocol, swarmPort, err := parsePortSpec(portSpec)
if err != nil {
return "", protocol, 0, 0, errors.Wrap(err, "failed to parse node port")
}
if nodeProtocol != protocol {
return "", protocol, 0, 0, errors.New("protocol mismatch")
}
return name, protocol, port, swarmPort, nil
}
return name, protocol, port, 0, nil
}
func parsePortSpec(portSpec string) (api.PortConfig_Protocol, uint32, error) {
parts := strings.Split(portSpec, "/")
p := parts[0]
port, err := strconv.ParseUint(p, 10, 32)
if err != nil {
return 0, 0, err
}
if len(parts) > 1 {
proto := parts[1]
protocol, ok := api.PortConfig_Protocol_value[strings.ToUpper(proto)]
if !ok {
return 0, 0, errors.Errorf("invalid protocol string: %s", proto)
}
return api.PortConfig_Protocol(protocol), uint32(port), nil
}
return api.ProtocolTCP, uint32(port), nil
}