summaryrefslogtreecommitdiff
path: root/runtime/networkdriver/portallocator/portallocator.go
blob: 9ecd447116ab0aa277428b2f88830d3c84681e9c (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package portallocator

import (
	"errors"
	"github.com/dotcloud/docker/pkg/collections"
	"net"
	"sync"
)

const (
	BeginPortRange = 49153
	EndPortRange   = 65535
)

type (
	portMappings map[string]*collections.OrderedIntSet
	ipMapping    map[string]portMappings
)

var (
	ErrAllPortsAllocated    = errors.New("all ports are allocated")
	ErrPortAlreadyAllocated = errors.New("port has already been allocated")
	ErrUnknownProtocol      = errors.New("unknown protocol")
)

var (
	currentDynamicPort = map[string]int{
		"tcp": BeginPortRange - 1,
		"udp": BeginPortRange - 1,
	}
	defaultIP             = net.ParseIP("0.0.0.0")
	defaultAllocatedPorts = portMappings{}
	otherAllocatedPorts   = ipMapping{}
	lock                  = sync.Mutex{}
)

func init() {
	defaultAllocatedPorts["tcp"] = collections.NewOrderedIntSet()
	defaultAllocatedPorts["udp"] = collections.NewOrderedIntSet()
}

// RequestPort returns an available port if the port is 0
// If the provided port is not 0 then it will be checked if
// it is available for allocation
func RequestPort(ip net.IP, proto string, port int) (int, error) {
	lock.Lock()
	defer lock.Unlock()

	if err := validateProtocol(proto); err != nil {
		return 0, err
	}

	// If the user requested a specific port to be allocated
	if port > 0 {
		if err := registerSetPort(ip, proto, port); err != nil {
			return 0, err
		}
		return port, nil
	}
	return registerDynamicPort(ip, proto)
}

// ReleasePort will return the provided port back into the
// pool for reuse
func ReleasePort(ip net.IP, proto string, port int) error {
	lock.Lock()
	defer lock.Unlock()

	if err := validateProtocol(proto); err != nil {
		return err
	}

	allocated := defaultAllocatedPorts[proto]
	allocated.Remove(port)

	if !equalsDefault(ip) {
		registerIP(ip)

		// Remove the port for the specific ip address
		allocated = otherAllocatedPorts[ip.String()][proto]
		allocated.Remove(port)
	}
	return nil
}

func ReleaseAll() error {
	lock.Lock()
	defer lock.Unlock()

	currentDynamicPort["tcp"] = BeginPortRange - 1
	currentDynamicPort["udp"] = BeginPortRange - 1

	defaultAllocatedPorts = portMappings{}
	defaultAllocatedPorts["tcp"] = collections.NewOrderedIntSet()
	defaultAllocatedPorts["udp"] = collections.NewOrderedIntSet()

	otherAllocatedPorts = ipMapping{}

	return nil
}

func registerDynamicPort(ip net.IP, proto string) (int, error) {

	if !equalsDefault(ip) {
		registerIP(ip)

		ipAllocated := otherAllocatedPorts[ip.String()][proto]

		port, err := findNextPort(proto, ipAllocated)
		if err != nil {
			return 0, err
		}
		ipAllocated.Push(port)
		return port, nil

	} else {

		allocated := defaultAllocatedPorts[proto]

		port, err := findNextPort(proto, allocated)
		if err != nil {
			return 0, err
		}
		allocated.Push(port)
		return port, nil
	}
}

func registerSetPort(ip net.IP, proto string, port int) error {
	allocated := defaultAllocatedPorts[proto]
	if allocated.Exists(port) {
		return ErrPortAlreadyAllocated
	}

	if !equalsDefault(ip) {
		registerIP(ip)

		ipAllocated := otherAllocatedPorts[ip.String()][proto]
		if ipAllocated.Exists(port) {
			return ErrPortAlreadyAllocated
		}
		ipAllocated.Push(port)
	} else {
		allocated.Push(port)
	}
	return nil
}

func equalsDefault(ip net.IP) bool {
	return ip == nil || ip.Equal(defaultIP)
}

func findNextPort(proto string, allocated *collections.OrderedIntSet) (int, error) {
	port := nextPort(proto)
	startSearchPort := port
	for allocated.Exists(port) {
		port = nextPort(proto)
		if startSearchPort == port {
			return 0, ErrAllPortsAllocated
		}
	}
	return port, nil
}

func nextPort(proto string) int {
	c := currentDynamicPort[proto] + 1
	if c > EndPortRange {
		c = BeginPortRange
	}
	currentDynamicPort[proto] = c
	return c
}

func registerIP(ip net.IP) {
	if _, exists := otherAllocatedPorts[ip.String()]; !exists {
		otherAllocatedPorts[ip.String()] = portMappings{
			"tcp": collections.NewOrderedIntSet(),
			"udp": collections.NewOrderedIntSet(),
		}
	}
}

func validateProtocol(proto string) error {
	if _, exists := defaultAllocatedPorts[proto]; !exists {
		return ErrUnknownProtocol
	}
	return nil
}