forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
85 lines (65 loc) · 2 KB
/
common.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
package portutils
import (
"fmt"
"strconv"
"strings"
"github.com/fsouza/go-dockerclient"
)
// SplitPortAndProtocol splits a string of format port/proto and returns
// a docker.Port
func SplitPortAndProtocol(port string) (docker.Port, error) {
dp := docker.Port(port)
err := ValidatePortAndProtocol(dp)
return dp, err
}
// FilterPortAndProtocolArray splits an array of strings of format port/proto
// and returns an array of docker.Port that succeeded parsing
func FilterPortAndProtocolArray(ports []string) ([]docker.Port, []error) {
allErrs := []error{}
allPorts := []docker.Port{}
for _, port := range ports {
dp, err := SplitPortAndProtocol(port)
if err == nil {
allPorts = append(allPorts, dp)
} else {
allErrs = append(allErrs, err)
}
}
return allPorts, allErrs
}
// SplitPortAndProtocolArray splits an array of strings of format port/proto
// and returns an array of docker.Port
func SplitPortAndProtocolArray(ports []string) ([]docker.Port, []error) {
allErrs := []error{}
allPorts := []docker.Port{}
for _, port := range ports {
dp, err := SplitPortAndProtocol(port)
if err != nil {
allErrs = append(allErrs, err)
}
allPorts = append(allPorts, dp)
}
if len(allErrs) > 0 {
return allPorts, allErrs
}
return allPorts, nil
}
// ValidatePortAndProtocol validates the port range and protocol of a docker.Port
func ValidatePortAndProtocol(port docker.Port) error {
errs := []string{}
_, err := strconv.ParseUint(port.Port(), 10, 16)
if err != nil {
if numError, ok := err.(*strconv.NumError); ok {
if numError.Err == strconv.ErrRange || numError.Err == strconv.ErrSyntax {
errs = append(errs, "port number must be in range 0 - 65535")
}
}
}
if len(port.Proto()) > 0 && !(strings.ToUpper(port.Proto()) == "TCP" || strings.ToUpper(port.Proto()) == "UDP") {
errs = append(errs, "protocol must be tcp or udp")
}
if len(errs) > 0 {
return fmt.Errorf("failed to parse port %s/%s: [%v]", port.Port(), port.Proto(), strings.Join(errs, ", "))
}
return nil
}