/
l7policy.py
342 lines (290 loc) · 14.9 KB
/
l7policy.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
# Copyright 2016 Blue Box, an IBM Company
#
# 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.
from octavia_lib.api.drivers import data_models as driver_dm
from octavia_lib.common import constants as lib_consts
from oslo_config import cfg
from oslo_db import exception as odb_exceptions
from oslo_log import log as logging
from oslo_utils import excutils
from pecan import expose as pecan_expose
from pecan import request as pecan_request
from wsme import types as wtypes
from wsmeext import pecan as wsme_pecan
from octavia.api.drivers import driver_factory
from octavia.api.drivers import utils as driver_utils
from octavia.api.v2.controllers import base
from octavia.api.v2.controllers import l7rule
from octavia.api.v2.types import l7policy as l7policy_types
from octavia.common import constants
from octavia.common import data_models
from octavia.common import exceptions
from octavia.common import validate
from octavia.db import prepare as db_prepare
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class L7PolicyController(base.BaseController):
RBAC_TYPE = constants.RBAC_L7POLICY
def __init__(self):
super().__init__()
@wsme_pecan.wsexpose(l7policy_types.L7PolicyRootResponse, wtypes.text,
[wtypes.text], ignore_extra_args=True)
def get(self, id, fields=None):
"""Gets a single l7policy's details."""
context = pecan_request.context.get('octavia_context')
with context.session.begin():
db_l7policy = self._get_db_l7policy(context.session, id,
show_deleted=False)
self._auth_validate_action(context, db_l7policy.project_id,
constants.RBAC_GET_ONE)
result = self._convert_db_to_type(
db_l7policy, l7policy_types.L7PolicyResponse)
if fields is not None:
result = self._filter_fields([result], fields)[0]
return l7policy_types.L7PolicyRootResponse(l7policy=result)
@wsme_pecan.wsexpose(l7policy_types.L7PoliciesRootResponse, wtypes.text,
[wtypes.text], ignore_extra_args=True)
def get_all(self, project_id=None, fields=None):
"""Lists all l7policies of a listener."""
pcontext = pecan_request.context
context = pcontext.get('octavia_context')
query_filter = self._auth_get_all(context, project_id)
with context.session.begin():
db_l7policies, links = self.repositories.l7policy.get_all_API_list(
context.session, show_deleted=False,
pagination_helper=pcontext.get(constants.PAGINATION_HELPER),
**query_filter)
result = self._convert_db_to_type(
db_l7policies, [l7policy_types.L7PolicyResponse])
if fields is not None:
result = self._filter_fields(result, fields)
return l7policy_types.L7PoliciesRootResponse(
l7policies=result, l7policies_links=links)
def _test_lb_and_listener_statuses(self, session, lb_id, listener_ids):
"""Verify load balancer is in a mutable state."""
if not self.repositories.test_and_set_lb_and_listeners_prov_status(
session, lb_id,
constants.PENDING_UPDATE, constants.PENDING_UPDATE,
listener_ids=listener_ids):
LOG.info("L7Policy cannot be created or modified because the "
"Load Balancer is in an immutable state")
raise exceptions.ImmutableObject(resource='Load Balancer',
id=lb_id)
def _validate_create_l7policy(self, lock_session, l7policy_dict):
try:
# Set the default HTTP redirect code here so it's explicit
if ((l7policy_dict.get('redirect_url') or
l7policy_dict.get('redirect_prefix')) and
not l7policy_dict.get('redirect_http_code')):
l7policy_dict['redirect_http_code'] = 302
return self.repositories.l7policy.create(lock_session,
**l7policy_dict)
except odb_exceptions.DBDuplicateEntry as e:
raise exceptions.IDAlreadyExists() from e
except odb_exceptions.DBReferenceError as e:
raise exceptions.InvalidOption(value=l7policy_dict.get(e.key),
option=e.key) from e
except odb_exceptions.DBError as e:
raise exceptions.APIException() from e
@wsme_pecan.wsexpose(l7policy_types.L7PolicyRootResponse,
body=l7policy_types.L7PolicyRootPOST, status_code=201)
def post(self, l7policy_):
"""Creates a l7policy on a listener."""
l7policy = l7policy_.l7policy
context = pecan_request.context.get('octavia_context')
# Verify the parent listener exists
listener_id = l7policy.listener_id
with context.session.begin():
listener = self._get_db_listener(
context.session, listener_id)
load_balancer_id = listener.load_balancer_id
l7policy.project_id, provider = self._get_lb_project_id_provider(
context.session, load_balancer_id)
self._auth_validate_action(context, l7policy.project_id,
constants.RBAC_POST)
# PROMETHEUS listeners cannot have l7policies attached
if listener.protocol == lib_consts.PROTOCOL_PROMETHEUS:
raise exceptions.ListenerNoChildren(
protocol=lib_consts.PROTOCOL_PROMETHEUS)
# Make sure any pool specified by redirect_pool_id exists
if l7policy.redirect_pool_id:
with context.session.begin():
db_pool = self._get_db_pool(
context.session, l7policy.redirect_pool_id)
self._validate_protocol(listener.protocol, db_pool.protocol)
# Load the driver early as it also provides validation
driver = driver_factory.get_driver(provider)
lock_session = context.session
lock_session.begin()
try:
if self.repositories.check_quota_met(
lock_session,
data_models.L7Policy,
l7policy.project_id):
raise exceptions.QuotaException(
resource=data_models.L7Policy._name())
l7policy_dict = db_prepare.create_l7policy(
l7policy.to_dict(render_unsets=True),
load_balancer_id, listener_id)
self._test_lb_and_listener_statuses(
lock_session, lb_id=load_balancer_id,
listener_ids=[listener_id])
db_l7policy = self._validate_create_l7policy(
lock_session, l7policy_dict)
# Prepare the data for the driver data model
provider_l7policy = (
driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))
# Dispatch to the driver
LOG.info("Sending create L7 Policy %s to provider %s",
db_l7policy.id, driver.name)
driver_utils.call_provider(
driver.name, driver.l7policy_create, provider_l7policy)
lock_session.commit()
except Exception:
with excutils.save_and_reraise_exception():
lock_session.rollback()
with context.session.begin():
db_l7policy = self._get_db_l7policy(context.session,
db_l7policy.id)
result = self._convert_db_to_type(db_l7policy,
l7policy_types.L7PolicyResponse)
return l7policy_types.L7PolicyRootResponse(l7policy=result)
def _graph_create(self, lock_session, policy_dict):
load_balancer_id = policy_dict.pop('load_balancer_id', None)
listener_id = policy_dict['listener_id']
policy_dict = db_prepare.create_l7policy(
policy_dict, load_balancer_id, listener_id)
rules = policy_dict.pop('l7rules', []) or []
db_policy = self._validate_create_l7policy(lock_session, policy_dict)
new_rules = []
for r in rules:
r['project_id'] = db_policy.project_id
new_rules.append(
l7rule.L7RuleController(db_policy.id)._graph_create(
lock_session, r))
db_policy.l7rules = new_rules
return db_policy
@wsme_pecan.wsexpose(l7policy_types.L7PolicyRootResponse,
wtypes.text, body=l7policy_types.L7PolicyRootPUT,
status_code=200)
def put(self, id, l7policy_):
"""Updates a l7policy."""
l7policy = l7policy_.l7policy
context = pecan_request.context.get('octavia_context')
with context.session.begin():
db_l7policy = self._get_db_l7policy(context.session, id,
show_deleted=False)
load_balancer_id, listener_id = (
self._get_listener_and_loadbalancer_id(db_l7policy))
project_id, provider = self._get_lb_project_id_provider(
context.session, load_balancer_id)
self._auth_validate_action(context, project_id, constants.RBAC_PUT)
l7policy_dict = validate.sanitize_l7policy_api_args(
l7policy.to_dict(render_unsets=False))
# Reset renamed attributes
for attr, val in l7policy_types.L7PolicyPUT._type_to_model_map.items():
if val in l7policy_dict:
l7policy_dict[attr] = l7policy_dict.pop(val)
sanitized_l7policy = l7policy_types.L7PolicyPUT(**l7policy_dict)
with context.session.begin():
listener = self._get_db_listener(
context.session, db_l7policy.listener_id)
# Make sure any specified redirect_pool_id exists
if l7policy_dict.get('redirect_pool_id'):
with context.session.begin():
db_pool = self._get_db_pool(
context.session, l7policy_dict['redirect_pool_id'])
self._validate_protocol(listener.protocol, db_pool.protocol)
# Load the driver early as it also provides validation
driver = driver_factory.get_driver(provider)
with context.session.begin():
lock_session = context.session
self._test_lb_and_listener_statuses(lock_session,
lb_id=load_balancer_id,
listener_ids=[listener_id])
# Prepare the data for the driver data model
l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
l7policy_dict['id'] = id
provider_l7policy_dict = (
driver_utils.l7policy_dict_to_provider_dict(l7policy_dict))
# Also prepare the baseline object data
old_provider_l7policy = (
driver_utils.db_l7policy_to_provider_l7policy(db_l7policy))
# Dispatch to the driver
LOG.info("Sending update L7 Policy %s to provider %s",
id, driver.name)
driver_utils.call_provider(
driver.name, driver.l7policy_update,
old_provider_l7policy,
driver_dm.L7Policy.from_dict(provider_l7policy_dict))
# Update the database to reflect what the driver just accepted
sanitized_l7policy.provisioning_status = constants.PENDING_UPDATE
db_l7policy_dict = sanitized_l7policy.to_dict(render_unsets=False)
self.repositories.l7policy.update(lock_session, id,
**db_l7policy_dict)
# Force SQL alchemy to query the DB, otherwise we get inconsistent
# results
context.session.expire_all()
with context.session.begin():
db_l7policy = self._get_db_l7policy(context.session, id)
result = self._convert_db_to_type(db_l7policy,
l7policy_types.L7PolicyResponse)
return l7policy_types.L7PolicyRootResponse(l7policy=result)
@wsme_pecan.wsexpose(None, wtypes.text, status_code=204)
def delete(self, id):
"""Deletes a l7policy."""
context = pecan_request.context.get('octavia_context')
with context.session.begin():
db_l7policy = self._get_db_l7policy(context.session, id,
show_deleted=False)
load_balancer_id, listener_id = (
self._get_listener_and_loadbalancer_id(db_l7policy))
project_id, provider = self._get_lb_project_id_provider(
context.session, load_balancer_id)
self._auth_validate_action(context, project_id, constants.RBAC_DELETE)
if db_l7policy.provisioning_status == constants.DELETED:
return
# Load the driver early as it also provides validation
driver = driver_factory.get_driver(provider)
with context.session.begin():
self._test_lb_and_listener_statuses(context.session,
lb_id=load_balancer_id,
listener_ids=[listener_id])
self.repositories.l7policy.update(
context.session, db_l7policy.id,
provisioning_status=constants.PENDING_DELETE)
LOG.info("Sending delete L7 Policy %s to provider %s",
id, driver.name)
provider_l7policy = driver_utils.db_l7policy_to_provider_l7policy(
db_l7policy)
driver_utils.call_provider(driver.name, driver.l7policy_delete,
provider_l7policy)
@pecan_expose()
def _lookup(self, l7policy_id, *remainder):
"""Overridden pecan _lookup method for custom routing.
Verifies that the l7policy passed in the url exists, and if so decides
which controller, if any, should control be passed.
"""
context = pecan_request.context.get('octavia_context')
if l7policy_id and remainder and remainder[0] == 'rules':
remainder = remainder[1:]
with context.session.begin():
db_l7policy = self.repositories.l7policy.get(
context.session, id=l7policy_id)
if not db_l7policy:
LOG.info("L7Policy %s not found.", l7policy_id)
raise exceptions.NotFound(
resource='L7Policy', id=l7policy_id)
return l7rule.L7RuleController(
l7policy_id=db_l7policy.id), remainder
return None