| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
import functools |
| 17 |
import re |
| 18 |
import urllib |
| 19 |
import requests |
| 20 |
import six |
| 21 |
import urllib3 |
| 22 |
import time |
| 23 |
from requests import exceptions as req_exc |
| 24 |
|
| 25 |
try: |
| 26 |
import urlparse |
| 27 |
except ImportError: |
| 28 |
import urllib.parse as urlparse |
| 29 |
|
| 30 |
try: |
| 31 |
from oslo_log import log as logging |
| 32 |
except ImportError: |
| 33 |
import logging |
| 34 |
|
| 35 |
try: |
| 36 |
from oslo_serialization import jsonutils |
| 37 |
except ImportError: |
| 38 |
import json as jsonutils |
| 39 |
|
| 40 |
from infoblox_client import exceptions as ib_ex |
| 41 |
from infoblox_client import utils |
| 42 |
|
| 43 |
LOG = logging.getLogger(__name__) |
| 44 |
CLOUD_WAPI_MAJOR_VERSION = 2 |
| 45 |
|
| 46 |
|
| 47 |
def reraise_neutron_exception(func): |
| 48 |
"""This decorator catches third-party exceptions and replaces them with |
| 49 |
Infoblox exceptions""" |
| 50 |
|
| 51 |
@functools.wraps(func) |
| 52 |
def callee(*args, **kwargs): |
| 53 |
"""Catches third-party exceptions and raises Infoblox exceptions""" |
| 54 |
try: |
| 55 |
return func(*args, **kwargs) |
| 56 |
except req_exc.Timeout as e: |
| 57 |
raise ib_ex.InfobloxTimeoutError(e, reason=e) |
| 58 |
except req_exc.RequestException as e: |
| 59 |
raise ib_ex.InfobloxConnectionError(reason=e) |
| 60 |
|
| 61 |
return callee |
| 62 |
|
| 63 |
|
| 64 |
def retry_on_expired_cookie(func): |
| 65 |
""" |
| 66 |
Decorator to handle expired cookies by re-authenticating |
| 67 |
and retrying the request. |
| 68 |
""" |
| 69 |
@functools.wraps(func) |
| 70 |
def wrapper(self, *args, **kwargs): |
| 71 |
""" |
| 72 |
Wrapper function to handle expired cookies by re-authenticating |
| 73 |
and retrying the request. |
| 74 |
""" |
| 75 |
try: |
| 76 |
return func(self, *args, **kwargs) |
| 77 |
except (req_exc.HTTPError, ib_ex.InfobloxBadWAPICredential, |
| 78 |
ib_ex.InfobloxFileDownloadFailed, |
| 79 |
ib_ex.InfobloxFileUploadFailed) as e: |
| 80 |
if isinstance(e, (req_exc.HTTPError, |
| 81 |
ib_ex.InfobloxBadWAPICredential, |
| 82 |
ib_ex.InfobloxFileDownloadFailed, |
| 83 |
ib_ex.InfobloxFileUploadFailed)): |
| 84 |
LOG.warning("Bad WAPI credentials or Cookie timeout.\ |
| 85 |
Re-authenticating and retrying the request.") |
| 86 |
else: |
| 87 |
raise |
| 88 |
|
| 89 |
LOG.warning("Clearing cookies and re-authenticating.") |
| 90 |
self.session.cookies.clear() |
| 91 |
if hasattr(self, 'username') and hasattr(self, 'password'): |
| 92 |
LOG.warning("Re-authenticating with username and password.") |
| 93 |
self.session.auth = (self.username, self.password) |
| 94 |
elif hasattr(self, 'cert') and hasattr(self, 'key'): |
| 95 |
LOG.warning("Re-authenticating with client certificate.") |
| 96 |
self.session.cert = (self.cert, self.key) |
| 97 |
else: |
| 98 |
LOG.warning("No valid credentials found to re-authenticate.") |
| 99 |
raise ib_ex.InfobloxConfigException( |
| 100 |
msg="No valid credentials found to re-authenticate.") |
| 101 |
return func(self, *args, **kwargs) |
| 102 |
return wrapper |
| 103 |
|
| 104 |
|
| 105 |
class Connector(object): |
| 106 |
"""Connector stands for interacting with Infoblox NIOS |
| 107 |
|
| 108 |
Defines methods for getting, creating, updating and |
| 109 |
removing objects from an Infoblox server instance. |
| 110 |
""" |
| 111 |
|
| 112 |
DEFAULT_HEADER = {'Content-type': 'application/json'} |
| 113 |
DEFAULT_OPTIONS = {'ssl_verify': False, |
| 114 |
'silent_ssl_warnings': False, |
| 115 |
'http_request_timeout': 10, |
| 116 |
'http_pool_connections': 10, |
| 117 |
'http_pool_maxsize': 10, |
| 118 |
'max_retries': 3, |
| 119 |
'wapi_version': '2.10', |
| 120 |
'max_results': None, |
| 121 |
'log_api_calls_as_info': False, |
| 122 |
'paging': False} |
| 123 |
|
| 124 |
def __init__(self, options): |
| 125 |
self._parse_options(options) |
| 126 |
self._configure_session() |
| 127 |
|
| 128 |
try: |
| 129 |
self._urlencode = urllib.urlencode |
| 130 |
self._quote = urllib.quote |
| 131 |
self._urljoin = urlparse.urljoin |
| 132 |
except AttributeError: |
| 133 |
self._urlencode = urlparse.urlencode |
| 134 |
self._quote = urlparse.quote |
| 135 |
self._urljoin = urlparse.urljoin |
| 136 |
masked_options = utils.mask_sensitive_data(options) |
| 137 |
LOG.debug( |
| 138 |
"Connector initialized with options: {}".format(masked_options)) |
| 139 |
|
| 140 |
def _parse_options(self, options): |
| 141 |
"""Copy necessary options to self""" |
| 142 |
attributes = ('host', 'wapi_version', 'username', 'password', |
| 143 |
'cert', 'key', 'ssl_verify', 'http_request_timeout', |
| 144 |
'max_retries', 'http_pool_connections', |
| 145 |
'http_pool_maxsize', 'silent_ssl_warnings', |
| 146 |
'log_api_calls_as_info', 'max_results', |
| 147 |
'paging') |
| 148 |
|
| 149 |
creds_basic_auth = ['username', 'password'] |
| 150 |
creds_cert_auth = ['cert', 'key'] |
| 151 |
creds = creds_basic_auth + creds_cert_auth |
| 152 |
|
| 153 |
for attr in attributes: |
| 154 |
if isinstance(options, dict) and \ |
| 155 |
attr in options and \ |
| 156 |
options[attr] is not None: |
| 157 |
setattr(self, attr, options[attr]) |
| 158 |
elif hasattr(options, attr): |
| 159 |
value = getattr(options, attr) |
| 160 |
setattr(self, attr, value) |
| 161 |
elif attr in self.DEFAULT_OPTIONS: |
| 162 |
setattr(self, attr, self.DEFAULT_OPTIONS[attr]) |
| 163 |
elif attr not in creds: |
| 164 |
msg = "WAPI config error. Option %s is not defined" % attr |
| 165 |
LOG.error(msg) |
| 166 |
raise ib_ex.InfobloxConfigException(msg=msg) |
| 167 |
|
| 168 |
def check_creds(credentials): |
| 169 |
for attr in credentials: |
| 170 |
try: |
| 171 |
getattr(self, attr) |
| 172 |
except AttributeError: |
| 173 |
return False |
| 174 |
return True |
| 175 |
|
| 176 |
|
| 177 |
if not check_creds(creds_basic_auth) and \ |
| 178 |
not check_creds(creds_cert_auth): |
| 179 |
msg = "WAPI config error. Option either (username, password) " \ |
| 180 |
"or (cert, key) should be passed" |
| 181 |
LOG.error(msg) |
| 182 |
raise ib_ex.InfobloxConfigException(msg=msg) |
| 183 |
|
| 184 |
self.wapi_url = "https://%s/wapi/v%s/" % (self.host, |
| 185 |
self.wapi_version) |
| 186 |
self.cloud_api_enabled = self.is_cloud_wapi( |
| 187 |
self.wapi_version) |
| 188 |
|
| 189 |
def _configure_session(self): |
| 190 |
LOG.debug("Configuring session") |
| 191 |
self.session = requests.Session() |
| 192 |
adapter = requests.adapters.HTTPAdapter( |
| 193 |
pool_connections=self.http_pool_connections, |
| 194 |
pool_maxsize=self.http_pool_maxsize, |
| 195 |
max_retries=self.max_retries) |
| 196 |
self.session.mount('http://', adapter) |
| 197 |
self.session.mount('https://', adapter) |
| 198 |
if hasattr(self, 'username') and hasattr(self, 'password'): |
| 199 |
LOG.info("Authenticating with username and password.") |
| 200 |
self.session.auth = (self.username, self.password) |
| 201 |
else: |
| 202 |
self.session.cert = (self.cert, self.key) |
| 203 |
LOG.info("Authenticating with client certificate.") |
| 204 |
self.session.verify = utils.try_value_to_bool(self.ssl_verify, |
| 205 |
strict_mode=False) |
| 206 |
LOG.debug("SSL verification is %s", self.session.verify) |
| 207 |
|
| 208 |
if self.silent_ssl_warnings: |
| 209 |
LOG.debug("Silencing SSL warnings") |
| 210 |
urllib3.disable_warnings() |
| 211 |
|
| 212 |
def _construct_url(self, relative_path, query_params=None, |
| 213 |
extattrs=None, force_proxy=False): |
| 214 |
""" |
| 215 |
Construct URL for Infoblox WAPI request |
| 216 |
""" |
| 217 |
LOG.debug("Constructing URL for relative path: %s", relative_path) |
| 218 |
if query_params is None: |
| 219 |
query_params = {} |
| 220 |
if extattrs is None: |
| 221 |
extattrs = {} |
| 222 |
if force_proxy: |
| 223 |
LOG.debug("Forcing proxy search") |
| 224 |
query_params['_proxy_search'] = 'GM' |
| 225 |
|
| 226 |
if not relative_path or relative_path[0] == '/': |
| 227 |
raise ValueError('Path in request must be relative.') |
| 228 |
query = '' |
| 229 |
if query_params or extattrs: |
| 230 |
query = '?' |
| 231 |
|
| 232 |
if extattrs: |
| 233 |
attrs_queries = [] |
| 234 |
for key, value in extattrs.items(): |
| 235 |
param = "*%s" % key |
| 236 |
value = value['value'] |
| 237 |
if isinstance(value, list): |
| 238 |
for item in value: |
| 239 |
attrs_queries.append(self._urlencode({param: item})) |
| 240 |
else: |
| 241 |
attrs_queries.append(self._urlencode({param: value})) |
| 242 |
query += '&'.join(attrs_queries) |
| 243 |
if query_params: |
| 244 |
if len(query) > 1: |
| 245 |
query += '&' |
| 246 |
query += self._urlencode(query_params, doseq=True) |
| 247 |
|
| 248 |
base_url = self._urljoin(self.wapi_url, |
| 249 |
self._quote(relative_path)) |
| 250 |
LOG.debug("Constructed URL: %s", base_url + query) |
| 251 |
return base_url + query |
| 252 |
|
| 253 |
@staticmethod |
| 254 |
def _validate_obj_type_or_die(obj_type, obj_type_expected=True): |
| 255 |
"""Validate object type |
| 256 |
|
| 257 |
Args: |
| 258 |
obj_type_expected (bool): If False, method will assume, that object |
| 259 |
ref is passed as the first argument. |
| 260 |
""" |
| 261 |
if not obj_type: |
| 262 |
raise ValueError('NIOS object type cannot be empty.') |
| 263 |
if obj_type_expected and '/' in obj_type: |
| 264 |
LOG.error( |
| 265 |
"NIOS object type cannot contain slash: {}".format(obj_type)) |
| 266 |
raise ValueError('NIOS object type cannot contain slash.') |
| 267 |
|
| 268 |
@staticmethod |
| 269 |
def _validate_authorized(response): |
| 270 |
if response.status_code == requests.codes.UNAUTHORIZED: |
| 271 |
raise ib_ex.InfobloxBadWAPICredential( |
| 272 |
response=response.content, |
| 273 |
content=utils.format_html(response.content), |
| 274 |
code=response.status_code |
| 275 |
) |
| 276 |
|
| 277 |
@staticmethod |
| 278 |
def _build_query_params(payload=None, return_fields=None, |
| 279 |
max_results=None, paging=False): |
| 280 |
if payload: |
| 281 |
query_params = payload |
| 282 |
else: |
| 283 |
query_params = dict() |
| 284 |
|
| 285 |
if return_fields: |
| 286 |
if 'default' in return_fields: |
| 287 |
return_fields.remove('default') |
| 288 |
query_params['_return_fields+'] = ','.join(return_fields) |
| 289 |
else: |
| 290 |
query_params['_return_fields'] = ','.join(return_fields) |
| 291 |
|
| 292 |
if max_results: |
| 293 |
query_params['_max_results'] = max_results |
| 294 |
|
| 295 |
if paging: |
| 296 |
query_params['_paging'] = 1 |
| 297 |
query_params['_return_as_object'] = 1 |
| 298 |
|
| 299 |
return query_params |
| 300 |
|
| 301 |
def is_cookie_expired(self): |
| 302 |
""" |
| 303 |
Check if the cookie is expired by comparing the expiration time |
| 304 |
with the current time. |
| 305 |
""" |
| 306 |
LOG.debug("Validating cookie expiration") |
| 307 |
cookie_jar = self.session.cookies |
| 308 |
for cookie in cookie_jar: |
| 309 |
if cookie.name == 'ibapauth': |
| 310 |
|
| 311 |
cookie_value = cookie.value.strip('"') |
| 312 |
cookie_parts = {} |
| 313 |
for part in cookie_value.split(','): |
| 314 |
if '=' in part: |
| 315 |
key, value = part.split('=', 1) |
| 316 |
cookie_parts[key] = value |
| 317 |
|
| 318 |
|
| 319 |
ctime = int(cookie_parts.get('ctime', 0)) |
| 320 |
timeout = int(cookie_parts.get('timeout', 0)) |
| 321 |
|
| 322 |
|
| 323 |
expiration_time = ctime + timeout |
| 324 |
|
| 325 |
|
| 326 |
current_time = int(time.time()) |
| 327 |
|
| 328 |
|
| 329 |
return current_time > expiration_time |
| 330 |
return True |
| 331 |
|
| 332 |
def _get_request_options(self, data=None): |
| 333 |
opts = dict(timeout=self.http_request_timeout, |
| 334 |
headers=self.DEFAULT_HEADER, |
| 335 |
verify=self.session.verify) |
| 336 |
if data: |
| 337 |
opts['data'] = jsonutils.dumps(data) |
| 338 |
return opts |
| 339 |
|
| 340 |
def _validate_cookie(self): |
| 341 |
if self.is_cookie_expired(): |
| 342 |
LOG.info("Cookie expired. \ |
| 343 |
Clearing cookies and re-authenticating on the next request.") |
| 344 |
self.session.cookies.clear() |
| 345 |
if hasattr(self, 'username') and hasattr(self, 'password'): |
| 346 |
LOG.info("Re-authenticating with username and password.") |
| 347 |
self.session.auth = (self.username, self.password) |
| 348 |
elif hasattr(self, 'cert') and hasattr(self, 'key'): |
| 349 |
LOG.info("Re-authenticating with client certificate.") |
| 350 |
self.session.cert = (self.cert, self.key) |
| 351 |
else: |
| 352 |
LOG.warning("No valid credentials found to re-authenticate.") |
| 353 |
raise ib_ex.InfobloxConfigException( |
| 354 |
msg="No valid credentials found to re-authenticate.") |
| 355 |
else: |
| 356 |
LOG.info("Using existing cookie for authentication") |
| 357 |
self.session.auth = None |
| 358 |
|
| 359 |
@staticmethod |
| 360 |
def _parse_reply(request): |
| 361 |
"""Tries to parse reply from NIOS. |
| 362 |
|
| 363 |
Raises exception with content if reply is not in json format |
| 364 |
""" |
| 365 |
try: |
| 366 |
LOG.debug("WAPI Response: %s", request.content) |
| 367 |
return jsonutils.loads(request.content) |
| 368 |
except ValueError: |
| 369 |
LOG.error("Failed to parse reply from NIOS: %s", request.content) |
| 370 |
raise ib_ex.InfobloxConnectionError(reason=request.content) |
| 371 |
|
| 372 |
def _log_request(self, verb, url, opts): |
| 373 |
message = ("Sending %s request to %s with parameters %s", |
| 374 |
verb, url, opts) |
| 375 |
if self.log_api_calls_as_info: |
| 376 |
LOG.info(*message) |
| 377 |
else: |
| 378 |
LOG.debug(*message) |
| 379 |
|
| 380 |
@reraise_neutron_exception |
| 381 |
@retry_on_expired_cookie |
| 382 |
def get_object(self, obj_type, payload=None, return_fields=None, |
| 383 |
extattrs=None, force_proxy=False, max_results=None, |
| 384 |
paging=None): |
| 385 |
"""Retrieve a list of Infoblox objects of type 'obj_type' |
| 386 |
|
| 387 |
Some get requests like 'ipv4address' should be always |
| 388 |
proxied to GM on Hellfire |
| 389 |
If request is cloud and proxy is not forced yet, |
| 390 |
then plan to do two requests: |
| 391 |
- the first one is not proxied to GM |
| 392 |
- the second is proxied to GM |
| 393 |
|
| 394 |
Args: |
| 395 |
obj_type (str): Infoblox object type, e.g. 'network', |
| 396 |
'range', etc. |
| 397 |
payload (dict): Payload with data to send |
| 398 |
return_fields (list): List of fields to be returned |
| 399 |
extattrs (dict): List of Extensible Attributes |
| 400 |
force_proxy (bool): Set _proxy_search flag |
| 401 |
to process requests on GM |
| 402 |
max_results (int): Maximum number of objects to be returned. |
| 403 |
If set to a negative number, the appliance will return an error |
| 404 |
when the number of returned objects would exceed the setting. |
| 405 |
The default is -1000. If this is set to a positive number, |
| 406 |
the results will be truncated when necessary. |
| 407 |
Paging (bool): Enables paging to wapi calls if paging = True, |
| 408 |
it uses _max_results to set paging size of the wapi calls. |
| 409 |
If _max_results is negative, it will take paging size as 1000. |
| 410 |
|
| 411 |
Returns: |
| 412 |
A list of the Infoblox objects requested |
| 413 |
Raises: |
| 414 |
requests.exceptions.HTTPError: If API responded with error HTTP |
| 415 |
status code. |
| 416 |
""" |
| 417 |
self._validate_obj_type_or_die(obj_type, obj_type_expected=False) |
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
if max_results is None and self.max_results: |
| 422 |
max_results = self.max_results |
| 423 |
|
| 424 |
if paging is None: |
| 425 |
paging = self.paging if self.paging else False |
| 426 |
|
| 427 |
query_params = self._build_query_params(payload=payload, |
| 428 |
return_fields=return_fields, |
| 429 |
max_results=max_results, |
| 430 |
paging=paging) |
| 431 |
|
| 432 |
proxy_flag = self.cloud_api_enabled and force_proxy |
| 433 |
|
| 434 |
try: |
| 435 |
return self._handle_get_object( |
| 436 |
obj_type, query_params, extattrs, proxy_flag) |
| 437 |
except req_exc.HTTPError: |
| 438 |
LOG.warning( |
| 439 |
"Failed on object search with proxy flag %s", proxy_flag) |
| 440 |
|
| 441 |
return self._handle_get_object(obj_type, query_params, |
| 442 |
extattrs, proxy_flag=True) |
| 443 |
|
| 444 |
def _handle_get_object(self, obj_type, query_params, extattrs, |
| 445 |
proxy_flag=False): |
| 446 |
if '_paging' in query_params: |
| 447 |
|
| 448 |
if not ('_max_results' in query_params): |
| 449 |
query_params['_max_results'] = 1000 |
| 450 |
|
| 451 |
if query_params['_max_results'] < 0: |
| 452 |
|
| 453 |
|
| 454 |
query_params['_max_results'] = 1000 |
| 455 |
|
| 456 |
result = [] |
| 457 |
while True: |
| 458 |
|
| 459 |
url = self._construct_url(obj_type, query_params, extattrs, |
| 460 |
force_proxy=proxy_flag) |
| 461 |
resp = self._get_object(obj_type, url) |
| 462 |
if not resp: |
| 463 |
return None |
| 464 |
if not ('next_page_id' in resp): |
| 465 |
result.extend(resp['result']) |
| 466 |
query_params.pop('_page_id', None) |
| 467 |
return result |
| 468 |
else: |
| 469 |
query_params['_page_id'] = resp['next_page_id'] |
| 470 |
result.extend(resp['result']) |
| 471 |
else: |
| 472 |
url = self._construct_url(obj_type, query_params, extattrs, |
| 473 |
force_proxy=proxy_flag) |
| 474 |
return self._get_object(obj_type, url) |
| 475 |
|
| 476 |
def _get_object(self, obj_type, url): |
| 477 |
opts = self._get_request_options() |
| 478 |
self._log_request('get', url, opts) |
| 479 |
if self.session.cookies: |
| 480 |
|
| 481 |
|
| 482 |
self._validate_cookie() |
| 483 |
r = self.session.get(url, **opts) |
| 484 |
|
| 485 |
self._validate_authorized(r) |
| 486 |
|
| 487 |
if r.status_code != requests.codes.ok: |
| 488 |
LOG.warning("Failed on object search with url %s: %s", |
| 489 |
url, r.content) |
| 490 |
r.raise_for_status() |
| 491 |
return self._parse_reply(r) |
| 492 |
|
| 493 |
@reraise_neutron_exception |
| 494 |
@retry_on_expired_cookie |
| 495 |
def download_file(self, url): |
| 496 |
LOG.debug("Downloading file from %s", url) |
| 497 |
req_cookies = None |
| 498 |
if self.session.cookies: |
| 499 |
self._validate_cookie() |
| 500 |
cookies_dict = self.session.cookies.get_dict() |
| 501 |
ibapauth_cookie = cookies_dict.get('ibapauth', None) |
| 502 |
if ibapauth_cookie: |
| 503 |
req_cookies = {'ibapauth': ibapauth_cookie} |
| 504 |
else: |
| 505 |
req_cookies = None |
| 506 |
|
| 507 |
headers = {'content-type': 'application/force-download'} |
| 508 |
r = self.session.get(url, headers=headers, cookies=req_cookies) |
| 509 |
if r.status_code != requests.codes.ok: |
| 510 |
res_content = utils.format_html(r.content) |
| 511 |
LOG.error("Failed to download file from %s: %s", url, res_content) |
| 512 |
response = utils.safe_json_load(r.content) |
| 513 |
raise ib_ex.InfobloxFileDownloadFailed( |
| 514 |
response=response, |
| 515 |
url=url, |
| 516 |
content=res_content, |
| 517 |
code=r.status_code |
| 518 |
) |
| 519 |
return r |
| 520 |
|
| 521 |
@reraise_neutron_exception |
| 522 |
@retry_on_expired_cookie |
| 523 |
def upload_file(self, url, files): |
| 524 |
"""Upload file to fully-qualified upload url |
| 525 |
|
| 526 |
Args: |
| 527 |
url (str): upload url provided by infoblox fileop uploadinit |
| 528 |
files (dict): file contents payload |
| 529 |
Returns: |
| 530 |
The requests response |
| 531 |
Raises: |
| 532 |
InfobloxException |
| 533 |
""" |
| 534 |
LOG.debug("Uploading file to %s", url) |
| 535 |
req_cookies = None |
| 536 |
if self.session.cookies: |
| 537 |
self._validate_cookie() |
| 538 |
cookies_dict = self.session.cookies.get_dict() |
| 539 |
ibapauth_cookie = cookies_dict.get('ibapauth', None) |
| 540 |
if ibapauth_cookie: |
| 541 |
req_cookies = {'ibapauth': ibapauth_cookie} |
| 542 |
else: |
| 543 |
req_cookies = None |
| 544 |
r = self.session.post(url, files=files, cookies=req_cookies) |
| 545 |
if r.status_code != requests.codes.ok: |
| 546 |
response = utils.safe_json_load(r.content) |
| 547 |
res_content = utils.format_html(r.content) |
| 548 |
LOG.error("Failed to upload file to %s: %s", url, res_content) |
| 549 |
raise ib_ex.InfobloxFileUploadFailed( |
| 550 |
response=response, |
| 551 |
url=url, |
| 552 |
content=res_content, |
| 553 |
code=r.status_code, |
| 554 |
) |
| 555 |
return r |
| 556 |
|
| 557 |
@reraise_neutron_exception |
| 558 |
@retry_on_expired_cookie |
| 559 |
def create_object(self, obj_type, payload, return_fields=None): |
| 560 |
"""Create an Infoblox object of type 'obj_type' |
| 561 |
|
| 562 |
Args: |
| 563 |
obj_type (str): Infoblox object type, |
| 564 |
e.g. 'network', 'range', etc. |
| 565 |
payload (dict): Payload with data to send |
| 566 |
return_fields (list): List of fields to be returned |
| 567 |
Returns: |
| 568 |
The object reference of the new creation object |
| 569 |
Raises: |
| 570 |
InfobloxException |
| 571 |
""" |
| 572 |
self._validate_obj_type_or_die(obj_type) |
| 573 |
|
| 574 |
query_params = self._build_query_params(return_fields=return_fields) |
| 575 |
|
| 576 |
url = self._construct_url(obj_type, query_params) |
| 577 |
opts = self._get_request_options(data=payload) |
| 578 |
self._log_request('post', url, opts) |
| 579 |
if self.session.cookies: |
| 580 |
|
| 581 |
|
| 582 |
self._validate_cookie() |
| 583 |
r = self.session.post(url, **opts) |
| 584 |
|
| 585 |
self._validate_authorized(r) |
| 586 |
|
| 587 |
if r.status_code != requests.codes.CREATED: |
| 588 |
LOG.error( |
| 589 |
"Failed to create object with url %s: %s", url, r.content) |
| 590 |
response = utils.safe_json_load(r.content) |
| 591 |
already_assigned = 'is assigned to another network view' |
| 592 |
if response and already_assigned in response.get('text'): |
| 593 |
exception = ib_ex.InfobloxMemberAlreadyAssigned |
| 594 |
else: |
| 595 |
exception = ib_ex.InfobloxCannotCreateObject |
| 596 |
raise exception( |
| 597 |
response=response, |
| 598 |
obj_type=obj_type, |
| 599 |
content=r.content, |
| 600 |
args=payload, |
| 601 |
code=r.status_code) |
| 602 |
|
| 603 |
return self._parse_reply(r) |
| 604 |
|
| 605 |
def _check_service_availability(self, operation, resp, ref): |
| 606 |
if resp.status_code == requests.codes.SERVICE_UNAVAILABLE: |
| 607 |
raise ib_ex.InfobloxGridTemporaryUnavailable( |
| 608 |
response=resp.content, |
| 609 |
operation=operation, |
| 610 |
ref=ref, |
| 611 |
content=resp.content, |
| 612 |
code=resp.status_code) |
| 613 |
|
| 614 |
@reraise_neutron_exception |
| 615 |
@retry_on_expired_cookie |
| 616 |
def call_func(self, func_name, ref, payload, return_fields=None): |
| 617 |
LOG.debug("Calling function %s on object %s", func_name, ref) |
| 618 |
if self.session.cookies: |
| 619 |
self._validate_cookie() |
| 620 |
query_params = self._build_query_params(return_fields=return_fields) |
| 621 |
query_params['_function'] = func_name |
| 622 |
|
| 623 |
url = self._construct_url(ref, query_params) |
| 624 |
opts = self._get_request_options(data=payload) |
| 625 |
self._log_request('post', url, opts) |
| 626 |
r = self.session.post(url, **opts) |
| 627 |
|
| 628 |
self._validate_authorized(r) |
| 629 |
|
| 630 |
if r.status_code not in (requests.codes.CREATED, |
| 631 |
requests.codes.ok): |
| 632 |
self._check_service_availability('call_func', r, ref) |
| 633 |
|
| 634 |
raise ib_ex.InfobloxFuncException( |
| 635 |
response=jsonutils.loads(r.content), |
| 636 |
ref=ref, |
| 637 |
func_name=func_name, |
| 638 |
content=r.content, |
| 639 |
code=r.status_code) |
| 640 |
|
| 641 |
return self._parse_reply(r) |
| 642 |
|
| 643 |
@reraise_neutron_exception |
| 644 |
@retry_on_expired_cookie |
| 645 |
def update_object(self, ref, payload, return_fields=None): |
| 646 |
"""Update an Infoblox object |
| 647 |
|
| 648 |
Args: |
| 649 |
ref (str): Infoblox object reference |
| 650 |
payload (dict): Payload with data to send |
| 651 |
return_fields (list): List of fields to return |
| 652 |
Returns: |
| 653 |
The object reference of the updated object |
| 654 |
Raises: |
| 655 |
InfobloxException |
| 656 |
""" |
| 657 |
query_params = self._build_query_params(return_fields=return_fields) |
| 658 |
|
| 659 |
opts = self._get_request_options(data=payload) |
| 660 |
url = self._construct_url(ref, query_params) |
| 661 |
self._log_request('put', url, opts) |
| 662 |
if self.session.cookies: |
| 663 |
self._validate_cookie() |
| 664 |
r = self.session.put(url, **opts) |
| 665 |
|
| 666 |
self._validate_authorized(r) |
| 667 |
|
| 668 |
if r.status_code != requests.codes.ok: |
| 669 |
self._check_service_availability('update', r, ref) |
| 670 |
|
| 671 |
raise ib_ex.InfobloxCannotUpdateObject( |
| 672 |
response=jsonutils.loads(r.content), |
| 673 |
ref=ref, |
| 674 |
content=r.content, |
| 675 |
code=r.status_code) |
| 676 |
|
| 677 |
return self._parse_reply(r) |
| 678 |
|
| 679 |
@reraise_neutron_exception |
| 680 |
@retry_on_expired_cookie |
| 681 |
def delete_object(self, ref, delete_arguments=None): |
| 682 |
"""Remove an Infoblox object |
| 683 |
|
| 684 |
Args: |
| 685 |
ref (str): Object reference |
| 686 |
delete_arguments (dict): Extra delete arguments |
| 687 |
Returns: |
| 688 |
The object reference of the removed object |
| 689 |
Raises: |
| 690 |
InfobloxException |
| 691 |
""" |
| 692 |
opts = self._get_request_options() |
| 693 |
if not isinstance(delete_arguments, dict): |
| 694 |
delete_arguments = {} |
| 695 |
url = self._construct_url(ref, query_params=delete_arguments) |
| 696 |
self._log_request('delete', url, opts) |
| 697 |
if self.session.cookies: |
| 698 |
self._validate_cookie() |
| 699 |
r = self.session.delete(url, **opts) |
| 700 |
|
| 701 |
self._validate_authorized(r) |
| 702 |
|
| 703 |
if r.status_code != requests.codes.ok: |
| 704 |
self._check_service_availability('delete', r, ref) |
| 705 |
|
| 706 |
raise ib_ex.InfobloxCannotDeleteObject( |
| 707 |
response=jsonutils.loads(r.content), |
| 708 |
ref=ref, |
| 709 |
content=r.content, |
| 710 |
code=r.status_code) |
| 711 |
|
| 712 |
return self._parse_reply(r) |
| 713 |
|
| 714 |
@staticmethod |
| 715 |
def is_cloud_wapi(wapi_version): |
| 716 |
"""Validate that a WAPI semantic version is valid. |
| 717 |
|
| 718 |
Args: |
| 719 |
wapi_version (str): WAPI semantic version |
| 720 |
|
| 721 |
Returns: |
| 722 |
True if the major version is higher than a given threshold, |
| 723 |
False otherwise. |
| 724 |
|
| 725 |
Raises: |
| 726 |
ValueError: if an invalid version is passed |
| 727 |
""" |
| 728 |
valid = wapi_version and isinstance(wapi_version, six.string_types) |
| 729 |
if not valid: |
| 730 |
raise ValueError("Invalid argument was passed") |
| 731 |
version_match = re.search(r'(\d+)\.(\d+)', wapi_version) |
| 732 |
if version_match: |
| 733 |
if int(version_match.group(1)) >= CLOUD_WAPI_MAJOR_VERSION: |
| 734 |
LOG.debug("Cloud WAPI version detected: %s", wapi_version) |
| 735 |
return True |
| 736 |
LOG.debug("Non-cloud WAPI version detected: %s", wapi_version) |
| 737 |
return False |