Repository navigation
Expand file tree
/
Copy pathnodeProxy.go
More file actions
executable file
·334 lines (290 loc) · 7.93 KB
/
Copy pathnodeProxy.go
File metadata and controls
executable file
·334 lines (290 loc) · 7.93 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/***
Copyright 2016 Cisco Systems Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package drivers
import (
"fmt"
osexec "os/exec"
"strings"
"sync"
log "github.com/Sirupsen/logrus"
"github.com/contiv/netplugin/core"
)
const (
contivNPChain = "CONTIV-NODEPORT"
)
// Presence indicates presence of an item
type Presence struct {
Items map[string]bool
}
// NodeSvcProxy holds service proxy info
type NodeSvcProxy struct {
Mutex sync.Mutex
SvcMap map[string]core.ServiceSpec // service name as key
ProvMap map[string]Presence // service name as key
LocalIP map[string]string // globalIP as key
ipTablesPath string
natRules map[string][]string // natRule for the service
}
// NewNodeProxy creates an instance of the node proxy
func NewNodeProxy() (*NodeSvcProxy, error) {
ipTablesPath, err := osexec.LookPath("iptables")
if err != nil {
return nil, err
}
// Install contiv chain and jump
out, err := osexec.Command(ipTablesPath, "-t", "nat", "-N",
contivNPChain).CombinedOutput()
if err != nil {
if !strings.Contains(string(out), "Chain already exists") {
log.Errorf("Failed to setup contiv nodeport chain %v out: %s",
err, out)
return nil, err
}
}
_, err = osexec.Command(ipTablesPath, "-t", "nat", "-C",
"PREROUTING", "-m", "addrtype", "--dst-type", "LOCAL", "-j",
contivNPChain).CombinedOutput()
if err != nil {
out, err = osexec.Command(ipTablesPath, "-t", "nat", "-I",
"PREROUTING", "-m", "addrtype", "--dst-type", "LOCAL", "-j",
contivNPChain).CombinedOutput()
if err != nil {
log.Errorf("Failed to setup contiv nodeport chain jump %v out: %s",
err, out)
return nil, err
}
}
// Flush any old rules we might have added. They will get re-added
// if the service is still active
osexec.Command(ipTablesPath, "-t", "nat", "-F",
contivNPChain).CombinedOutput()
proxy := NodeSvcProxy{}
proxy.SvcMap = make(map[string]core.ServiceSpec)
proxy.ProvMap = make(map[string]Presence)
proxy.LocalIP = make(map[string]string)
proxy.ipTablesPath = ipTablesPath
proxy.natRules = make(map[string][]string)
return &proxy, nil
}
// DeleteLocalIP removes an entry from the localIP map
func (p *NodeSvcProxy) DeleteLocalIP(globalIP string) {
// strip cidr
globalIP = strings.Split(globalIP, "/")[0]
p.Mutex.Lock()
defer p.Mutex.Unlock()
delete(p.LocalIP, globalIP)
}
// AddLocalIP adds an entry to the localIP map
func (p *NodeSvcProxy) AddLocalIP(globalIP, localIP string) {
// strip cidr
globalIP = strings.Split(globalIP, "/")[0]
localIP = strings.Split(localIP, "/")[0]
p.Mutex.Lock()
defer p.Mutex.Unlock()
p.LocalIP[globalIP] = localIP
}
func (p *NodeSvcProxy) detectClash(svcName string, nodePort uint16) bool {
// verify if there is a clashing nodeport
for svc, s := range p.SvcMap {
if svc == svcName {
continue
}
for _, port := range s.Ports {
if port.NodePort == nodePort && port.Protocol == "TCP" {
log.Errorf("CONTIV-NODEPORT: %s/%d clashes with %s/%d",
svcName, nodePort, svc, nodePort)
return true
}
}
}
return false
}
// AddSvcSpec adds a service to the proxy
func (p *NodeSvcProxy) AddSvcSpec(svcName string, spec *core.ServiceSpec) error {
p.Mutex.Lock()
defer p.Mutex.Unlock()
log.Infof("Node proxy AddSvcSpec: %s", svcName)
// Determine if this is a node service
isNodeSvc := false
for _, port := range spec.Ports {
if port.NodePort != 0 && port.Protocol == "TCP" {
isNodeSvc = true
if p.detectClash(svcName, port.NodePort) {
return nil
}
}
}
if !isNodeSvc {
p.deleteSvc(svcName) // delete it if it exists
return nil
}
p.SvcMap[svcName] = *spec
p.syncSvc(svcName)
return nil
}
// DelSvcSpec deletes a service from the proxy
func (p *NodeSvcProxy) DelSvcSpec(svcName string, spec *core.ServiceSpec) error {
p.Mutex.Lock()
defer p.Mutex.Unlock()
p.deleteSvc(svcName) // delete it if it exists
return nil
}
// SvcProviderUpdate invokes switch api
func (p *NodeSvcProxy) SvcProviderUpdate(svcName string, providers []string) {
log.Infof("Node proxy AddSvcSpec: %s %v", svcName, providers)
p.Mutex.Lock()
defer p.Mutex.Unlock()
// check if there is at least one local provider
localProv := false
for _, prov := range providers {
_, localProv = p.LocalIP[prov]
if localProv {
break
}
}
if !localProv { // get rid of the natRules if it exists
p.deleteSvcRules(svcName)
delete(p.ProvMap, svcName)
return
}
// Make a new provider map
newProv := make(map[string]bool)
provMap := Presence{
Items: newProv,
}
p.ProvMap[svcName] = provMap
for _, prov := range providers {
_, found := p.LocalIP[prov]
if found {
provMap.Items[prov] = true
}
}
p.syncSvc(svcName)
}
func (p *NodeSvcProxy) execNATRule(act, dport, dest string) (string, error) {
out, err := osexec.Command(p.ipTablesPath, "-t", "nat", act,
contivNPChain, "-p", "tcp", "-m", "tcp", "--dport",
dport, "-j", "DNAT", "--to-destination",
dest).CombinedOutput()
return string(out), err
}
func (p *NodeSvcProxy) syncSvc(svcName string) {
// check if the service is active
_, found := p.SvcMap[svcName]
if !found {
p.deleteSvcRules(svcName)
return
}
pMap, found := p.ProvMap[svcName]
if !found {
p.deleteSvcRules(svcName)
return
}
active := false
prov := ""
for prov = range pMap.Items {
active = true
break
}
if active {
p.installSvcRules(svcName, p.LocalIP[prov])
return
}
p.deleteSvcRules(svcName)
}
func findString(lines []string, matchStr string) bool {
for _, line := range lines {
if strings.Contains(line, matchStr) {
return true
}
}
return false
}
func (p *NodeSvcProxy) installSvcRules(svcName, prov string) {
allPresent := true
spec := p.SvcMap[svcName]
providers := p.ProvMap[svcName]
natRules, found := p.natRules[svcName]
provToUse := prov
if found {
if len(natRules) == 0 {
found = false
}
}
if !found {
allPresent = false
} else {
// find the in-use provider
for prov := range providers.Items {
localProv := p.LocalIP[prov]
if strings.Contains(natRules[0], localProv) {
provToUse = localProv
break
}
}
// Check if all required NAT rules are present
for _, port := range spec.Ports {
matchStr := fmt.Sprintf(":%d", port.ProvPort)
if !findString(natRules, matchStr) {
allPresent = false
break
}
}
}
if allPresent {
log.Infof("Svc %s -- all rules present", svcName)
return
}
// Remove all previous rules and install new ones
p.deleteSvcRules(svcName)
natRules = make([]string, 0, len(spec.Ports))
for _, port := range spec.Ports {
if port.NodePort == 0 || port.Protocol != "TCP" {
continue
}
dport := fmt.Sprintf("%d", port.NodePort)
dest := fmt.Sprintf("%s:%d", provToUse, port.ProvPort)
out, err := p.execNATRule("-A", dport, dest)
addRule := dport + "/" + dest
if err != nil {
log.Errorf("Failed to add rule: %s, err: %v - %s",
addRule, err, out)
} else {
natRules = append(natRules, addRule)
log.Infof("Added %s", addRule)
}
}
p.natRules[svcName] = natRules
}
func (p *NodeSvcProxy) deleteSvcRules(svcName string) {
natRules, found := p.natRules[svcName]
if !found {
return
}
// Remove all rules
for _, rule := range natRules {
delRule := strings.Split(rule, "/")
out, err := p.execNATRule("-D", delRule[0], delRule[1])
if err != nil {
log.Errorf("Failed to delete rule: %s, err: %v - %s",
rule, err, out)
} else {
log.Infof("Deleted %s", rule)
}
}
delete(p.natRules, svcName)
}
func (p *NodeSvcProxy) deleteSvc(svcName string) {
p.deleteSvcRules(svcName)
delete(p.SvcMap, svcName)
}