forked from shettyg/ovn-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ovn-docker-driver
executable file
·674 lines (545 loc) · 20.1 KB
/
ovn-docker-driver
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#! /usr/bin/python
# Copyright (C) 2015 Nicira, Inc.
#
# 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.
import argparse
import atexit
import getpass
import json
import os
import re
import shlex
import subprocess
import sys
import time
import uuid
import ovs.dirs
import ovs.util
import ovs.daemon
import ovs.unixctl.server
import ovs.vlog
from neutronclient.v2_0 import client
from flask import Flask, jsonify
from flask import request, abort
app = Flask(__name__)
vlog = ovs.vlog.Vlog("ovn-docker-driver")
AUTH_STRATEGY = ""
AUTH_URL = ""
ENDPOINT_URL = ""
MODE = ""
OVN_BRIDGE = ""
PASSWORD = ""
PLUGIN_DIR = "/etc/docker/plugins"
PLUGIN_FILE = "/etc/docker/plugins/openvswitch.spec"
TENANT_ID = ""
USERNAME = ""
VIF_ID = ""
def call_popen(cmd):
child = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = child.communicate()
if child.returncode:
raise RuntimeError("Fatal error executing %s" % (cmd))
if len(output) == 0 or output[0] == None:
output = ""
else:
output = output[0].strip()
return output
def call_prog(prog, args_list):
cmd = [prog, "-vconsole:off"] + args_list
return call_popen(cmd)
def ovs_vsctl(args):
return call_prog("ovs-vsctl", shlex.split(args))
def cleanup():
if os.path.isfile(PLUGIN_FILE):
os.remove(PLUGIN_FILE)
def ovn_init_overlay():
global OVN_BRIDGE
OVN_BRIDGE = "br-int"
br_list = ovs_vsctl("list-br").split()
if OVN_BRIDGE not in br_list:
ovs_vsctl("-- --may-exist add-br %s "
"-- br-set-external-id %s bridge-id %s "
"-- set bridge %s other-config:disable-in-band=true "
"-- set bridge %s fail-mode=secure"
% (OVN_BRIDGE, OVN_BRIDGE, OVN_BRIDGE, OVN_BRIDGE,
OVN_BRIDGE))
global AUTH_STRATEGY, ENDPOINT_URL
AUTH_STRATEGY = "noauth"
endpoint_ip = ovs_vsctl("get Open_vSwitch . "
"external_ids:ipam").strip('"')
if not endpoint_ip:
sys.exit("ipam server's ip address not set")
ENDPOINT_URL = "http://%s:9696/" % (endpoint_ip)
ovs_vsctl("set open_vswitch . external_ids:ovn-bridge=%s "
"external_ids:ovn-encap-type=geneve" % OVN_BRIDGE)
def ovn_init_underlay():
global USERNAME, PASSWORD, TENANT_ID, AUTH_URL, AUTH_STRATEGY, VIF_ID
VIF_ID = os.environ.get('OS_VIF_ID', '')
if not VIF_ID:
sys.exit("env OS_VIF_ID not set")
USERNAME = os.environ.get('OS_USERNAME', '')
if not USERNAME:
sys.exit("env OS_USERNAME not set")
TENANT_ID = os.environ.get('OS_TENANT_ID', '')
if not TENANT_ID:
sys.exit("env OS_TENANT_ID not set")
AUTH_URL = os.environ.get('OS_AUTH_URL', '')
if not AUTH_URL:
sys.exit("env OS_AUTH_URL not set")
AUTH_STRATEGY = "keystone"
PASSWORD = os.environ.get('OS_PASSWORD', '')
if not PASSWORD:
PASSWORD = getpass.getpass()
def ovn_init(args):
global MODE
if args.underlay_mode:
if not args.bridge:
sys.exit("OVS bridge name not provided")
global OVN_BRIDGE
OVN_BRIDGE = args.bridge
MODE = "underlay"
ovn_init_underlay()
else:
MODE = "overlay"
ovn_init_overlay()
def prepare():
parser = argparse.ArgumentParser()
parser.add_argument('--overlay-mode', action='store_true')
parser.add_argument('--underlay-mode', action='store_true')
parser.add_argument('--bridge', help="The Bridge to which containers "
"interfaces connect to.")
ovs.vlog.add_args(parser)
ovs.daemon.add_args(parser)
args = parser.parse_args()
ovs.vlog.handle_args(args)
ovs.daemon.handle_args(args)
ovn_init(args)
if not os.path.isdir(PLUGIN_DIR):
sys.exit("No docker plugin directory configured")
ovs.daemon.daemonize()
try:
fo = open(PLUGIN_FILE, "w")
fo.write("tcp://0.0.0.0:5000")
fo.close()
except Exception as e:
ovs.util.ovs_fatal(0, "Failed to write to spec file (%s)" % str(e),
vlog)
atexit.register(cleanup)
# curl -i -H 'Content-Type: application/json' -X POST
# http://localhost:5000/Plugin.Activate
@app.route('/Plugin.Activate', methods=['POST'])
def plugin_activate():
return jsonify({"Implements": ["NetworkDriver"]})
def neutron_login():
try:
neutron = client.Client(username=USERNAME,
password=PASSWORD,
tenant_id=TENANT_ID,
auth_url=AUTH_URL,
endpoint_url=ENDPOINT_URL,
auth_strategy=AUTH_STRATEGY)
except Exception as e:
raise RuntimeError("Failed to login into Neutron(%s)" % str(e))
return neutron
def get_networkuuid_by_name(neutron, name):
param = {'fields': 'id', 'name': name}
ret = neutron.list_networks(**param)
if len(ret['networks']) > 1:
raise RuntimeError("More than one network for the given name")
elif len(ret['networks']) == 0:
network = None
else:
network = ret['networks'][0]['id']
return network
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{"NetworkID":"dummy-network","Options":{"subnet":"192.168.1.0/24"}}'
# http://localhost:5000/NetworkDriver.CreateNetwork
@app.route('/NetworkDriver.CreateNetwork', methods=['POST'])
def create_network():
# When IPAM is Neutron, we will have to create subnet separately
# because Docker currently does not allow passing subnet information.
if not request.data:
abort(400)
data = json.loads(request.data)
# NetworkID will have docker generated network uuid and it
# becomes 'name' in a neutron network record.
network = data.get("NetworkID", "")
if not network:
abort(400)
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
try:
if get_networkuuid_by_name(neutron, network):
return jsonify({})
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
try:
if MODE == "underlay":
body = {'network': {'name': network, 'admin_state_up': True}}
else:
body = {'network': {'name': network,
'tenant_id': "admin",
'admin_state_up': True}}
ret = neutron.create_network(body)
network_id = ret['network']['id']
except Exception as e:
error = "Failed in neutron api call (%s)" % str(e)
return jsonify({'Err': error})
return jsonify({})
# curl -i -H 'Content-Type: application/json' -X POST -d
# {"NetworkID":"dummy-network"}
# http://localhost:5000/NetworkDriver.DeleteNetwork
@app.route('/NetworkDriver.DeleteNetwork', methods=['POST'])
def delete_network():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
network = get_networkuuid_by_name(neutron, nid)
if not network:
return jsonify({})
try:
neutron.delete_network(network)
except Exception as e:
error = "Failed in neutron api call (%s)" % str(e)
return jsonify({'Err': error})
return jsonify({})
def reserve_vlan():
reserved_vlan = 0
vlans = ovs_vsctl("--if-exists get Open_vSwitch . "
"external_ids:vlans").strip('"')
if not vlans:
reserved_vlan = 1
ovs_vsctl("set Open_vSwitch . external_ids:vlans=%s" % reserved_vlan)
return reserved_vlan
vlan_set = str(vlans).split(',')
for vlan in range(1, 4095):
if str(vlan) not in vlan_set:
vlan_set.append(str(vlan))
reserved_vlan = vlan
vlans = re.sub(r'[ \[\]\']', '', str(vlan_set))
ovs_vsctl("set Open_vSwitch . external_ids:vlans=%s" % vlans)
return reserved_vlan
if not reserved_vlan:
raise RuntimeError("No more vlans available on this host")
def unreserve_vlan(reserved_vlan):
vlans = ovs_vsctl("--if-exists get Open_vSwitch . "
"external_ids:vlans").strip('"')
if not vlans:
return
vlan_set = str(vlans).split(',')
if str(reserved_vlan) not in vlan_set:
return
vlan_set.remove(str(reserved_vlan))
vlans = re.sub(r'[ \[\]\']', '', str(vlan_set))
if vlans:
ovs_vsctl("set Open_vSwitch . external_ids:vlans=%s" % vlans)
else:
ovs_vsctl("remove Open_vSwitch . external_ids vlans")
def create_port_underlay(neutron, network, eid):
reserved_vlan = reserve_vlan()
body = {'port': {'network_id': network,
'binding:profile': {'parent_name': VIF_ID,
'tag': int(reserved_vlan)},
'name': eid,
'admin_state_up': True}}
try:
ret = neutron.create_port(body)
mac_address = ret['port']['mac_address']
ip = "%s" % ret['port']['fixed_ips'][0]['ip_address']
except Exception as e:
unreserve_vlan(reserved_vlan)
raise RuntimeError("Failed in creation of neutron port (%s)." % str(e))
ovs_vsctl("set Open_vSwitch . external_ids:%s_vlan=%s"
% (eid, reserved_vlan))
return (mac_address, ip)
def create_port_overlay(neutron, network, eid):
body = {'port': {'network_id': network,
'tenant_id': "admin",
'name': eid,
'admin_state_up': True}}
ret = neutron.create_port(body)
mac_address = ret['port']['mac_address']
ip = "%s" % ret['port']['fixed_ips'][0]['ip_address']
return (mac_address, ip)
def get_endpointuuid_by_name(neutron, name):
param = {'fields': 'id', 'name': name}
ret = neutron.list_ports(**param)
if len(ret['ports']) > 1:
raise RuntimeError("More than one endpoint for the given name")
elif len(ret['ports']) == 0:
endpoint = None
else:
endpoint = ret['ports'][0]['id']
return endpoint
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{"NetworkID":"dummy-network","EndpointID":"dummy-endpoint","Interfaces":[],"Options":{}}'
# http://localhost:5000/NetworkDriver.CreateEndpoint
@app.route('/NetworkDriver.CreateEndpoint', methods=['POST'])
def create_endpoint():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
eid = data.get("EndpointID", "")
if not eid:
abort(400)
interfaces = data.get("Interfaces", "")
if interfaces:
# If interfaces has record, the endpoint has already
# been created.
return jsonify({})
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
network = get_networkuuid_by_name(neutron, nid)
if not network:
error = "Failed to get neutron network record for (%s)" % (nid)
return jsonify({'Err': error})
try:
ret = neutron.show_network(network)
subnet = ret['network']['subnets'][0]
if not subnet:
raise RuntimeError("No subnet defined for the network.")
except Exception as e:
error = "Could not obtain network information.\n(%s)" % (str(e))
return jsonify({'Err': error})
try:
ret = neutron.show_subnet(subnet)
gateway_ip = ret['subnet']['gateway_ip']
cidr = ret['subnet']['cidr']
netmask = cidr.rsplit('/', 1)[1]
if not netmask:
raise RuntimeError("No cidr netmask found for subnet")
except Exception as e:
error = "Could not obtain subnet information (%s)" % (str(e))
return jsonify({'Err': error})
try:
if MODE == "underlay":
(mac_address, ip_address) = create_port_underlay(neutron, network,
eid)
else:
(mac_address, ip_address) = create_port_overlay(neutron, network,
eid)
except Exception as e:
error = "Failed in neutron port creation call (%s)" % (str(e))
return jsonify({'Err': error})
ip_address_and_mask = "%s/%s" % (ip_address, netmask)
return jsonify({"Interfaces": [{
"ID": 0,
"Address": ip_address_and_mask,
"AddressIPv6": None,
"MacAddress": mac_address
}]})
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{"NetworkID":"dummy-network","EndpointID":"dummy-endpoint"}'
# http://localhost:5000/NetworkDriver.EndpointOperInfo
@app.route('/NetworkDriver.EndpointOperInfo', methods=['POST'])
def show_endpoint():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
eid = data.get("EndpointID", "")
if not eid:
abort(400)
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
endpoint = get_endpointuuid_by_name(neutron, eid)
if not endpoint:
error = "Failed to get endpoint by name"
return jsonify({'Err': error})
try:
ret = neutron.show_port(endpoint)
mac_address = ret['port']['mac_address']
ip_address = ret['port']['fixed_ips'][0]['ip_address']
except Exception as e:
error = "Failed to get endpoint information (%s)" % (str(e))
return jsonify({'Err': error})
veth_outside = eid[0:15]
return jsonify({"Value": {"ip_address": ip_address,
"mac_address": mac_address,
"veth_outside": veth_outside
}})
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{"NetworkID":"dummy-network","EndpointID":"dummy-endpoint"}'
# http://localhost:5000/NetworkDriver.DeleteEndpoint
@app.route('/NetworkDriver.DeleteEndpoint', methods=['POST'])
def delete_endpoint():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
eid = data.get("EndpointID", "")
if not eid:
abort(400)
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
endpoint = get_endpointuuid_by_name(neutron, eid)
if not endpoint:
return jsonify({})
if MODE == "underlay":
reserved_vlan = ovs_vsctl("--if-exists get Open_vSwitch . "
"external_ids:%s_vlan" % eid).strip('"')
if reserved_vlan:
unreserve_vlan(reserved_vlan)
ovs_vsctl("remove Open_vSwitch . external_ids %s_vlan"
% eid)
else:
# This endpoint was not created on this host
return jsonify({})
try:
neutron.delete_port(endpoint)
except Exception as e:
error = "Failed to delete endpoint. (%s)" % (str(e))
return jsonify({'Err': error})
return jsonify({})
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{u'NetworkID': u'dummy-network', u'SandboxKey': u'sandbox-key', \
# u'Options': {u'foo': u'fooValue'}, u'EndpointID': u'dummy-endpoint'}'
# http://localhost:5000/NetworkDriver.Join
@app.route('/NetworkDriver.Join', methods=['POST'])
def network_join():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
eid = data.get("EndpointID", "")
if not eid:
abort(400)
sboxkey = data.get("SandboxKey", "")
if not sboxkey:
abort(400)
# sboxkey is of the form: /var/run/docker/netns/CONTAINER_ID
vm_id = sboxkey.rsplit('/')[-1]
try:
neutron = neutron_login()
except Exception as e:
error = "%s" % (str(e))
return jsonify({'Err': error})
endpoint = get_endpointuuid_by_name(neutron, eid)
if not endpoint:
error = "Failed to get endpoint by name"
return jsonify({'Err': error})
try:
ret = neutron.show_port(endpoint)
mac_address = ret['port']['mac_address']
except Exception as e:
error = "Failed to get endpoint information (%s)" % (str(e))
return jsonify({'Err': error})
veth_outside = eid[0:15]
veth_inside = eid[0:13] + "_c"
command = "ip link add %s type veth peer name %s" \
% (veth_inside, veth_outside)
try:
call_popen(shlex.split(command))
except Exception as e:
error = "Failed to create veth pair (%s)" % (str(e))
return jsonify({'Err': error})
command = "ip link set dev %s address %s" \
% (veth_inside, mac_address)
try:
call_popen(shlex.split(command))
except Exception as e:
error = "Failed to set veth mac address (%s)" % (str(e))
return jsonify({'Err': error})
command = "ip link set %s up" % (veth_outside)
try:
call_popen(shlex.split(command))
except Exception as e:
error = "Failed to up the veth interface (%s)" % (str(e))
return jsonify({'Err': error})
try:
if MODE == "underlay":
reserved_vlan = ovs_vsctl("--if-exists get Open_vSwitch . "
"external_ids:%s_vlan" % eid).strip('"')
if not reserved_vlan:
error = "No reserved vlan for this endpoint"
return jsonify({'Err': error})
ovs_vsctl("add-port %s %s tag=%s"
% (OVN_BRIDGE, veth_outside, reserved_vlan))
else:
ovs_vsctl("add-port %s %s" % (OVN_BRIDGE, veth_outside))
ovs_vsctl("set interface %s external_ids:attached-mac=%s "
"external_ids:iface-id=%s "
"external_ids:vm-id=%s "
"external_ids:iface-status=%s "
% (veth_outside, mac_address, endpoint, vm_id, "active"))
except Exception as e:
error = "Failed to create a port (%s)" % (str(e))
return jsonify({'Err': error})
return jsonify({"InterfaceNames": [{
"SrcName": veth_inside,
"DstPrefix": "eth"
}],
"Gateway": "",
"GatewayIPv6": "",
"HostsPath": "",
"ResolvConfPath": ""})
# curl -i -H 'Content-Type: application/json' -X POST -d
# '{"NetworkID":"dummy-network","EndpointID":"dummy-endpoint"}'
# http://localhost:5000/NetworkDriver.Leave
@app.route('/NetworkDriver.Leave', methods=['POST'])
def network_leave():
if not request.data:
abort(400)
data = json.loads(request.data)
nid = data.get("NetworkID", "")
if not nid:
abort(400)
eid = data.get("EndpointID", "")
if not eid:
abort(400)
veth_outside = eid[0:15]
command = "ip link delete %s" % (veth_outside)
try:
call_popen(shlex.split(command))
except Exception as e:
error = "Failed to delete veth pair (%s)" % (str(e))
return jsonify({'Err': error})
try:
ovs_vsctl("--if-exists del-port %s" % (veth_outside))
except Exception as e:
error = "Failed to delete port (%s)" % (str(e))
return jsonify({'Err': error})
return jsonify({})
if __name__ == '__main__':
prepare()
app.run(host='0.0.0.0')