-
Notifications
You must be signed in to change notification settings - Fork 390
/
db.py
1477 lines (1306 loc) · 54.4 KB
/
db.py
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
"""
This file contains implementation of data model for physical router
configuration manager
"""
from physical_router_config import PhysicalRouterConfig
from physical_router_config import JunosInterface
from physical_router_config import PushConfigState
from dm_utils import DMUtils
from sandesh.dm_introspect import ttypes as sandesh
from cfgm_common.vnc_db import DBBase
from cfgm_common.uve.physical_router.ttypes import *
from vnc_api.vnc_api import *
import copy
import socket
import gevent
from gevent import queue
from cfgm_common.vnc_cassandra import VncCassandraClient
from netaddr import IPAddress
from cfgm_common.zkclient import IndexAllocator
from cfgm_common import vnc_greenlets
from sandesh_common.vns.constants import DEVICE_MANAGER_KEYSPACE_NAME
class DBBaseDM(DBBase):
obj_type = __name__
class BgpRouterDM(DBBaseDM):
_dict = {}
obj_type = 'bgp_router'
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.bgp_routers = {}
self.physical_router = None
self.update(obj_dict)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
self.name = obj['fq_name'][-1]
self.params = obj['bgp_router_parameters']
if self.params is not None:
if self.params.get('autonomous_system') is None:
self.params[
'autonomous_system'] = \
GlobalSystemConfigDM.get_global_asn()
self.update_single_ref('physical_router', obj)
new_peers = {}
for ref in obj.get('bgp_router_refs', []):
new_peers[ref['uuid']] = ref['attr']
for peer_id in set(self.bgp_routers.keys()) - set(new_peers.keys()):
peer = BgpRouterDM.get(peer_id)
if not peer:
continue
if self.uuid in peer.bgp_routers:
del peer.bgp_routers[self.uuid]
for peer_id, attrs in new_peers.items():
peer = BgpRouterDM.get(peer_id)
if peer:
peer.bgp_routers[self.uuid] = attrs
self.bgp_routers = new_peers
def sandesh_build(self):
return sandesh.BgpRouter(name=self.name, uuid=self.uuid,
peers=self.bgp_routers,
physical_router=self.physical_router)
@classmethod
def sandesh_request(cls, req):
# Return the list of BGP routers
resp = sandesh.BgpRouterListResp(bgp_routers=[])
if req.name_or_uuid is None:
for router in cls.values():
sandesh_router = router.sandesh_build()
resp.bgp_routers.extend(sandesh_router)
else:
router = cls.find_by_name_or_uuid(req.name_or_uuid)
if router:
sandesh_router = router.sandesh_build()
resp.bgp_routers.extend(sandesh_router)
resp.response(req.context())
def get_all_bgp_router_ips(self):
if self.params['address'] is not None:
bgp_router_ips = set([self.params['address']])
else:
bgp_router_ips = set()
for peer_uuid in self.bgp_routers:
peer = BgpRouterDM.get(peer_uuid)
if peer is None or peer.params['address'] is None:
continue
bgp_router_ips.add(peer.params['address'])
return bgp_router_ips
# end get_all_bgp_router_ips
# end class BgpRouterDM
class PhysicalRouterDM(DBBaseDM):
_dict = {}
obj_type = 'physical_router'
_sandesh = None
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.virtual_networks = set()
self.bgp_router = None
self.config_manager = None
self.nc_q = queue.Queue(maxsize=1)
self.vn_ip_map = {}
self.init_cs_state()
self.update(obj_dict)
self.config_manager = PhysicalRouterConfig(
self.management_ip, self.user_credentials, self.vendor,
self.product, self._logger)
self.set_conf_sent_state(False)
self.config_repush_interval = PushConfigState.get_repush_interval()
self.nc_handler_gl = vnc_greenlets.VncGreenlet("VNC Device Manager",
self.nc_handler)
self.uve_send()
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
self.name = obj['fq_name'][-1]
self.management_ip = obj.get('physical_router_management_ip')
self.dataplane_ip = obj.get('physical_router_dataplane_ip')
self.vendor = obj.get('physical_router_vendor_name', '')
self.product = obj.get('physical_router_product_name', '')
self.vnc_managed = obj.get('physical_router_vnc_managed')
self.user_credentials = obj.get('physical_router_user_credentials')
self.junos_service_ports = obj.get(
'physical_router_junos_service_ports')
self.update_single_ref('bgp_router', obj)
self.update_multiple_refs('virtual_network', obj)
self.physical_interfaces = set([pi['uuid'] for pi in
obj.get('physical_interfaces', [])])
self.logical_interfaces = set([li['uuid'] for li in
obj.get('logical_interfaces', [])])
if self.config_manager is not None:
self.config_manager.update(
self.management_ip, self.user_credentials, self.vendor,
self.product)
# end update
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
if obj.is_vnc_managed() and obj.is_conf_sent():
obj.config_manager.delete_bgp_config()
obj._cassandra.delete_pr(uuid)
obj.uve_send(True)
obj.update_single_ref('bgp_router', {})
obj.update_multiple_refs('virtual_network', {})
del cls._dict[uuid]
# end delete
def is_junos_service_ports_enabled(self):
if (self.junos_service_ports is not None
and self.junos_service_ports.get('service_port') is not None):
return True
return False
# end is_junos_service_ports_enabled
def block_and_set_config_state(self, timeout):
try:
if self.nc_q.get(True, timeout) is not None:
self.set_config_state()
except queue.Empty:
self.set_config_state()
# end block_and_set_config_state
def set_config_state(self):
try:
self.nc_q.put_nowait(1)
except queue.Full:
pass
# end
def nc_handler(self):
while self.nc_q.get() is not None:
try:
self.push_config()
except Exception as e:
self._logger.error("Exception: " + str(e))
# end
def is_valid_ip(self, ip_str):
try:
socket.inet_aton(ip_str)
return True
except socket.error:
return False
# end
def init_cs_state(self):
vn_subnet_set = self._cassandra.get_pr_vn_set(self.uuid)
for vn_subnet in vn_subnet_set:
ip = self._cassandra.get(self._cassandra._PR_VN_IP_CF,
self.uuid + ':' + vn_subnet)
if ip is not None:
self.vn_ip_map[vn_subnet] = ip['ip_address']
# end init_cs_state
def reserve_ip(self, vn_uuid, subnet_uuid):
try:
vn = VirtualNetwork()
vn.set_uuid(vn_uuid)
ip_addr = self._manager._vnc_lib.virtual_network_ip_alloc(
vn,
subnet_uuid=subnet_uuid)
if ip_addr:
return ip_addr[0] # ip_alloc default ip count is 1
except Exception as e:
self._logger.error("Exception: %s" % (str(e)))
return None
# end
def free_ip(self, vn_uuid, ip_addr):
try:
vn = VirtualNetwork()
vn.set_uuid(vn_uuid)
self._manager._vnc_lib.virtual_network_ip_free(
vn, [ip_addr])
return True
except Exception as e:
self._logger.error("Exception: %s" % (str(e)))
return False
# end
def get_vn_irb_ip_map(self):
irb_ips = {}
for vn_subnet, ip_addr in self.vn_ip_map.items():
(vn_uuid, subnet_prefix) = vn_subnet.split(':', 1)
vn = VirtualNetworkDM.get(vn_uuid)
if vn_uuid not in irb_ips:
irb_ips[vn_uuid] = set()
irb_ips[vn_uuid].add(
(ip_addr,
vn.gateways[subnet_prefix].get('default_gateway')))
return irb_ips
# end get_vn_irb_ip_map
def evaluate_vn_irb_ip_map(self, vn_set):
new_vn_ip_set = set()
for vn_uuid in vn_set:
vn = VirtualNetworkDM.get(vn_uuid)
# dont need irb ip, gateway ip
if vn.get_forwarding_mode() != 'l2_l3':
continue
for subnet_prefix in vn.gateways.keys():
new_vn_ip_set.add(vn_uuid + ':' + subnet_prefix)
old_set = set(self.vn_ip_map.keys())
delete_set = old_set.difference(new_vn_ip_set)
create_set = new_vn_ip_set.difference(old_set)
for vn_subnet in delete_set:
(vn_uuid, subnet_prefix) = vn_subnet.split(':', 1)
ret = self.free_ip(vn_uuid, self.vn_ip_map[vn_subnet])
if ret == False:
self._logger.error("Unable to free ip for vn/subnet/pr \
(%s/%s/%s)" % (
vn_uuid,
subnet_prefix,
self.uuid))
ret = self._cassandra.delete(
self._cassandra._PR_VN_IP_CF,
self.uuid + ':' + vn_uuid + ':' + subnet_prefix)
if ret == False:
self._logger.error("Unable to free ip from db for vn/subnet/pr \
(%s/%s/%s)" % (
vn_uuid,
subnet_prefix,
self.uuid))
continue
self._cassandra.delete_from_pr_map(self.uuid, vn_subnet)
del self.vn_ip_map[vn_subnet]
for vn_subnet in create_set:
(vn_uuid, subnet_prefix) = vn_subnet.split(':', 1)
subnet_uuid = vn.gateways[subnet_prefix].get('subnet_uuid')
(sub, length) = subnet_prefix.split('/')
ip_addr = self.reserve_ip(vn_uuid, subnet_uuid)
if ip_addr is None:
self._logger.error("Unable to allocate ip for vn/subnet/pr \
(%s/%s/%s)" % (
vn_uuid,
subnet_prefix,
self.uuid))
continue
ret = self._cassandra.add(self._cassandra._PR_VN_IP_CF,
self.uuid + ':' + vn_uuid +
':' + subnet_prefix,
{'ip_address': ip_addr + '/' + length})
if ret == False:
self._logger.error("Unable to store ip for vn/subnet/pr \
(%s/%s/%s)" % (
self.uuid,
subnet_prefix,
self.uuid))
if self.free_ip(vn_uuid, ip_addr) == False:
self._logger.error("Unable to free ip for vn/subnet/pr \
(%s/%s/%s)" % (
self.uuid,
subnet_prefix,
self.uuid))
continue
self._cassandra.add_to_pr_map(self.uuid, vn_subnet)
self.vn_ip_map[vn_subnet] = ip_addr + '/' + length
# end evaluate_vn_irb_ip_map
def get_vn_li_map(self):
vn_dict = {}
for vn_id in self.virtual_networks:
vn_dict[vn_id] = []
li_set = self.logical_interfaces
for pi_uuid in self.physical_interfaces:
pi = PhysicalInterfaceDM.get(pi_uuid)
if pi is None:
continue
li_set |= pi.logical_interfaces
for li_uuid in li_set:
li = LogicalInterfaceDM.get(li_uuid)
if li is None:
continue
vmi_id = li.virtual_machine_interface
vmi = VirtualMachineInterfaceDM.get(vmi_id)
if vmi is None:
continue
vn_id = vmi.virtual_network
vn_dict.setdefault(vn_id, []).append(
JunosInterface(li.name, li.li_type, li.vlan_tag))
return vn_dict
# end
def is_vnc_managed(self):
if (self.vendor is None or self.product is None or
self.vendor.lower() != "juniper" or self.product.lower()[:2] != "mx"):
self._logger.info("auto configuraion of physical router is not supported \
vendor family(%s:%s), ip: %s, not pushing netconf message" %
(str(self.vendor), str(self.product), self.management_ip))
return False
if not self.vnc_managed:
self._logger.info("vnc managed property must be set for a physical router to get auto \
configured, ip: %s, not pushing netconf message" % (self.management_ip))
return False
return True
# end is_vnc_managed
def set_conf_sent_state(self, state):
self.config_sent = state
# end set_conf_sent_state
def is_conf_sent(self):
return self.config_sent
# end is_conf_sent
def delete_config(self):
if not self.is_vnc_managed() and self.is_conf_sent():
# user must have unset the vnc managed property
self.config_manager.delete_bgp_config()
if self.config_manager.retry():
# failed commit: set repush interval upto max value
self.config_repush_interval = min([2 * self.config_repush_interval,
PushConfigState.get_repush_max_interval()])
self.block_and_set_config_state(self.config_repush_interval)
return True
# succesful commit: reset repush interval
self.config_repush_interval = PushConfigState.get_repush_interval()
self.set_conf_sent_state(False)
self.uve_send()
return True
return False
# end delete_config
def get_pnf_vrf_name(self, si_obj, interface_type, first_tag):
if not first_tag:
return '_contrail-' + si_obj.name + '-' + interface_type
else:
return ('_contrail-' + si_obj.name + '-' + interface_type
+ '-sc-entry-point')
def allocate_pnf_resources(self, vmi):
resources = self._cassandra.get_pnf_resources(
vmi, self.uuid)
network_id = int(resources['network_id'])
if vmi.service_interface_type == "left":
ip = str(IPAddress(network_id*4+1))
if vmi.service_interface_type == "right":
ip = str(IPAddress(network_id*4+2))
ip = ip + "/30"
return {
"ip_address": ip,
"vlan_id": resources['vlan_id'],
"unit_id": resources['unit_id']}
# end
def config_pnf_logical_interface(self):
pnf_dict = {}
pnf_ris = set()
# make it fake for now
# sholud save to the database, the allocation
self.vlan_alloc = {"max": 1}
self.ip_alloc = {"max": -1}
self.li_alloc = {}
for pi_uuid in self.physical_interfaces:
pi = PhysicalInterfaceDM.get(pi_uuid)
if pi is None:
continue
for pi_pi_uuid in pi.physical_interfaces:
pi_pi = PhysicalInterfaceDM.get(pi_pi_uuid)
for pi_vmi_uuid in pi_pi.virtual_machine_interfaces:
allocate_li = False
pi_vmi = VirtualMachineInterfaceDM.get(pi_vmi_uuid)
if (pi_vmi is None or
pi_vmi.service_instance is None or
pi_vmi.service_interface_type is None):
continue
if pi_vmi.routing_instances:
for ri_id in pi_vmi.routing_instances:
ri_obj = RoutingInstanceDM.get(ri_id)
if ri_obj and ri_obj.routing_instances and ri_obj.service_chain_address:
pnf_ris.add(ri_obj)
# If this service is on a service chain, we need allocate
# a logic interface for its VMI
allocate_li = True
if allocate_li:
resources = self.allocate_pnf_resources(pi_vmi)
if (not resources or
not resources["ip_address"] or
not resources["vlan_id"] or
not resources["unit_id"]):
self._logger.error(
"Cannot allocate PNF resources for \
Virtual Machine Interface" + pi_vmi_uuid)
return
logical_interface = JunosInterface(
pi.name + '.' + resources["unit_id"],
"l3", resources["vlan_id"], resources["ip_address"])
self.config_manager.add_pnf_logical_interface(
logical_interface)
lis = pnf_dict.setdefault(
pi_vmi.service_instance,
{"left": [], "right": [],
"mgmt": [], "other": []}
)[pi_vmi.service_interface_type]
lis.append(logical_interface)
return (pnf_dict, pnf_ris)
# end
def compute_pnf_static_route(self, ri_obj, pnf_dict):
"""
Compute all the static route for the pnfs on the device
Args:
ri_obj: The routing instance need to added the static routes
pnf_dict: The pnf mapping dict
Returns:
static_routes: a static route list
[
"service_chain_address":{
"next-hop":"ip_address",
"preference": int #use for the load balance
}
]
"""
prefrence = 0
static_routes = {}
for vmi_uuid in ri_obj.virtual_machine_interfaces:
# found the service chain address
# Check if this vmi is a PNF vmi
vmi = VirtualMachineInterfaceDM.get(vmi_uuid)
preference = 0
if vmi is not None:
if vmi.service_instance is not None:
li_list = []
if vmi.service_interface_type == 'left':
li_list = pnf_dict[vmi.service_instance]['right']
elif vmi.service_interface_type == 'right':
li_list = pnf_dict[vmi.service_instance]['left']
for li in li_list:
static_entry = {
"next-hop": li.ip.split('/')[0]
}
if preference > 0:
static_entry[
"preference"] = preference
preference += 1
srs = static_routes.setdefault(
ri_obj.service_chain_address, [])
srs.append(static_entry)
return static_routes
# end
def add_pnf_vrfs(self, first_vrf, pnf_dict, pnf_ris):
is_first_vrf = False
is_left_first_vrf = False
for ri_obj in pnf_ris:
if ri_obj in first_vrf:
is_first_vrf = True
else:
is_first_vrf = False
export_set = copy.copy(ri_obj.export_targets)
import_set = copy.copy(ri_obj.import_targets)
for ri2_id in ri_obj.routing_instances:
ri2 = RoutingInstanceDM.get(ri2_id)
if ri2 is None:
continue
import_set |= ri2.export_targets
pnf_inters = set()
static_routes = self.compute_pnf_static_route(ri_obj, pnf_dict)
if_type = ""
for vmi_uuid in ri_obj.virtual_machine_interfaces:
vmi_obj = VirtualMachineInterfaceDM.get(vmi_uuid)
if vmi_obj.service_instance is not None:
si_obj = ServiceInstanceDM.get(vmi_obj.service_instance)
if_type = vmi_obj.service_interface_type
pnf_li_inters = pnf_dict[
vmi_obj.service_instance][if_type]
if if_type == 'left' and is_first_vrf:
is_left_first_vrf = True
else:
is_left_first_vrf = False
for pnf_li in pnf_li_inters:
pnf_inters.add(pnf_li)
if pnf_inters:
vrf_name = self.get_pnf_vrf_name(
si_obj, if_type, is_left_first_vrf)
vrf_interfaces = pnf_inters
ri_conf = { 'ri_name': vrf_name }
ri_conf['import_targets'] = import_set
ri_conf['export_targets'] = export_set
ri_conf['interfaces'] = vrf_interfaces
ri_conf['static_routes'] = static_routes
ri_conf['no_vrf_table_label'] = True
self.config_manager.add_routing_instance(ri_conf)
def push_config(self):
if self.delete_config() or not self.is_vnc_managed():
return
self.config_manager.reset_bgp_config()
bgp_router = BgpRouterDM.get(self.bgp_router)
if bgp_router:
for peer_uuid, attr in bgp_router.bgp_routers.items():
peer = BgpRouterDM.get(peer_uuid)
if peer is None:
continue
local_as = bgp_router.params.get('local_autonomous_system') or \
bgp_router.params.get('autonomous_system')
peer_as = peer.params.get('local_autonomous_system') or \
peer.params.get('autonomous_system')
external = (local_as != peer_as)
self.config_manager.add_bgp_peer(peer.params['address'],
peer.params, attr, external)
self.config_manager.set_bgp_config(bgp_router.params)
self.config_manager.set_global_routing_options(bgp_router.params)
bgp_router_ips = bgp_router.get_all_bgp_router_ips()
tunnel_ip = self.dataplane_ip
if not tunnel_ip and bgp_router.params:
tunnel_ip = bgp_router.params.get('address')
if (tunnel_ip and self.is_valid_ip(tunnel_ip)):
self.config_manager.add_dynamic_tunnels(
tunnel_ip,
GlobalSystemConfigDM.ip_fabric_subnets,
bgp_router_ips)
vn_dict = self.get_vn_li_map()
self.evaluate_vn_irb_ip_map(set(vn_dict.keys()))
vn_irb_ip_map = self.get_vn_irb_ip_map()
first_vrf = []
pnfs = self.config_pnf_logical_interface()
pnf_dict = pnfs[0]
pnf_ris = pnfs[1]
for vn_id, interfaces in vn_dict.items():
vn_obj = VirtualNetworkDM.get(vn_id)
if (vn_obj is None or
vn_obj.get_vxlan_vni() is None or
vn_obj.vn_network_id is None):
continue
export_set = None
import_set = None
for ri_id in vn_obj.routing_instances:
# Find the primary RI by matching the name
ri_obj = RoutingInstanceDM.get(ri_id)
if ri_obj is None:
continue
if ri_obj.fq_name[-1] == vn_obj.fq_name[-1]:
vrf_name_l2 = DMUtils.make_vrf_name(vn_obj.fq_name[-1],
vn_obj.vn_network_id, 'l2')
vrf_name_l3 = DMUtils.make_vrf_name(vn_obj.fq_name[-1],
vn_obj.vn_network_id, 'l3')
export_set = copy.copy(ri_obj.export_targets)
import_set = copy.copy(ri_obj.import_targets)
for ri2_id in ri_obj.routing_instances:
ri2 = RoutingInstanceDM.get(ri2_id)
if ri2 in pnf_ris:
first_vrf.append(ri2)
if ri2 is None:
continue
import_set |= ri2.export_targets
if vn_obj.get_forwarding_mode() in ['l2', 'l2_l3']:
irb_ips = None
if vn_obj.get_forwarding_mode() == 'l2_l3':
irb_ips = vn_irb_ip_map.get(vn_id, [])
ri_conf = { 'ri_name': vrf_name_l2 }
ri_conf['is_l2'] = True
ri_conf['is_l2_l3'] = (vn_obj.get_forwarding_mode() == 'l2_l3')
ri_conf['import_targets'] = import_set
ri_conf['export_targets'] = export_set
ri_conf['prefixes'] = vn_obj.get_prefixes()
ri_conf['gateways'] = irb_ips
ri_conf['router_external'] = vn_obj.router_external
ri_conf['interfaces'] = interfaces
ri_conf['vni'] = vn_obj.get_vxlan_vni()
ri_conf['network_id'] = vn_obj.vn_network_id
self.config_manager.add_routing_instance(ri_conf)
if vn_obj.get_forwarding_mode() in ['l3', 'l2_l3']:
interfaces = []
if vn_obj.get_forwarding_mode() == 'l2_l3':
interfaces = [
JunosInterface(
'irb.' + str(vn_obj.vn_network_id),
'l3', 0)]
ri_conf = { 'ri_name': vrf_name_l3 }
ri_conf['is_l2_l3'] = (vn_obj.get_forwarding_mode() == 'l2_l3')
ri_conf['import_targets'] = import_set
ri_conf['export_targets'] = export_set
ri_conf['prefixes'] = vn_obj.get_prefixes()
ri_conf['router_external'] = vn_obj.router_external
ri_conf['interfaces'] = interfaces
self.config_manager.add_routing_instance(ri_conf)
break
if (export_set is not None and
self.is_junos_service_ports_enabled() and
len(vn_obj.instance_ip_map) > 0):
service_port_ids = DMUtils.get_service_ports(vn_obj.vn_network_id)
if self.is_service_port_id_valid(service_port_ids[0]) == False:
self._logger.error("DM can't allocate service interfaces for \
(vn, vn-id)=(%s,%s)" % (
vn_obj.fq_name,
vn_obj.vn_network_id))
else:
vrf_name = DMUtils.make_vrf_name(vn_obj.fq_name[-1],
vn_obj.vn_network_id, 'l3', True)
interfaces = []
service_ports = self.junos_service_ports.get(
'service_port')
interfaces.append(
JunosInterface(
service_ports[0] + "." + str(service_port_ids[0]),
'l3', 0))
interfaces.append(
JunosInterface(
service_ports[0] + "." + str(service_port_ids[1]),
'l3', 0))
ri_conf = { 'ri_name': vrf_name }
ri_conf['import_targets'] = import_set
ri_conf['interfaces'] = interfaces
ri_conf['fip_map'] = vn_obj.instance_ip_map
ri_conf['network_id'] = vn_obj.vn_network_id
ri_conf['restrict_proxy_arp'] = vn_obj.router_external
self.config_manager.add_routing_instance(ri_conf)
# Add PNF ri configuration
self.add_pnf_vrfs(first_vrf, pnf_dict, pnf_ris)
config_size = self.config_manager.send_bgp_config()
self.set_conf_sent_state(True)
self.uve_send()
if self.config_manager.retry():
# failed commit: set repush interval upto max value
self.config_repush_interval = min([2 * self.config_repush_interval,
PushConfigState.get_repush_max_interval()])
self.block_and_set_config_state(self.config_repush_interval)
else:
# successful commit: reset repush interval to base
self.config_repush_interval = PushConfigState.get_repush_interval()
if PushConfigState.get_push_delay_enable():
# sleep, delay=compute max delay between two successive commits
gevent.sleep(self.get_push_config_interval(config_size))
# end push_config
def get_push_config_interval(self, last_config_size):
config_delay = int(
(last_config_size/1000) * PushConfigState.get_push_delay_per_kb())
delay = min([PushConfigState.get_push_delay_max(), config_delay])
return delay
def is_service_port_id_valid(self, service_port_id):
# mx allowed ifl unit number range is (1, 16385) for service ports
if service_port_id < 1 or service_port_id > 16384:
return False
return True
# end is_service_port_id_valid
def uve_send(self, deleted=False):
pr_trace = UvePhysicalRouterConfig(
name=self.name,
ip_address=self.management_ip,
connected_bgp_router=self.bgp_router,
auto_conf_enabled=self.vnc_managed,
product_info=str(self.vendor) + ':' + str(self.product))
if deleted:
pr_trace.deleted = True
pr_msg = UvePhysicalRouterConfigTrace(
data=pr_trace,
sandesh=PhysicalRouterDM._sandesh)
pr_msg.send(sandesh=PhysicalRouterDM._sandesh)
return
commit_stats = self.config_manager.get_commit_stats()
if self.is_vnc_managed():
pr_trace.netconf_enabled_status = True
pr_trace.last_commit_time = commit_stats['last_commit_time']
pr_trace.last_commit_duration = commit_stats[
'last_commit_duration']
pr_trace.commit_status_message = commit_stats[
'commit_status_message']
pr_trace.total_commits_sent_since_up = commit_stats[
'total_commits_sent_since_up']
else:
pr_trace.netconf_enabled_status = False
pr_msg = UvePhysicalRouterConfigTrace(
data=pr_trace, sandesh=PhysicalRouterDM._sandesh)
pr_msg.send(sandesh=PhysicalRouterDM._sandesh)
# end uve_send
# end PhysicalRouterDM
class GlobalVRouterConfigDM(DBBaseDM):
_dict = {}
obj_type = 'global_vrouter_config'
global_vxlan_id_mode = None
global_forwarding_mode = None
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.update(obj_dict)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
new_global_vxlan_id_mode = obj.get('vxlan_network_identifier_mode')
new_global_forwarding_mode = obj.get('forwarding_mode')
if (GlobalVRouterConfigDM.global_vxlan_id_mode !=
new_global_vxlan_id_mode or
GlobalVRouterConfigDM.global_forwarding_mode !=
new_global_forwarding_mode):
GlobalVRouterConfigDM.global_vxlan_id_mode = \
new_global_vxlan_id_mode
GlobalVRouterConfigDM.global_forwarding_mode = \
new_global_forwarding_mode
self.update_physical_routers()
# end update
def update_physical_routers(self):
for pr in PhysicalRouterDM.values():
pr.set_config_state()
# end update_physical_routers
@classmethod
def is_global_vxlan_id_mode_auto(cls):
if (cls.global_vxlan_id_mode is not None and
cls.global_vxlan_id_mode == 'automatic'):
return True
return False
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
# end delete
# end GlobalVRouterConfigDM
class GlobalSystemConfigDM(DBBaseDM):
_dict = {}
obj_type = 'global_system_config'
global_asn = None
ip_fabric_subnets = None
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.physical_routers = set()
self.update(obj_dict)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
GlobalSystemConfigDM.global_asn = obj.get('autonomous_system')
GlobalSystemConfigDM.ip_fabric_subnets = obj.get('ip_fabric_subnets')
self.set_children('physical_router', obj)
# end update
@classmethod
def get_global_asn(cls):
return cls.global_asn
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
# end delete
# end GlobalSystemConfigDM
class PhysicalInterfaceDM(DBBaseDM):
_dict = {}
obj_type = 'physical_interface'
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.virtual_machine_interfaces = set()
self.physical_interfaces = set()
self.update(obj_dict)
pr = PhysicalRouterDM.get(self.physical_router)
if pr:
pr.physical_interfaces.add(self.uuid)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
self.physical_router = self.get_parent_uuid(obj)
self.logical_interfaces = set([li['uuid'] for li in
obj.get('logical_interfaces', [])])
self.name = obj.get('fq_name')[-1]
self.update_multiple_refs('virtual_machine_interface', obj)
self.update_multiple_refs('physical_interface', obj)
# end update
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
pr = PhysicalRouterDM.get(obj.physical_router)
if pr:
pr.physical_interfaces.discard(obj.uuid)
del cls._dict[uuid]
# end delete
# end PhysicalInterfaceDM
class LogicalInterfaceDM(DBBaseDM):
_dict = {}
obj_type = 'logical_interface'
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.virtual_machine_interface = None
self.vlan_tag = 0
self.li_type = None
self.update(obj_dict)
if self.physical_interface:
parent = PhysicalInterfaceDM.get(self.physical_interface)
elif self.physical_router:
parent = PhysicalRouterDM.get(self.physical_router)
if parent:
parent.logical_interfaces.add(self.uuid)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
if obj['parent_type'] == 'physical-router':
self.physical_router = self.get_parent_uuid(obj)
self.physical_interface = None
else:
self.physical_interface = self.get_parent_uuid(obj)
self.physical_router = None
self.vlan_tag = obj.get("logical_interface_vlan_tag", 0)
self.li_type = obj.get("logical_interface_type", 0)
self.update_single_ref('virtual_machine_interface', obj)
self.name = obj['fq_name'][-1]
# end update
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
if obj.physical_interface:
parent = PhysicalInterfaceDM.get(obj.physical_interface)
elif obj.physical_router:
parent = PhysicalInterfaceDM.get(obj.physical_router)
if parent:
parent.logical_interfaces.discard(obj.uuid)
obj.update_single_ref('virtual_machine_interface', {})
del cls._dict[uuid]
# end delete
# end LogicalInterfaceDM
class FloatingIpDM(DBBaseDM):
_dict = {}
obj_type = 'floating_ip'
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.virtual_machine_interface = None
self.floating_ip_address = None
self.update(obj_dict)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
self.floating_ip_address = obj.get("floating_ip_address")
self.public_network = self.get_pool_public_network(
self.get_parent_uuid(obj))
self.update_single_ref('virtual_machine_interface', obj)
# end update
def get_pool_public_network(self, pool_uuid):
pool_obj = self.read_obj(pool_uuid, "floating_ip_pool")
if pool_obj is None:
return None
return self.get_parent_uuid(pool_obj)
# end get_pool_public_network
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
obj.update_single_ref('virtual_machine_interface', {})
del cls._dict[uuid]
# end delete
# end FloatingIpDM
class InstanceIpDM(DBBaseDM):
_dict = {}
obj_type = 'instance_ip'
def __init__(self, uuid, obj_dict=None):
self.uuid = uuid
self.instance_ip_address = None
self.virtual_machine_interface = None
self.update(obj_dict)
# end __init__
def update(self, obj=None):
if obj is None:
obj = self.read_obj(self.uuid)
self.instance_ip_address = obj.get("instance_ip_address")
self.update_single_ref('virtual_machine_interface', obj)
# end update
@classmethod
def delete(cls, uuid):
if uuid not in cls._dict:
return
obj = cls._dict[uuid]
obj.update_single_ref('virtual_machine_interface', {})
del cls._dict[uuid]
# end delete
# end InstanceIpDM
class VirtualMachineInterfaceDM(DBBaseDM):
_dict = {}