-
Notifications
You must be signed in to change notification settings - Fork 390
/
virtual_machine_interface.py
1816 lines (1646 loc) · 73.8 KB
/
virtual_machine_interface.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) 2019 Juniper Networks, Inc. All rights reserved.
#
from builtins import range
from builtins import str
import os
from cfgm_common import _obj_serializer_all
from cfgm_common import jsonutils as json
from cfgm_common.exceptions import NoIdError
from cfgm_common.zkclient import ZookeeperLock
from netaddr import AddrFormatError
from netaddr import IPAddress
from vnc_api.gen.resource_common import VirtualMachineInterface
from vnc_api.gen.resource_common import VirtualPortGroup
from vnc_api.gen.resource_xsd import MacAddressesType
from vnc_api.gen.resource_xsd import PolicyBasedForwardingRuleType
from vnc_cfg_api_server.context import get_context
from vnc_cfg_api_server.resources._resource_base import ResourceMixin
class VirtualMachineInterfaceServer(ResourceMixin, VirtualMachineInterface):
portbindings = {}
portbindings['VIF_TYPE_VROUTER'] = 'vrouter'
portbindings['VIF_TYPE_HW_VEB'] = 'hw_veb'
portbindings['VNIC_TYPE_NORMAL'] = 'normal'
portbindings['VNIC_TYPE_DIRECT'] = 'direct'
portbindings['VNIC_TYPE_BAREMETAL'] = 'baremetal'
portbindings['VNIC_TYPE_VIRTIO_FORWARDER'] = 'virtio-forwarder'
portbindings['PORT_FILTER'] = True
portbindings['VIF_TYPE_VHOST_USER'] = 'vhostuser'
portbindings['VHOST_USER_MODE'] = 'vhostuser_mode'
portbindings['VHOST_USER_MODE_SERVER'] = 'server'
portbindings['VHOST_USER_MODE_CLIENT'] = 'client'
portbindings['VHOST_USER_SOCKET'] = 'vhostuser_socket'
portbindings['VHOST_USER_VROUTER_PLUG'] = 'vhostuser_vrouter_plug'
vhostuser_sockets_dir = '/var/run/vrouter/'
NIC_NAME_LEN = 14
@staticmethod
def _kvp_to_dict(kvps):
return dict((kvp['key'], kvp['value']) for kvp in kvps)
@classmethod
def _check_vrouter_link(cls, vmi_data, kvp_dict, obj_dict, db_conn):
api_server = db_conn.get_api_server()
host_id = kvp_dict.get('host_id')
if not host_id:
return
vm_refs = vmi_data.get('virtual_machine_refs')
if not vm_refs:
vm_refs = obj_dict.get('virtual_machine_refs')
if not vm_refs:
return
vrouter_fq_name = ['default-global-system-config', host_id]
try:
vrouter_id = db_conn.fq_name_to_uuid('virtual_router',
vrouter_fq_name)
except NoIdError:
return
# if virtual_machine_refs is an empty list delete vrouter link
if ('virtual_machine_refs' in obj_dict and not
obj_dict['virtual_machine_refs']):
api_server.internal_request_ref_update(
'virtual-router',
vrouter_id,
'DELETE',
'virtual_machine',
vm_refs[0]['uuid'])
return
api_server.internal_request_ref_update(
'virtual-router',
vrouter_id,
'ADD',
'virtual-machine',
vm_refs[0]['uuid'])
@classmethod
def _check_bridge_domain_vmi_association(
cls, obj_dict, db_dict, db_conn, vn_uuid, create):
if ('virtual_network_refs' not in obj_dict and
'bridge_domain_refs' not in obj_dict):
return True, ''
vn_fq_name = []
if vn_uuid:
vn_fq_name = db_conn.uuid_to_fq_name(vn_uuid)
bridge_domain_links = {}
bd_refs = obj_dict.get('bridge_domain_refs') or []
for bd in bd_refs:
bd_fq_name = bd['to']
if bd_fq_name[0:3] != vn_fq_name:
msg = ("Virtual machine interface(%s) can only refer to "
"bridge domain belonging to virtual network(%s)" %
(obj_dict['uuid'], vn_uuid))
return False, msg
bd_uuid = bd.get('uuid')
if not bd_uuid:
bd_uuid = db_conn.fq_name_to_uuid('bridge_domain', bd_fq_name)
bdmt = bd['attr']
vlan_tag = bdmt['vlan_tag']
if vlan_tag in bridge_domain_links:
msg = ("Virtual machine interface(%s) already refers to "
"bridge domain(%s) for vlan tag %d" %
(obj_dict['uuid'], bd_uuid, vlan_tag))
return False, msg
bridge_domain_links[vlan_tag] = bd_uuid
# disallow final state where bd exists but vn doesn't
if 'virtual_network_refs' in obj_dict:
vn_refs = obj_dict['virtual_network_refs']
else:
vn_refs = (db_dict or {}).get('virtual_network_refs')
if not vn_refs:
if 'bridge_domain_refs' not in obj_dict:
bd_refs = db_dict.get('bridge_domain_refs')
if bd_refs:
msg = ("Virtual network can not be removed on virtual machine "
"interface(%s) while it refers a bridge domain" %
(obj_dict['uuid']))
return False, msg
return True, ''
@classmethod
def _check_port_security_and_address_pairs(cls, obj_dict, db_dict=None):
if ('port_security_enabled' not in obj_dict and
'virtual_machine_interface_allowed_address_pairs' not in
obj_dict):
return True, ""
if not db_dict:
db_dict = {}
if 'port_security_enabled' in obj_dict:
port_security = obj_dict.get('port_security_enabled', True)
else:
port_security = db_dict.get('port_security_enabled', True)
if 'virtual_machine_interface_allowed_address_pairs' in obj_dict:
address_pairs = obj_dict.get(
'virtual_machine_interface_allowed_address_pairs')
else:
address_pairs = db_dict.get(
'virtual_machine_interface_allowed_address_pairs')
# Validate the format of allowed_address_pair
if address_pairs:
for aap in address_pairs.get('allowed_address_pair', {}):
try:
IPAddress(aap.get('ip').get('ip_prefix'))
except AddrFormatError as e:
return (False, (400, str(e)))
if (not port_security and address_pairs and
address_pairs.get('allowed_address_pair')):
msg = "Allowed address pairs are not allowed when port "\
"security is disabled"
return False, (400, msg)
return True, ""
@classmethod
def _check_service_health_check_type(cls, obj_dict, db_dict, db_conn):
service_health_check_refs = obj_dict.get('service_health_check_refs')
if not service_health_check_refs:
return True, ''
if obj_dict and obj_dict.get('port_tuple_refs'):
return True, ''
if db_dict and db_dict.get('port_tuple_refs'):
return True, ''
for shc in service_health_check_refs or []:
if 'uuid' in shc:
shc_uuid = shc['uuid']
else:
shc_fq_name = shc['to']
shc_uuid = db_conn.fq_name_to_uuid(
'service_health_check', shc_fq_name)
ok, result = cls.dbe_read(
db_conn,
'service_health_check',
shc_uuid,
obj_fields=['service_health_check_properties'])
if not ok:
return ok, result
shc_type = result['service_health_check_properties'
]['health_check_type']
if shc_type != 'link-local':
msg = ("Virtual machine interface(%s) of non service vm can "
"only refer link-local type service health check" %
obj_dict['uuid'])
return False, (400, msg)
return True, ''
@classmethod
def _is_port_bound(cls, obj_dict, new_kvp_dict):
"""Check whatever port is bound.
For any NON 'baremetal port' we assume port is bound when it is linked
to either VM or Vrouter.
For any 'baremetal' port we assume it is bound when it has set:
* binding:local_link_information
* binding:host_id
:param obj_dict: Current port dict to check
:param new_kvp_dict: KVP dict of port update.
:returns: True if port is bound, False otherwise.
"""
bindings = obj_dict['virtual_machine_interface_bindings']
kvps = bindings['key_value_pair']
kvp_dict = cls._kvp_to_dict(kvps)
old_vnic_type = kvp_dict.get('vnic_type')
new_vnic_type = new_kvp_dict.get('vnic_type')
if new_vnic_type == cls.portbindings['VNIC_TYPE_BAREMETAL']:
return False
if old_vnic_type == cls.portbindings['VNIC_TYPE_BAREMETAL']:
if (kvp_dict.get('profile', {}).get('local_link_information') and
kvp_dict.get('host_id')):
return True
else:
return (obj_dict.get('logical_router_back_refs') or
obj_dict.get('virtual_machine_refs'))
@classmethod
def _get_port_vhostuser_socket_name(cls, id=None):
name = 'tap' + id
name = name[:cls.NIC_NAME_LEN]
return cls.vhostuser_sockets_dir + 'uvh_vif_' + name
@classmethod
def _is_dpdk_enabled(cls, obj_dict, db_conn, host_id=None):
if host_id is None or not host_id:
if obj_dict.get('virtual_machine_interface_bindings'):
bindings = obj_dict['virtual_machine_interface_bindings']
kvps = bindings['key_value_pair']
kvp_dict = cls._kvp_to_dict(kvps)
host_id = kvp_dict.get('host_id')
if not host_id or host_id == 'null':
return True, False
else:
return True, False
vrouter = None
vrouter_fq_name = ['default-global-system-config', host_id]
fields = ['uuid', 'fq_name', 'virtual_router_dpdk_enabled']
ok, result = cls.server.get_resource_class('virtual_router').locate(
vrouter_fq_name, create_it=False, fields=fields)
if not ok and result[0] == 404:
ok, result, _ = db_conn.dbe_list('virtual_router',
field_names=fields)
if not ok:
return False, result
vrs = result
for vr in vrs:
fullname = vr['fq_name'][-1].split('.')
for hname in fullname:
if host_id.partition('.')[0] == hname:
vrouter = vr
break
if vr == vrouter:
break
if not vrouter:
return True, result
elif not ok:
return False, result
else:
vrouter = result
return True, vrouter.get('virtual_router_dpdk_enabled', False)
@classmethod
def _kvps_update(cls, kvps, kvp):
key = kvp['key']
value = kvp['value']
kvp_dict = cls._kvp_to_dict(kvps)
if key not in list(kvp_dict.keys()):
if value:
kvps.append(kvp)
else:
for i in range(len(kvps)):
kvps_dict = dict(kvps[i])
if key == kvps_dict.get('key'):
if value:
kvps[i]['value'] = value
break
else:
del kvps[i]
break
@classmethod
def _kvps_prop_update(cls, obj_dict, kvps, prop_collection_updates,
vif_type, vif_details, prop_set):
if obj_dict:
cls._kvps_update(kvps, vif_type)
cls._kvps_update(kvps, vif_details)
else:
if prop_set:
vif_type_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'set',
'value': vif_type,
'position': 'vif_type',
}
vif_details_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'set',
'value': vif_details,
'position': 'vif_details',
}
else:
vif_type_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'delete',
'value': vif_type,
'position': 'vif_type',
}
vif_details_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'delete',
'value': vif_details,
'position': 'vif_details',
}
prop_collection_updates.append(vif_details_prop)
prop_collection_updates.append(vif_type_prop)
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
vn_dict = obj_dict['virtual_network_refs'][0]
vn_uuid = vn_dict.get('uuid')
if not vn_uuid:
vn_fq_name = vn_dict.get('to')
if not vn_fq_name:
msg = ("Virtual Machine Interface must have valide Virtual "
"Network reference")
return False, (400, msg)
vn_uuid = db_conn.fq_name_to_uuid('virtual_network', vn_fq_name)
ok, result = cls.dbe_read(
db_conn,
'virtual_network',
vn_uuid,
obj_fields=['parent_uuid', 'provider_properties'])
if not ok:
return ok, result
vn_dict = result
vlan_tag = (obj_dict.get('virtual_machine_interface_properties') or {}
).get('sub_interface_vlan_tag') or 0
if vlan_tag < 0 or vlan_tag > 4094:
return False, (400, "Invalid sub-interface VLAN tag ID: %s" %
vlan_tag)
if vlan_tag and 'virtual_machine_interface_refs' in obj_dict:
primary_vmi_ref = obj_dict['virtual_machine_interface_refs']
ok, primary_vmi = cls.dbe_read(
db_conn,
'virtual_machine_interface',
primary_vmi_ref[0]['uuid'],
obj_fields=['virtual_machine_interface_refs',
'virtual_machine_interface_properties'])
if not ok:
return ok, primary_vmi
primary_vmi_vlan_tag = primary_vmi.get(
'virtual_machine_interface_properties', {}).get(
'sub_interface_vlan_tag')
if primary_vmi_vlan_tag:
msg = ("sub interface can't have another sub interface as "
"it's primary port")
return False, (400, msg)
sub_vmi_refs = primary_vmi.get('virtual_machine_interface_refs',
{})
sub_vmi_uuids = [ref['uuid'] for ref in sub_vmi_refs]
if sub_vmi_uuids:
ok, sub_vmis, _ = db_conn.dbe_list(
'virtual_machine_interface', obj_uuids=sub_vmi_uuids,
field_names=['virtual_machine_interface_properties'])
if not ok:
return ok, sub_vmis
sub_vmi_vlan_tags = [((vmi.get(
'virtual_machine_interface_properties') or {}).get(
'sub_interface_vlan_tag')) for vmi in sub_vmis]
if vlan_tag in sub_vmi_vlan_tags:
msg = "Two sub interfaces under same primary port "\
"can't have same Vlan tag"
return (False, (400, msg))
ok, error = cls._check_bridge_domain_vmi_association(
obj_dict, None, db_conn, vn_uuid, True)
if not ok:
return (False, (400, error))
inmac = None
if 'virtual_machine_interface_mac_addresses' in obj_dict:
mc = obj_dict['virtual_machine_interface_mac_addresses']
if 'mac_address' in mc and mc['mac_address']:
inmac = [m.replace("-", ":") for m in mc['mac_address']]
if inmac is not None:
mac_addrs_obj = MacAddressesType(inmac)
else:
mac_addr = cls.addr_mgmt.mac_alloc(obj_dict)
mac_addrs_obj = MacAddressesType([mac_addr])
mac_addrs_json = json.dumps(
mac_addrs_obj,
default=lambda o: dict((k, v)
for k, v in o.__dict__.items()))
mac_addrs_dict = json.loads(mac_addrs_json)
obj_dict['virtual_machine_interface_mac_addresses'] = mac_addrs_dict
kvps = []
if 'virtual_machine_interface_bindings' in obj_dict:
bindings = obj_dict['virtual_machine_interface_bindings']
kvps = bindings['key_value_pair']
kvp_dict = cls._kvp_to_dict(kvps)
if (kvp_dict.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_DIRECT'] or
kvp_dict.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_VIRTIO_FORWARDER']):
# If the segmentation_id in provider_properties is set, then
# a hw_veb VIF is requested.
if ('provider_properties' in vn_dict and
vn_dict['provider_properties'] is not None and
'segmentation_id' in vn_dict['provider_properties']):
kvp_dict['vif_type'] = cls.portbindings['VIF_TYPE_HW_VEB']
vif_type = {
'key': 'vif_type',
'value': cls.portbindings['VIF_TYPE_HW_VEB'],
}
vlan = vn_dict['provider_properties']['segmentation_id']
vif_params = {
'port_filter': cls.portbindings['PORT_FILTER'],
'vlan': str(vlan),
}
vif_details = {
'key': 'vif_details',
'value': json.dumps(vif_params),
}
kvps.append(vif_details)
kvps.append(vif_type)
else:
# An offloaded port is requested
vnic_type = {
'key': 'vnic_type',
'value': kvp_dict.get('vnic_type'),
}
if (kvp_dict.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_VIRTIO_FORWARDER']):
vif_params = {
cls.portbindings['VHOST_USER_MODE']:
cls.portbindings['VHOST_USER_MODE_SERVER'],
cls.portbindings['VHOST_USER_SOCKET']:
cls._get_port_vhostuser_socket_name(
obj_dict['uuid'])
}
vif_details = {
'key': 'vif_details',
'value': json.dumps(vif_params),
}
kvps.append(vif_details)
kvps.append(vnic_type)
if 'vif_type' not in kvp_dict:
vif_type = {'key': 'vif_type',
'value': cls.portbindings['VIF_TYPE_VROUTER']}
kvps.append(vif_type)
if 'vnic_type' not in kvp_dict:
vnic_type = {'key': 'vnic_type',
'value': cls.portbindings['VNIC_TYPE_NORMAL']}
kvps.append(vnic_type)
kvp_dict = cls._kvp_to_dict(kvps)
if (kvp_dict.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_NORMAL']):
(ok, result) = cls._is_dpdk_enabled(obj_dict, db_conn)
if not ok:
return ok, result
elif result:
vif_type = {
'key': 'vif_type',
'value': cls.portbindings['VIF_TYPE_VHOST_USER'],
}
vif_params = {
cls.portbindings['VHOST_USER_MODE']:
cls.portbindings['VHOST_USER_MODE_SERVER'],
cls.portbindings['VHOST_USER_SOCKET']:
cls._get_port_vhostuser_socket_name(obj_dict['uuid']),
cls.portbindings['VHOST_USER_VROUTER_PLUG']: True
}
vif_details = {
'key': 'vif_details',
'value': json.dumps(vif_params),
}
cls._kvps_update(kvps, vif_type)
cls._kvps_update(kvps, vif_details)
else:
vif_type = {'key': 'vif_type', 'value': None}
cls._kvps_update(kvps, vif_type)
(ok, result) = cls._check_port_security_and_address_pairs(obj_dict)
if not ok:
return ok, result
(ok, result) = cls._check_service_health_check_type(obj_dict, None,
db_conn)
if not ok:
return ok, result
# Manage baremetal provisioning here
if kvps:
kvp_dict = cls._kvp_to_dict(kvps)
vnic_type = kvp_dict.get('vnic_type')
vpg_name = kvp_dict.get('vpg')
tor_port_vlan_id = kvp_dict.get('tor_port_vlan_id', 0)
if vnic_type == 'baremetal' and kvp_dict.get('profile'):
# Process only if port profile exists and physical links are
# specified
phy_links = json.loads(kvp_dict.get('profile'))
if phy_links and phy_links.get('local_link_information'):
links = phy_links['local_link_information']
is_untagged_vlan = False
if tor_port_vlan_id:
vlan_id = tor_port_vlan_id
is_untagged_vlan = True
else:
vlan_id = vlan_tag
vpg_uuid, ret_dict = cls._manage_vpg_association(
obj_dict['uuid'], cls.server, db_conn, links,
vpg_name, vn_uuid, vlan_id, is_untagged_vlan)
if not vpg_uuid:
return vpg_uuid, ret_dict
obj_dict['port_virtual_port_group_id'] = vpg_uuid
obj_dict.update(ret_dict)
return True, ""
@classmethod
def post_dbe_create(cls, tenant_name, obj_dict, db_conn):
api_server = db_conn.get_api_server()
# add a ref from VPG to this VMI
vpg_uuid = obj_dict.get('port_virtual_port_group_id')
if vpg_uuid:
api_server.internal_request_ref_update(
'virtual-port-group',
vpg_uuid,
'ADD',
'virtual-machine-interface',
obj_dict['uuid'],
relax_ref_for_delete=True)
# Create ref to native/vn-default routing instance
vn_refs = obj_dict.get('virtual_network_refs')
if not vn_refs:
return True, ''
vn_fq_name = vn_refs[0].get('to')
if not vn_fq_name:
vn_uuid = vn_refs[0]['uuid']
vn_fq_name = db_conn.uuid_to_fq_name(vn_uuid)
ri_fq_name = vn_fq_name[:]
ri_fq_name.append(vn_fq_name[-1])
ri_uuid = db_conn.fq_name_to_uuid('routing_instance', ri_fq_name)
attr = PolicyBasedForwardingRuleType(direction="both")
attr_as_dict = attr.__dict__
api_server.internal_request_ref_update(
'virtual-machine-interface', obj_dict['uuid'], 'ADD',
'routing-instance', ri_uuid,
attr=attr_as_dict)
return True, ''
@classmethod
def pre_dbe_update(cls, id, fq_name, obj_dict, db_conn,
prop_collection_updates=None, **kwargs):
ok, read_result = cls.dbe_read(db_conn, 'virtual_machine_interface',
id)
if not ok:
return ok, read_result
vn_uuid = None
if 'virtual_network_refs' in read_result:
vn_uuid = read_result['virtual_network_refs'][0].get('uuid')
ok, error = cls._check_bridge_domain_vmi_association(
obj_dict, read_result, db_conn, vn_uuid, False)
if not ok:
return False, (400, error)
# check if the vmi is a internal interface of a logical
# router
if (read_result.get('logical_router_back_refs') and
obj_dict.get('virtual_machine_refs')):
return (False,
(400, 'Logical router interface cannot be used by VM'))
# check if vmi is going to point to vm and if its using
# gateway address in iip, disallow
iip_class = cls.server.get_resource_class('instance_ip')
for iip_ref in read_result.get('instance_ip_back_refs') or []:
if (obj_dict.get('virtual_machine_refs') and
iip_class.is_gateway_ip(db_conn, iip_ref['uuid'])):
return (False, (400, 'Gateway IP cannot be used by VM port'))
vpg = None
if read_result.get('virtual_port_group_back_refs'):
vpg_refs = read_result.get('virtual_port_group_back_refs')
vpg_id = vpg_refs[0].get('uuid')
ok, vpg = cls.dbe_read(
db_conn, 'virtual_port_group',
vpg_id, obj_fields=['virtual_port_group_trunk_port_id'])
if not ok:
return ok, vpg
if ('virtual_machine_interface_refs' in obj_dict and
'virtual_machine_interface_refs' in read_result):
for ref in read_result['virtual_machine_interface_refs']:
if (ref not in obj_dict['virtual_machine_interface_refs'] and
vpg and
vpg.get('virtual_port_group_trunk_port_id') != id):
# Dont allow remove of vmi ref during update if it's
# a sub port
msg = "VMI ref delete not allowed during update"
return (False, (409, msg))
bindings = read_result.get('virtual_machine_interface_bindings') or {}
kvps = bindings.get('key_value_pair') or []
kvp_dict = cls._kvp_to_dict(kvps)
old_vnic_type = kvp_dict.get('vnic_type',
cls.portbindings['VNIC_TYPE_NORMAL'])
bindings = obj_dict.get('virtual_machine_interface_bindings') or {}
kvps = bindings.get('key_value_pair') or []
vmib = False
for oper_param in prop_collection_updates or []:
if (oper_param['field'] == 'virtual_machine_interface_bindings' and
oper_param['operation'] == 'set'):
vmib = True
kvps.append(oper_param['value'])
old_vlan = (read_result.get('virtual_machine_interface_properties') or
{}).get('sub_interface_vlan_tag') or 0
new_vlan = None
if 'virtual_machine_interface_properties' in obj_dict:
new_vlan = (obj_dict['virtual_machine_interface_properties'] or
{}).get('sub_interface_vlan_tag') or 0
# vRouter has limitations for VLAN tag update.
# But, In case of neutron trunk port, subports are created first
# and then associated a VLAN tag
# To take care of limitations of vRouter for vlan tag update
# we will limit any vlan update once a port has been made
# a sub-interface
if (new_vlan != old_vlan and
'virtual_machine_interface_refs' in read_result):
return False, (400, "Cannot change sub-interface VLAN tag ID")
ret_dict = None
if kvps:
kvp_dict = cls._kvp_to_dict(kvps)
new_vnic_type = kvp_dict.get('vnic_type', old_vnic_type)
tor_port_vlan_id = kvp_dict.get('tor_port_vlan_id', 0)
# IRONIC: allow for normal->baremetal change if bindings has
# link-local info
if new_vnic_type != 'baremetal':
if (old_vnic_type != new_vnic_type):
if cls._is_port_bound(read_result, kvp_dict):
msg = ("Vnic_type can not be modified when port is "
"linked to Vrouter or VM.")
return False, (409, msg)
# Manage the bindings for baremetal servers
vnic_type = kvp_dict.get('vnic_type')
vpg_name = kvp_dict.get('vpg')
if read_result.get('virtual_port_group_back_refs'):
vpg_name_db = (read_result.get(
'virtual_port_group_back_refs')[0]['to'][-1])
obj_dict['virtual_port_group_name'] = vpg_name_db
if vnic_type == 'baremetal':
phy_links = json.loads(kvp_dict.get('profile'))
if phy_links and phy_links.get('local_link_information'):
links = phy_links['local_link_information']
is_untagged_vlan = False
if tor_port_vlan_id:
vlan_id = tor_port_vlan_id
is_untagged_vlan = True
if (vlan_id != old_vlan and
'virtual_machine_interface_refs' in read_result):
return False, (400, "Cannot change VLAN ID")
else:
vlan_id = new_vlan
vpg_uuid, ret_dict = cls._manage_vpg_association(
id, cls.server, db_conn, links, vpg_name,
vn_uuid, vlan_id, is_untagged_vlan)
if not vpg_uuid:
return vpg_uuid, ret_dict
obj_dict['port_virtual_port_group_id'] = vpg_uuid
if old_vnic_type == cls.portbindings['VNIC_TYPE_DIRECT']:
cls._check_vrouter_link(read_result, kvp_dict, obj_dict, db_conn)
if 'virtual_machine_interface_bindings' in obj_dict or vmib:
bindings_port = read_result.get(
'virtual_machine_interface_bindings', {})
kvps_port = bindings_port.get('key_value_pair') or []
kvp_dict_port = cls._kvp_to_dict(kvps_port)
kvp_dict = cls._kvp_to_dict(kvps)
if (kvp_dict_port.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_VIRTIO_FORWARDER'] and
kvp_dict.get('host_id') != 'null'):
vif_type = {
'key': 'vif_type',
'value': cls.portbindings['VIF_TYPE_VROUTER'],
}
vif_params = {
cls.portbindings['VHOST_USER_MODE']:
cls.portbindings['VHOST_USER_MODE_SERVER'],
cls.portbindings['VHOST_USER_SOCKET']:
cls._get_port_vhostuser_socket_name(id),
cls.portbindings['VHOST_USER_VROUTER_PLUG']: True,
}
vif_details = {
'key': 'vif_details',
'value': json.dumps(vif_params),
}
cls._kvps_prop_update(obj_dict, kvps, prop_collection_updates,
vif_type, vif_details, True)
elif ((kvp_dict_port.get('vnic_type') ==
cls.portbindings['VNIC_TYPE_NORMAL'] or
kvp_dict_port.get('vnic_type') is None) and
kvp_dict.get('host_id') != 'null'):
(ok, result) = cls._is_dpdk_enabled(obj_dict, db_conn,
kvp_dict.get('host_id'))
if not ok:
return ok, result
elif result:
vif_type = {
'key': 'vif_type',
'value': cls.portbindings['VIF_TYPE_VHOST_USER'],
}
vif_params = {
cls.portbindings['VHOST_USER_MODE']:
cls.portbindings['VHOST_USER_MODE_SERVER'],
cls.portbindings['VHOST_USER_SOCKET']:
cls._get_port_vhostuser_socket_name(id),
cls.portbindings['VHOST_USER_VROUTER_PLUG']: True,
}
vif_details = {
'key': 'vif_details',
'value': json.dumps(vif_params),
}
cls._kvps_prop_update(
obj_dict,
kvps,
prop_collection_updates,
vif_type,
vif_details,
True)
else:
vif_type = {'key': 'vif_type', 'value': None}
vif_details = {'key': 'vif_details', 'value': None}
cls._kvps_prop_update(
obj_dict,
kvps,
prop_collection_updates,
vif_type,
vif_details,
False)
else:
vif_type = {'key': 'vif_type', 'value': None}
vif_details = {'key': 'vif_details', 'value': None}
if (kvp_dict_port.get('vnic_type') !=
cls.portbindings['VNIC_TYPE_DIRECT']):
if obj_dict and 'vif_details' in kvp_dict_port:
cls._kvps_update(kvps, vif_type)
cls._kvps_update(kvps, vif_details)
elif kvp_dict.get('host_id') == 'null':
vif_details_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'delete',
'value': vif_details,
'position': 'vif_details',
}
vif_type_prop = {
'field': 'virtual_machine_interface_bindings',
'operation': 'delete',
'value': vif_type,
'position': 'vif_type',
}
prop_collection_updates.append(vif_details_prop)
prop_collection_updates.append(vif_type_prop)
ok, result = cls._check_port_security_and_address_pairs(obj_dict,
read_result)
if not ok:
return ok, result
ok, result = cls._check_service_health_check_type(
obj_dict, read_result, db_conn)
if not ok:
return ok, result
return True, ret_dict
@classmethod
def _check_annotations(
cls, api_server, obj_uuid,
resource_type, annotation_key,
annotation_value, fail_if_exists=True):
"""Check given annotation exists in the given object.
Consider availability as PASS/FAIL based on
fail_if_exists.
:Args
: api_server: api_server connection object
: obj_uuid: UUID of the object on which
: annotations to be checked
: resource_type: resource type of object
: for which annotations to be checked
: annotation_key: key of the annotation
: annotation_value: value of the annotation
: fail_if_exists:
: consider failure when annotation exists
:Returns
: True, '': PASS condition
: (False, (<code>, msg): Fail condition
"""
# get this annotation.
# if exists Fail per fail_if_exists
result = api_server.internal_request_prop_collection_get(
resource_type, obj_uuid, 'annotations',
position=annotation_key)
if fail_if_exists and result:
# Exists but not expected
if result.get('annotations'):
return False, result
return True, result
@classmethod
def _add_annotations(
cls, api_server, obj_uuid,
resource_type, annotation_key,
annotation_value):
"""Add given annotation to the VPG object.
:Args
: api_server: api_server connection object
: obj_uuid: UUID of the object for which
: annotations to be added
: resource_type: resource type of object
: for which annotations to be added
: annotation_key: key of the annotation
: annotation_value: value of the annotation
:Returns
: True, '': PASS condition
: (False, (<code>, msg): Fail condition
"""
# format update dict
updates = [{'field': 'annotations',
'operation': 'set',
'value': {'key': annotation_key,
'value': annotation_value}}]
ok, result = api_server.internal_request_prop_collection(
obj_uuid, updates)
if not ok:
return False, result
return True, ''
@classmethod
def _delete_annotations(
cls, api_server, obj_uuid, resource_type,
annotation_keys):
"""Delete given annotations from the object.
:Args
: api_server: api_server connection object
: obj_uuid: UUID of the object for which
: annotations to be added
: resource_type: resource type of object
: for which annotations to be added
: annotation_keys: list of annotation keys
: Returns
: True, '': PASS condition
: (False, (<code>, msg): Fail condition
"""
# format update dict
updates = [{'field': 'annotations',
'operation': 'delete',
'position': annkey} for annkey in annotation_keys]
ok, result = api_server.internal_request_prop_collection(
obj_uuid, updates)
if not ok:
return False, result
return True, ''
@classmethod
def _check_unique_vn_vlan_in_vpg(
cls, db_conn, api_server,
vpg_uuid, vn_uuid, vmi_uuid,
vlan_id, validation):
"""Verify given vn:vlan is unique in the VPG.
:Args
: db_conn: db connection object
: api_server: api_server connection object
: vpg_uuid: UUID of virtual_port_group object
: vn_uuid: UUID of virtual_network
: vlan_id: ID of the VLAN
: validation:
: enterprise
: serviceprovider
:Returns
: True, '': PASS condition
: (False, (<code>, msg): Fail condition
"""
# annotation key for current object
ann_key = 'validation:%s/vn:%s/vlan_id:%s' % (
validation, vn_uuid, vlan_id)
ann_value = vmi_uuid
# ensure that it do not exists already
ok, result = cls._check_annotations(
api_server, vpg_uuid, 'virtual_port_group', ann_key,
ann_value, fail_if_exists=True)
if not ok:
result = result or {}
annotations = result.get('annotations') or []
for key_d, key in annotations:
if key_d.get('value') != vmi_uuid:
vtype, vn, vlan = key.split('/', 2)
msg = ("VN(%s):VLAN(%s) already exists "
"at VPG(%s). No more than one "
"Allowed in Fabric %s" % (
vn_uuid, vlan_id, vpg_uuid, vtype))
return (False, (400, msg))
return True, ''
@classmethod
def _add_unique_vn_vlan_in_vpg(
cls, db_conn, api_server, vpg_uuid, vn_uuid,
vlan_id, vmi_uuid, validation):
"""Add vn:vlan as an annotation to the VPG object.
:Args
: db_conn: db connection object
: api_server: api_server connection object
: vpg_uuid: UUID of virtual_port_group object
: vn_uuid: UUID of virtual_network
: vlan_id: ID of the VLAN
: validation:
: enterprise
: serviceprovider
:Returns
: True, '': PASS condition
: (False, (<code>, msg): Fail condition
"""
# annotation key for current object
ann_key = 'validation:%s/vn:%s/vlan_id:%d' % (
validation, vn_uuid, vlan_id)
ann_value = vmi_uuid
# ensure that it do not exists already
ok, result = cls._add_annotations(
api_server, vpg_uuid, 'virtual_port_group', ann_key,
ann_value)
if not ok:
return ok, result
return True, ''
@classmethod
def _check_add_one_untagged_vlan(
cls, db_conn, api_server, vpg_uuid,
vmi_uuid, vlan_id, is_untagged, validation):
"""Verify no untagged VLAN exists in the VPG.