This repository has been archived by the owner on Sep 26, 2019. It is now read-only.
/
resource_mapping.py
2276 lines (2026 loc) · 107 KB
/
resource_mapping.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
# 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 netaddr
from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
from neutron.api.v2 import attributes
from neutron.common import constants as const
from neutron.common import exceptions as n_exc
from neutron.common import log
from neutron import context as n_context
from neutron.db import model_base
from neutron.db import models_v2
from neutron.extensions import securitygroup as ext_sg
from neutron import manager
from neutron.notifiers import nova
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log as logging
from neutron.plugins.common import constants as pconst
from oslo.config import cfg
import sqlalchemy as sa
from gbpservice.neutron.db.grouppolicy import group_policy_db as gpdb
from gbpservice.neutron.db import servicechain_db # noqa
from gbpservice.neutron.services.grouppolicy import (
group_policy_driver_api as api)
from gbpservice.neutron.services.grouppolicy.common import constants as gconst
from gbpservice.neutron.services.grouppolicy.common import exceptions as exc
LOG = logging.getLogger(__name__)
class OwnedPort(model_base.BASEV2):
"""A Port owned by the resource_mapping driver."""
__tablename__ = 'gpm_owned_ports'
port_id = sa.Column(sa.String(36),
sa.ForeignKey('ports.id', ondelete='CASCADE'),
nullable=False, primary_key=True)
class OwnedSubnet(model_base.BASEV2):
"""A Subnet owned by the resource_mapping driver."""
__tablename__ = 'gpm_owned_subnets'
subnet_id = sa.Column(sa.String(36),
sa.ForeignKey('subnets.id', ondelete='CASCADE'),
nullable=False, primary_key=True)
class OwnedNetwork(model_base.BASEV2):
"""A Network owned by the resource_mapping driver."""
__tablename__ = 'gpm_owned_networks'
network_id = sa.Column(sa.String(36),
sa.ForeignKey('networks.id', ondelete='CASCADE'),
nullable=False, primary_key=True)
class OwnedRouter(model_base.BASEV2):
"""A Router owned by the resource_mapping driver."""
__tablename__ = 'gpm_owned_routers'
router_id = sa.Column(sa.String(36),
sa.ForeignKey('routers.id', ondelete='CASCADE'),
nullable=False, primary_key=True)
class PolicyRuleSetSGsMapping(model_base.BASEV2):
"""PolicyRuleSet to SGs mapping DB."""
__tablename__ = 'gpm_policy_rule_set_sg_mapping'
policy_rule_set_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_policy_rule_sets.id',
ondelete='CASCADE'),
nullable=False, primary_key=True)
provided_sg_id = sa.Column(sa.String(36),
sa.ForeignKey('securitygroups.id'))
consumed_sg_id = sa.Column(sa.String(36),
sa.ForeignKey('securitygroups.id'))
class PtgServiceChainInstanceMapping(model_base.BASEV2):
"""Policy Target Group to ServiceChainInstance mapping DB."""
__tablename__ = 'gpm_ptgs_servicechain_mapping'
provider_ptg_id = sa.Column(sa.String(36),
sa.ForeignKey('gp_policy_target_groups.id',
ondelete='CASCADE'),
nullable=False)
# Consumer PTG could be an External Policy
consumer_ptg_id = sa.Column(sa.String(36), nullable=False)
servicechain_instance_id = sa.Column(sa.String(36),
sa.ForeignKey('sc_instances.id',
ondelete='CASCADE'),
primary_key=True)
class ServicePolicyPTGIpAddressMapping(model_base.BASEV2):
"""Service Policy to IP Address mapping DB."""
__tablename__ = 'gpm_service_policy_ipaddress_mappings'
service_policy_id = sa.Column(
sa.String(36), sa.ForeignKey('gp_network_service_policies.id'),
nullable=False, primary_key=True)
policy_target_group = sa.Column(
sa.String(36), sa.ForeignKey('gp_policy_target_groups.id'),
nullable=False, primary_key=True)
ipaddress = sa.Column(sa.String(36))
class ResourceMappingDriver(api.PolicyDriver):
"""Resource Mapping driver for Group Policy plugin.
This driver implements group policy semantics by mapping group
policy resources to various other neutron resources.
"""
@log.log
def initialize(self):
self._cached_agent_notifier = None
self._nova_notifier = nova.Notifier()
def _reject_shared(self, object, type):
if object.get('shared'):
raise exc.InvalidSharedResource(type=type,
driver='resource_mapping')
def _reject_cross_tenant_ptg_l2p(self, context):
if context.current['l2_policy_id']:
l2p = context._plugin.get_l2_policy(
context._plugin_context, context.current['l2_policy_id'])
if l2p['tenant_id'] != context.current['tenant_id']:
raise (
exc.
CrossTenantPolicyTargetGroupL2PolicyNotSupported())
def _reject_cross_tenant_l2p_l3p(self, context):
# Can't create non shared L2p on a shared L3p
if context.current['l3_policy_id']:
l3p = context._plugin.get_l3_policy(
context._plugin_context,
context.current['l3_policy_id'])
if l3p['tenant_id'] != context.current['tenant_id']:
raise exc.CrossTenantL2PolicyL3PolicyNotSupported()
def _reject_non_shared_net_on_shared_l2p(self, context):
if context.current.get('shared') and context.current['network_id']:
net = self._core_plugin.get_network(
context._plugin_context, context.current['network_id'])
if not net.get('shared'):
raise exc.NonSharedNetworkOnSharedL2PolicyNotSupported()
def _reject_invalid_network_access(self, context):
# Validate if the explicit network belongs to the tenant.
# Are networks shared across tenants ??
# How to check if admin and if admin can access all networks ??
if context.current['network_id']:
network_id = context.current['network_id']
plugin_context = context._plugin_context
network = None
try:
network = self._core_plugin.get_network(plugin_context,
network_id)
except n_exc.NetworkNotFound:
raise exc.InvalidNetworkAccess(
msg="Can't access other tenants networks",
network_id=context.current['network_id'],
tenant_id=context.current['tenant_id'])
if network:
tenant_id_of_explicit_net = network['tenant_id']
if tenant_id_of_explicit_net != context.current['tenant_id']:
raise exc.InvalidNetworkAccess(
msg="Can't access other tenants networks",
network_id=context.current['network_id'],
tenant_id=context.current['tenant_id'])
def _reject_invalid_router_access(self, context):
# Validate if the explicit router(s) belong to the tenant.
# Are routers shared across tenants ??
# How to check if admin and if admin can access all routers ??
for router_id in context.current['routers']:
router = None
try:
router = self._l3_plugin.get_router(context._plugin_context,
router_id)
except n_exc.NotFound:
raise exc.InvalidRouterAccess(
msg="Can't access other tenants router",
router_id=router_id,
tenant_id=context.current['tenant_id'])
if router:
tenant_id_of_explicit_router = router['tenant_id']
curr_tenant_id = context.current['tenant_id']
if tenant_id_of_explicit_router != curr_tenant_id:
raise exc.InvalidRouterAccess(
msg="Can't access other tenants router",
router_id=router_id,
tenant_id=context.current['tenant_id'])
def _reject_multiple_redirects_in_rule(self, context):
policy_actions = context._plugin.get_policy_actions(
context._plugin_context,
filters={'id': context.current['policy_actions'],
'action_type': [gconst.GP_ACTION_REDIRECT]})
if len(policy_actions) > 1:
raise exc.MultipleRedirectActionsNotSupportedForRule()
def _reject_multiple_redirects_in_prs(self, context):
policy_rules = context._plugin.get_policy_rules(
context._plugin_context,
filters={'id': context.current['policy_rules']})
redirect_actions_list = []
for policy_rule in policy_rules:
policy_actions = context._plugin.get_policy_actions(
context._plugin_context,
filters={'id': policy_rule['policy_actions'],
'action_type': [gconst.GP_ACTION_REDIRECT]})
redirect_actions_list.extend(policy_actions)
if len(redirect_actions_list) > 1:
raise exc.MultipleRedirectActionsNotSupportedForPRS()
@log.log
def create_policy_target_precommit(self, context):
if not context.current['policy_target_group_id']:
raise exc.PolicyTargetRequiresPolicyTargetGroup()
if context.current['port_id']:
# Validate if explicit port's subnet
# is same as the subnet of PTG.
self._validate_pt_port_subnets(context)
@log.log
def create_policy_target_postcommit(self, context):
if not context.current['port_id']:
self._use_implicit_port(context)
self._assoc_ptg_sg_to_pt(context, context.current['id'],
context.current['policy_target_group_id'])
@log.log
def update_policy_target_precommit(self, context):
if (context.current['policy_target_group_id'] !=
context.original['policy_target_group_id']):
raise exc.PolicyTargetGroupUpdateOfPolicyTargetNotSupported()
@log.log
def update_policy_target_postcommit(self, context):
pass
@log.log
def delete_policy_target_precommit(self, context):
pass
@log.log
def delete_policy_target_postcommit(self, context):
sg_list = self._generate_list_of_sg_from_ptg(
context, context.current['policy_target_group_id'])
self._disassoc_sgs_from_port(context._plugin_context,
context.current['port_id'], sg_list)
port_id = context.current['port_id']
self._cleanup_port(context._plugin_context, port_id)
@log.log
def create_policy_target_group_precommit(self, context):
self._reject_cross_tenant_ptg_l2p(context)
self._validate_ptg_subnets(context)
@log.log
def create_policy_target_group_postcommit(self, context):
subnets = context.current['subnets']
if subnets:
l2p_id = context.current['l2_policy_id']
l2p = context._plugin.get_l2_policy(context._plugin_context,
l2p_id)
l3p_id = l2p['l3_policy_id']
l3p = context._plugin.get_l3_policy(context._plugin_context,
l3p_id)
router_id = l3p['routers'][0] if l3p['routers'] else None
for subnet_id in subnets:
self._use_explicit_subnet(context._plugin_context, subnet_id,
router_id)
else:
self._use_implicit_subnet(context)
self._handle_network_service_policy(context)
self._handle_policy_rule_sets(context)
self._update_default_security_group(context._plugin_context,
context.current['id'],
context.current['tenant_id'],
context.current['subnets'])
def _handle_network_service_policy(self, context):
network_service_policy_id = context.current.get(
"network_service_policy_id")
if not network_service_policy_id:
return
nsp = context._plugin.get_network_service_policy(
context._plugin_context, network_service_policy_id)
if not nsp.get("network_service_params"):
return
# TODO(Magesh):Handle concurrency issues
free_ip = self._get_last_free_ip(context._plugin_context,
context.current['subnets'])
if not free_ip:
LOG.error(_("Reserving IP Addresses failed for Network Service "
"Policy. No more IP Addresses on subnet"))
return
# TODO(Magesh):Fetch subnet from PTG to which NSP is attached
self._remove_ip_from_allocation_pool(context,
context.current['subnets'][0],
free_ip)
self._set_policy_ipaddress_mapping(context._plugin_context.session,
network_service_policy_id,
context.current['id'],
free_ip)
def _get_service_policy_ipaddress(self, context, policy_target_group):
ipaddress = self._get_ptg_policy_ipaddress_mapping(
context._plugin_context.session, policy_target_group)
return ipaddress
def _cleanup_network_service_policy(self, context, subnets, ptg_id,
ipaddress=None):
if not ipaddress:
ipaddress = self._get_ptg_policy_ipaddress_mapping(
context._plugin_context.session, ptg_id)
if ipaddress and subnets:
# TODO(rkukura): Loop on subnets?
self._restore_ip_to_allocation_pool(
context, subnets[0], ipaddress.ipaddress)
self._delete_policy_ipaddress_mapping(
context._plugin_context.session, ptg_id)
@log.log
def update_policy_target_group_precommit(self, context):
# REVISIT(rkukura): We could potentially allow updates to
# l2_policy_id when no policy targets exist. This would
# involve removing each old subnet from the l3_policy's
# router, deleting each old subnet, creating a new subnet on
# the new l2_policy's network, and adding that subnet to the
# l3_policy's router in postcommit. Its also possible that new
# subnet[s] would be provided explicitly as part of the
# update.
old_l2p = context.original['l2_policy_id']
new_l2p = context.current['l2_policy_id']
if old_l2p and old_l2p != new_l2p:
raise exc.L2PolicyUpdateOfPolicyTargetGroupNotSupported()
if set(context.original['subnets']) - set(context.current['subnets']):
raise exc.PolicyTargetGroupSubnetRemovalNotSupported()
new_subnets = list(set(context.current['subnets']) -
set(context.original['subnets']))
self._validate_ptg_subnets(context, new_subnets)
self._reject_cross_tenant_ptg_l2p(context)
self._validate_ptg_subnets(context, context.current['subnets'])
#Update service chain instance when any ruleset is changed
orig_provided_policy_rule_sets = context.original[
'provided_policy_rule_sets']
curr_provided_policy_rule_sets = context.current[
'provided_policy_rule_sets']
orig_consumed_policy_rule_sets = context.original[
'consumed_policy_rule_sets']
curr_consumed_policy_rule_sets = context.current[
'consumed_policy_rule_sets']
if (set(orig_provided_policy_rule_sets) !=
set(curr_provided_policy_rule_sets)
or set(orig_consumed_policy_rule_sets) !=
set(curr_consumed_policy_rule_sets)):
provider_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
context.current['id'],
None)
consumer_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
None,
context.current['id'])
context.ptg_chain_map = (provider_ptg_chain_map +
consumer_ptg_chain_map)
@log.log
def update_policy_target_group_postcommit(self, context):
# Three conditions where SG association needs to be changed
# (a) list of policy_targets change
# (b) provided_policy_rule_sets change
# (c) consumed_policy_rule_sets change
ptg_id = context.current['id']
new_policy_targets = list(
set(context.current['policy_targets']) - set(
context.original['policy_targets']))
if new_policy_targets:
self._update_sgs_on_pt_with_ptg(context, ptg_id,
new_policy_targets, "ASSOCIATE")
removed_policy_targets = list(
set(context.original['policy_targets']) - set(
context.current['policy_targets']))
if removed_policy_targets:
self._update_sgs_on_pt_with_ptg(context, ptg_id,
new_policy_targets, "DISASSOCIATE")
# generate a list of policy_rule_sets (SGs) to update on the PTG
orig_provided_policy_rule_sets = context.original[
'provided_policy_rule_sets']
curr_provided_policy_rule_sets = context.current[
'provided_policy_rule_sets']
new_provided_policy_rule_sets = list(
set(curr_provided_policy_rule_sets) - set(
orig_provided_policy_rule_sets))
orig_consumed_policy_rule_sets = context.original[
'consumed_policy_rule_sets']
curr_consumed_policy_rule_sets = context.current[
'consumed_policy_rule_sets']
new_consumed_policy_rule_sets = list(
set(curr_consumed_policy_rule_sets) - set(
orig_consumed_policy_rule_sets))
old_nsp = context.original.get("network_service_policy_id")
new_nsp = context.current.get("network_service_policy_id")
if old_nsp != new_nsp:
if old_nsp:
self._cleanup_network_service_policy(
context,
context.current['subnets'],
context.current['id'])
if new_nsp:
self._handle_network_service_policy(context)
# Delete old servicechain instance and create new one in case of update
if (set(orig_provided_policy_rule_sets) !=
set(curr_provided_policy_rule_sets)
or set(orig_consumed_policy_rule_sets) !=
set(curr_consumed_policy_rule_sets)):
self._cleanup_redirect_action(context)
if (curr_consumed_policy_rule_sets or
curr_provided_policy_rule_sets):
policy_rule_sets = (curr_consumed_policy_rule_sets +
curr_provided_policy_rule_sets)
self._handle_redirect_action(context, policy_rule_sets)
# if PTG associated policy_rule_sets are updated, we need to update
# the policy rules, then assoicate SGs to ports
if new_provided_policy_rule_sets or new_consumed_policy_rule_sets:
subnets = context.current['subnets']
self._set_sg_rules_for_subnets(context, subnets,
new_provided_policy_rule_sets,
new_consumed_policy_rule_sets)
self._update_sgs_on_ptg(context, ptg_id,
new_provided_policy_rule_sets,
new_consumed_policy_rule_sets, "ASSOCIATE")
# generate the list of contracts (SGs) to remove from current ports
removed_provided_prs = list(set(orig_provided_policy_rule_sets) -
set(curr_provided_policy_rule_sets))
removed_consumed_prs = list(set(orig_consumed_policy_rule_sets) -
set(curr_consumed_policy_rule_sets))
if removed_provided_prs or removed_consumed_prs:
self._update_sgs_on_ptg(context, ptg_id,
removed_provided_prs,
removed_consumed_prs, "DISASSOCIATE")
subnets = context.original['subnets']
self._unset_sg_rules_for_subnets(
context, subnets, removed_provided_prs, removed_consumed_prs)
# Deal with new added subnets for default SG
# Subnet removal not possible for now
new_subnets = list(set(context.current['subnets']) -
set(context.original['subnets']))
self._update_default_security_group(
context._plugin_context, context.current['id'],
context.current['tenant_id'], subnets=new_subnets)
@log.log
def delete_policy_target_group_precommit(self, context):
context.nsp_cleanup_ipaddress = self._get_ptg_policy_ipaddress_mapping(
context._plugin_context.session, context.current['id'])
provider_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
context.current['id'],
None)
consumer_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
None,
context.current['id'],)
context.ptg_chain_map = provider_ptg_chain_map + consumer_ptg_chain_map
@log.log
def delete_policy_target_group_postcommit(self, context):
self._cleanup_network_service_policy(context,
context.current['subnets'],
context.current['id'],
context.nsp_cleanup_ipaddress)
self._cleanup_redirect_action(context)
# Cleanup SGs
self._unset_sg_rules_for_subnets(
context, context.current['subnets'],
context.current['provided_policy_rule_sets'],
context.current['consumed_policy_rule_sets'])
l2p_id = context.current['l2_policy_id']
router_id = self._get_routerid_for_l2policy(context, l2p_id)
for subnet_id in context.current['subnets']:
self._cleanup_subnet(context._plugin_context, subnet_id, router_id)
self._delete_default_security_group(
context._plugin_context, context.current['id'],
context.current['tenant_id'])
@log.log
def create_l2_policy_precommit(self, context):
self._reject_cross_tenant_l2p_l3p(context)
self._reject_non_shared_net_on_shared_l2p(context)
self._reject_invalid_network_access(context)
@log.log
def create_l2_policy_postcommit(self, context):
if not context.current['network_id']:
self._use_implicit_network(context)
@log.log
def update_l2_policy_precommit(self, context):
if (context.current['l3_policy_id'] !=
context.original['l3_policy_id']):
raise exc.L3PolicyUpdateOfL2PolicyNotSupported()
self._reject_cross_tenant_l2p_l3p(context)
self._reject_non_shared_net_on_shared_l2p(context)
@log.log
def update_l2_policy_postcommit(self, context):
pass
@log.log
def delete_l2_policy_precommit(self, context):
pass
@log.log
def delete_l2_policy_postcommit(self, context):
network_id = context.current['network_id']
self._cleanup_network(context._plugin_context, network_id)
@log.log
def create_l3_policy_precommit(self, context):
curr = context.current
if len(curr['routers']) > 1:
raise exc.L3PolicyMultipleRoutersNotSupported()
# Validate non overlapping IPs in the same tenant
l3ps = context._plugin.get_l3_policies(
context._plugin_context, {'tenant_id': [curr['tenant_id']]})
subnets = [x['ip_pool'] for x in l3ps if x['id'] != curr['id']]
current_set = netaddr.IPSet(subnets)
if netaddr.IPSet([curr['ip_pool']]) & current_set:
raise exc.OverlappingIPPoolsInSameTenantNotAllowed(
ip_pool=curr['ip_pool'], overlapping_pools=subnets)
# In Neutron, one external gateway per router is allowed. Therefore
# we have to limit the number of ES per L3P to 1
if len(context.current['external_segments']) > 1:
raise exc.MultipleESPerL3PolicyNotSupported()
self._reject_invalid_router_access(context)
@log.log
def create_l3_policy_postcommit(self, context):
if not context.current['routers']:
self._use_implicit_router(context)
l3p = context.current
if l3p['external_segments']:
self._plug_router_to_external_segment(
context, l3p['external_segments'])
self._set_l3p_routes(context)
self._process_new_l3p_ip_pool(context, context.current['ip_pool'])
@log.log
def update_l3_policy_precommit(self, context):
if context.current['routers'] != context.original['routers']:
raise exc.L3PolicyRoutersUpdateNotSupported()
if len(context.current['external_segments']) > 1:
raise exc.MultipleESPerL3PolicyNotSupported()
# Currently there is no support for router update in l3p update.
# Added this check just in case it is supported in future.
self._reject_invalid_router_access(context)
@log.log
def update_l3_policy_postcommit(self, context):
new, old = context.current, context.original
if new['external_segments'] != old['external_segments']:
added = (set(new['external_segments'].keys()) -
set(old['external_segments'].keys()))
removed = (set(old['external_segments'].keys()) -
set(new['external_segments'].keys()))
if context.current['routers']:
if removed:
self._unplug_router_from_external_segment(
context, dict((x, old['external_segments'][x])
for x in removed))
if added:
self._plug_router_to_external_segment(
context, dict((x, new['external_segments'][x])
for x in added))
self._set_l3p_routes(context)
@log.log
def delete_l3_policy_precommit(self, context):
pass
@log.log
def delete_l3_policy_postcommit(self, context):
for router_id in context.current['routers']:
self._cleanup_router(context._plugin_context, router_id)
self._process_remove_l3p_ip_pool(context, context.current['ip_pool'])
@log.log
def create_policy_classifier_precommit(self, context):
pass
@log.log
def create_policy_classifier_postcommit(self, context):
pass
@log.log
def update_policy_classifier_precommit(self, context):
pass
@log.log
def update_policy_classifier_postcommit(self, context):
policy_rules = (context._plugin.get_policy_classifier(
context._plugin_context,
context.current['id'])['policy_rules'])
policy_rules = context._plugin.get_policy_rules(
context._plugin_context,
filters={'id': policy_rules})
policy_rulesets_to_update = []
for policy_rule in policy_rules:
pr_id = policy_rule['id']
pr_sets = context._plugin._get_policy_rule_policy_rule_sets(
context._plugin_context, pr_id)
policy_rulesets_to_update.extend(pr_sets)
self._update_policy_rule_sg_rules(context, pr_sets,
policy_rule, context.original, context.current)
self._handle_redirect_action(context, policy_rulesets_to_update)
@log.log
def delete_policy_classifier_precommit(self, context):
pass
@log.log
def delete_policy_classifier_postcommit(self, context):
pass
@log.log
def create_policy_action_precommit(self, context):
spec_id = context.current['action_value']
if spec_id:
specs = self._servicechain_plugin.get_servicechain_specs(
context._plugin_context, filters={'id': [spec_id]})
for spec in specs:
if not spec.get('shared', False):
self._reject_shared(context.current, 'policy_action')
@log.log
def create_policy_action_postcommit(self, context):
pass
@log.log
def update_policy_action_precommit(self, context):
pass
@log.log
def update_policy_action_postcommit(self, context):
# TODO(ivar): Should affect related SGs
self._handle_redirect_spec_id_update(context)
@log.log
def delete_policy_action_precommit(self, context):
pass
@log.log
def delete_policy_action_postcommit(self, context):
pass
@log.log
def create_policy_rule_precommit(self, context):
self._reject_multiple_redirects_in_rule(context)
@log.log
def create_policy_rule_postcommit(self, context):
pass
@log.log
def update_policy_rule_precommit(self, context):
self._reject_multiple_redirects_in_rule(context)
@log.log
def update_policy_rule_postcommit(self, context):
old_classifier_id = context.original['policy_classifier_id']
new_classifier_id = context.current['policy_classifier_id']
old_action_set = set(context.current['policy_actions'])
new_action_set = set(context.original['policy_actions'])
if (old_classifier_id != new_classifier_id or
old_action_set != new_action_set):
policy_rule_sets = (
context._plugin._get_policy_rule_policy_rule_sets(
context._plugin_context, context.current['id']))
for prs in context._plugin.get_policy_rule_sets(
context._plugin_context, filters={'id': policy_rule_sets}):
self._remove_policy_rule_set_rules(context, prs,
[context.original])
self._apply_policy_rule_set_rules(context, prs,
[context.current])
self._handle_redirect_action(context, policy_rule_sets)
@log.log
def delete_policy_rule_precommit(self, context):
# REVISIT(ivar): This will be removed once navigability issue is
# solved (bug/1384397)
context._rmd_policy_rule_sets_temp = (
context._plugin._get_policy_rule_policy_rule_sets(
context._plugin_context, context.current['id']))
@log.log
def delete_policy_rule_postcommit(self, context):
for prs in context._plugin.get_policy_rule_sets(
context._plugin_context,
filters={'id': context.current['policy_rule_sets']}):
self._remove_policy_rule_set_rules(context, prs, [context.current])
@log.log
def create_policy_rule_set_precommit(self, context):
self._reject_shared(context.current, 'policy_rule_set')
self._reject_multiple_redirects_in_prs(context)
@log.log
def create_policy_rule_set_postcommit(self, context):
# creating SGs
policy_rule_set_id = context.current['id']
consumed_sg = self._create_policy_rule_set_sg(context, 'consumed')
provided_sg = self._create_policy_rule_set_sg(context, 'provided')
consumed_sg_id = consumed_sg['id']
provided_sg_id = provided_sg['id']
self._set_policy_rule_set_sg_mapping(
context._plugin_context.session, policy_rule_set_id,
consumed_sg_id, provided_sg_id)
rules = context._plugin.get_policy_rules(
context._plugin_context,
{'id': context.current['policy_rules']})
self._apply_policy_rule_set_rules(context, context.current, rules)
if context.current['child_policy_rule_sets']:
self._recompute_policy_rule_sets(
context, context.current['child_policy_rule_sets'])
self._handle_redirect_action(
context, context.current['child_policy_rule_sets'])
@log.log
def update_policy_rule_set_precommit(self, context):
self._reject_shared(context.current, 'policy_rule_set')
self._reject_multiple_redirects_in_prs(context)
@log.log
def update_policy_rule_set_postcommit(self, context):
# Update policy_rule_set rules
old_rules = set(context.original['policy_rules'])
new_rules = set(context.current['policy_rules'])
to_add = context._plugin.get_policy_rules(
context._plugin_context, {'id': new_rules - old_rules})
to_remove = context._plugin.get_policy_rules(
context._plugin_context, {'id': old_rules - new_rules})
self._remove_policy_rule_set_rules(context, context.current, to_remove)
self._apply_policy_rule_set_rules(context, context.current, to_add)
# Update children contraint
to_recompute = (set(context.original['child_policy_rule_sets']) ^
set(context.current['child_policy_rule_sets']))
self._recompute_policy_rule_sets(context, to_recompute)
if to_add or to_remove:
to_recompute = (set(context.original['child_policy_rule_sets']) &
set(context.current['child_policy_rule_sets']))
self._recompute_policy_rule_sets(context, to_recompute)
# Handle any Redirects from the current Policy Rule Set
self._handle_redirect_action(context, [context.current['id']])
# Handle Update/Delete of Redirects for any child Rule Sets
if (set(context.original['child_policy_rule_sets']) !=
set(context.current['child_policy_rule_sets'])):
if context.original['child_policy_rule_sets']:
self._handle_redirect_action(
context, context.original['child_policy_rule_sets'])
if context.current['child_policy_rule_sets']:
self._handle_redirect_action(
context, context.current['child_policy_rule_sets'])
@log.log
def delete_policy_rule_set_precommit(self, context):
mapping = self._get_policy_rule_set_sg_mapping(
context._plugin_context.session, context.current['id'])
context._rmd_sg_list_temp = [mapping['provided_sg_id'],
mapping['consumed_sg_id']]
@log.log
def delete_policy_rule_set_postcommit(self, context):
# Disassociate SGs
sg_list = context._rmd_sg_list_temp
ptg_mapping = [context.current['providing_policy_target_groups'],
context.current['consuming_policy_target_groups']]
for ptgs in ptg_mapping:
for ptg in ptgs:
policy_target_list = ptg['policy_targets']
for pt_id in policy_target_list:
self._disassoc_sgs_from_pt(context, pt_id, sg_list)
# Delete SGs
for sg in sg_list:
self._delete_sg(context._plugin_context, sg)
if context.current['child_policy_rule_sets']:
self._handle_redirect_action(
context, context.current['child_policy_rule_sets'])
@log.log
def create_network_service_policy_precommit(self, context):
self._validate_nsp_parameters(context)
def create_external_segment_precommit(self, context):
if context.current['subnet_id']:
subnet = self._core_plugin.get_subnet(context._plugin_context,
context.current['subnet_id'])
network = self._core_plugin.get_network(context._plugin_context,
subnet['network_id'])
if not network['router:external']:
raise exc.InvalidSubnetForES(sub_id=subnet['id'],
net_id=network['id'])
db_es = context._plugin._get_external_segment(
context._plugin_context, context.current['id'])
db_es.cidr = subnet['cidr']
db_es.ip_version = subnet['ip_version']
context.current['cidr'] = db_es.cidr
context.current['ip_version'] = db_es.ip_version
else:
raise exc.ImplicitSubnetNotSupported()
def create_external_segment_postcommit(self, context):
pass
def update_external_segment_precommit(self, context):
invalid = ['port_address_translation']
for attr in invalid:
if context.current[attr] != context.original[attr]:
raise exc.InvalidAttributeUpdateForES(attribute=attr)
def update_external_segment_postcommit(self, context):
# REVISIT(ivar): concurrency issues
if (context.current['external_routes'] !=
context.original['external_routes']):
# Update SG rules for each EP
# Get all the EP using this ES
ep_ids = context._plugin._get_external_segment_external_policies(
context._plugin_context, context.current['id'])
# Process their routes
old_cidrs = [x['destination']
for x in context.original['external_routes']]
old_cidrs = self._process_external_cidrs(context, old_cidrs)
new_cidrs = [x['destination']
for x in context.current['external_routes']]
new_cidrs = self._process_external_cidrs(context, new_cidrs)
# Recompute PRS rules
self._recompute_external_policy_rules(context, ep_ids,
new_cidrs, old_cidrs)
old_routes = set((x['destination'], x['nexthop'])
for x in context.original['external_routes'])
new_routes = set((x['destination'], x['nexthop'])
for x in context.current['external_routes'])
# Set the correct list of routes for each L3P
self._recompute_l3_policy_routes(context, new_routes, old_routes)
def delete_external_segment_precommit(self, context):
pass
def delete_external_segment_postcommit(self, context):
pass
def create_external_policy_precommit(self, context):
self._reject_shared(context.current, 'external_policy')
# REVISIT(ivar): For security reasons, only one ES allowed per EP.
# see bug #1398156
if len(context.current['external_segments']) > 1:
raise exc.MultipleESPerEPNotSupported()
# REVISIT(ivar): bug #1398156 only one EP is allowed per tenant
ep_number = context._plugin.get_external_policies_count(
context._plugin_context,
filters={'tenant_id': [context.current['tenant_id']]})
if ep_number > 1:
raise exc.OnlyOneEPPerTenantAllowed()
def create_external_policy_postcommit(self, context):
# Only *North to South* rules are actually effective.
# The rules will be calculated as the symmetric difference between
# the union of all the Tenant's L3P supernets and the union of all the
# ES routes.
# REVISIT(ivar): Remove when ES update is supported for EP
if not context.current['external_segments']:
raise exc.ESIdRequiredWhenCreatingEP()
ep = context.current
if ep['external_segments']:
if (ep['provided_policy_rule_sets'] or
ep['consumed_policy_rule_sets']):
# Get the full processed list of external CIDRs
cidr_list = self._get_processed_ep_cidr_list(context, ep)
# set the rules on the proper SGs
self._set_sg_rules_for_cidrs(
context, cidr_list, ep['provided_policy_rule_sets'],
ep['consumed_policy_rule_sets'])
if ep['consumed_policy_rule_sets']:
self._handle_redirect_action(context,
ep['consumed_policy_rule_sets'])
def update_external_policy_precommit(self, context):
if context.original['external_segments']:
if (set(context.current['external_segments']) !=
set(context.original['external_segments'])):
raise exc.ESUpdateNotSupportedForEP()
provider_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
context.current['id'],
None)
consumer_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
None,
context.current['id'],)
context.ptg_chain_map = provider_ptg_chain_map + consumer_ptg_chain_map
def update_external_policy_postcommit(self, context):
# REVISIT(ivar): Concurrency issue, the cidr_list could be different
# in the time from adding new PRS to removing old ones. The consequence
# is that the rules added/removed could be completely wrong.
prov_cons = {'provided_policy_rule_sets': [],
'consumed_policy_rule_sets': []}
cidr_list = None
# Removed PRS
for attr in prov_cons:
orig_policy_rule_sets = context.original[attr]
curr_policy_rule_sets = context.current[attr]
prov_cons[attr] = list(set(orig_policy_rule_sets) -
set(curr_policy_rule_sets))
if any(prov_cons.values()):
cidr_list = self._get_processed_ep_cidr_list(
context, context.current)
self._unset_sg_rules_for_cidrs(
context, cidr_list, prov_cons['provided_policy_rule_sets'],
prov_cons['consumed_policy_rule_sets'])
if prov_cons['consumed_policy_rule_sets']:
self._cleanup_redirect_action(context)
# Added PRS
for attr in prov_cons:
orig_policy_rule_sets = context.original[attr]
curr_policy_rule_sets = context.current[attr]
prov_cons[attr] = list(set(curr_policy_rule_sets) -
set(orig_policy_rule_sets))
if any(prov_cons.values()):
cidr_list = cidr_list or self._get_processed_ep_cidr_list(
context, context.current)
self._set_sg_rules_for_cidrs(
context, cidr_list, prov_cons['provided_policy_rule_sets'],
prov_cons['consumed_policy_rule_sets'])
if prov_cons['consumed_policy_rule_sets']:
self._handle_redirect_action(
context, prov_cons['consumed_policy_rule_sets'])
def delete_external_policy_precommit(self, context):
provider_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
context.current['id'],
None)
consumer_ptg_chain_map = self._get_ptg_servicechain_mapping(
context._plugin_context.session,
None,
context.current['id'],)
context.ptg_chain_map = provider_ptg_chain_map + consumer_ptg_chain_map
def delete_external_policy_postcommit(self, context):
if (context.current['provided_policy_rule_sets'] or
context.current['consumed_policy_rule_sets']):
# REVISIT(ivar): concurrency issue, ES may not exist anymore
cidr_list = self._get_processed_ep_cidr_list(
context, context.current)
self._unset_sg_rules_for_cidrs(
context, cidr_list,
context.current['provided_policy_rule_sets'],
context.current['consumed_policy_rule_sets'])
self._cleanup_redirect_action(context)
def create_nat_pool_precommit(self, context):
# No FIP supported right now
# REVISIT(ivar): ignore or reject?
pass