Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/module_utils/icontrol.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2017, F5 Networks Inc.
4 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9
10 import os
11
12 try:
13 from StringIO import StringIO
14 except ImportError:
15 from io import StringIO
16
17 try:
18 from BytesIO import BytesIO
19 except ImportError:
20 from io import BytesIO
21
22 from ansible.module_utils.urls import urlparse
23 from ansible.module_utils.urls import generic_urlparse
24 from ansible.module_utils.urls import Request
25
26 try:
27 import json as _json
28 except ImportError:
29 import simplejson as _json
30
31 from .common import F5ModuleError
32
33
34 """An F5 REST API URI handler.
35
36 Use this module to make calls to an F5 REST server. It is influenced by the same
37 API that the Python ``requests`` tool uses, but the two are not the same, as the
38 library here is **much** more simple and targeted specifically to F5's needs.
39
40 The ``requests`` design was chosen due to familiarity with the tool. Internally,
41 the classes contained herein use Ansible native libraries.
42
43 The means by which you should use it are similar to ``requests`` basic usage.
44
45 Authentication is not handled for you automatically by this library, however it *is*
46 handled automatically for you in the supporting F5 module_utils code; specifically the
47 different product module_util files (bigip.py, bigiq.py, etc).
48
49 Internal (non-module) usage of this library looks like this.
50
51 ```
52 # Create a session instance
53 mgmt = iControlRestSession()
54 mgmt.verify = False
55
56 server = '1.1.1.1'
57 port = 443
58
59 # Payload used for getting an initial authentication token
60 payload = {
61 'username': 'admin',
62 'password': 'secret',
63 'loginProviderName': 'tmos'
64 }
65
66 # Create URL to call, injecting server and port
67 url = f"https://{server}:{port}/mgmt/shared/authn/login"
68
69 # Call the API
70 resp = session.post(url, json=payload)
71
72 # View the response
73 print(resp.json())
74
75 # Update the session with the authentication token
76 session.headers['X-F5-Auth-Token'] = resp.json()['token']['token']
77
78 # Create another URL to call, injecting server and port
79 url = f"https://{server}:{port}/mgmt/tm/ltm/virtual/~Common~virtual1"
80
81 # Call the API
82 resp = session.get(url)
83
84 # View the details of a virtual payload
85 print(resp.json())
86 ```
87 """
88
89 from ansible.module_utils.six.moves.urllib.error import HTTPError
90
91 from .constants import (
92 LOGOUT, BASE_HEADERS
93 )
94
95
96 class Response(object):
97 def __init__(self):
98 self._content = None
99 self.status = None
100 self.headers = dict()
101 self.url = None
102 self.reason = None
103 self.request = None
104 self.msg = None
105
106 @property
107 def content(self):
108 return self._content
109
110 @property
111 def raw_content(self):
112 return self._content
113
114 def json(self):
115 return _json.loads(self._content or 'null')
116
117 @property
118 def ok(self):
119 if self.status is not None and int(self.status) > 400:
120 return False
121 try:
122 response = self.json()
123 if 'code' in response and response['code'] > 400:
124 return False
125 except ValueError:
126 pass
127 return True
128
129
130 class iControlRestSession(object):
131 """Represents a session that communicates with a BigIP.
132
133 This acts as a loose wrapper around Ansible's ``Request`` class. We're doing
134 this as interim work until we move to the httpapi connector.
135 """
136 def __init__(self, headers=None, use_proxy=True, force=False, timeout=120,
137 validate_certs=True, url_username=None, url_password=None,
138 http_agent=None, force_basic_auth=False, follow_redirects='urllib2',
139 client_cert=None, client_key=None, cookies=None):
140 self.request = Request(
141 headers=headers,
142 use_proxy=use_proxy,
143 force=force,
144 timeout=timeout,
145 validate_certs=validate_certs,
146 url_username=url_username,
147 url_password=url_password,
148 http_agent=http_agent,
149 force_basic_auth=force_basic_auth,
150 follow_redirects=follow_redirects,
151 client_cert=client_cert,
152 client_key=client_key,
153 cookies=cookies
154 )
155 self.last_url = None
156
157 def get_headers(self, result):
158 try:
159 return dict(result.getheaders())
160 except AttributeError:
161 return result.headers
162
163 def update_response(self, response, result):
164 response.headers = self.get_headers(result)
165 response._content = result.read()
166 response.status = result.getcode()
167 response.url = result.geturl()
168 response.msg = "OK (%s bytes)" % response.headers.get('Content-Length', 'unknown')
169
170 def send(self, method, url, **kwargs):
171 response = Response()
172
173 # Set the last_url called
174 #
175 # This is used by the object destructor to erase the token when the
176 # ModuleManager exits and destroys the iControlRestSession object
177 self.last_url = url
178
179 body = None
180 data = kwargs.pop('data', None)
181 json = kwargs.pop('json', None)
182
183 if not data and json is not None:
184 self.request.headers.update(BASE_HEADERS)
185 body = _json.dumps(json, ensure_ascii=False)
186 if not isinstance(body, bytes):
187 body = body.encode('utf-8')
188 if data:
189 body = data
190 if body:
191 kwargs['data'] = body
192
193 try:
194 result = self.request.open(method, url, **kwargs)
195 except HTTPError as e:
196 # Catch HTTPError delivered from Ansible
197 #
198 # The structure of this object, in Ansible 2.8 is
199 #
200 # HttpError {
201 # args
202 # characters_written
203 # close
204 # code
205 # delete
206 # errno
207 # file
208 # filename
209 # filename2
210 # fp
211 # getcode
212 # geturl
213 # hdrs
214 # headers
215 # info
216 # msg
217 # name
218 # reason
219 # strerror
220 # url
221 # with_traceback
222 # }
223 self.update_response(response, e)
224 return response
225
226 self.update_response(response, result)
227 return response
228
229 def delete(self, url, **kwargs):
230 return self.send('DELETE', url, **kwargs)
231
232 def get(self, url, **kwargs):
233 return self.send('GET', url, **kwargs)
234
235 def patch(self, url, data=None, **kwargs):
236 return self.send('PATCH', url, data=data, **kwargs)
237
238 def post(self, url, data=None, **kwargs):
239 return self.send('POST', url, data=data, **kwargs)
240
241 def put(self, url, data=None, **kwargs):
242 return self.send('PUT', url, data=data, **kwargs)
243
244 def __del__(self):
245 if self.last_url is None:
246 return
247 token = self.request.headers.get('X-F5-Auth-Token', None)
248 if not token:
249 return
250 try:
251 p = generic_urlparse(urlparse(self.last_url))
252 uri = "https://{0}:{1}{2}{3}".format(
253 p['hostname'], p['port'], LOGOUT, token
254 )
255 self.delete(uri)
256 except ValueError:
257 pass
258
259
260 class TransactionContextManager(object):
261 def __init__(self, client, validate_only=False):
262 self.client = client
263 self.validate_only = validate_only
264 self.transid = None
265
266 def __enter__(self):
267 uri = "https://{0}:{1}/mgmt/tm/transaction/".format(
268 self.client.provider['server'],
269 self.client.provider['server_port']
270 )
271 resp = self.client.api.post(uri, json={})
272 if resp.status not in [200]:
273 try:
274 response = resp.json()
275 if 'message' in response:
276 raise F5ModuleError(
277 'Failed to create transaction: {0}'.format(response['message'])
278 )
279 except ValueError:
280 pass
281 raise F5ModuleError(
282 'Failed to create transaction, status: {0}, contents: {1}'.format(
283 resp.status, resp.content
284 )
285 )
286 try:
287 response = resp.json()
288 except ValueError as ex:
289 raise F5ModuleError(str(ex))
290
291 self.transid = response['transId']
292 self.client.api.request.headers['X-F5-REST-Coordination-Id'] = self.transid
293 return self.client
294
295 def __exit__(self, exc_type, exc_value, exc_tb):
296 self.client.api.request.headers.pop('X-F5-REST-Coordination-Id')
297 if exc_tb is None:
298 uri = "https://{0}:{1}/mgmt/tm/transaction/{2}".format(
299 self.client.provider['server'],
300 self.client.provider['server_port'],
301 self.transid
302 )
303 params = dict(
304 state="VALIDATING",
305 validateOnly=self.validate_only
306 )
307 resp = self.client.api.patch(uri, json=params)
308 if resp.status not in [200]:
309 try:
310 response = resp.json()
311 if 'message' in response:
312 raise F5ModuleError(
313 'Failed to commit transaction {0}: {1}'.format(
314 self.transid, response['message']
315 )
316 )
317 except ValueError:
318 pass
319 raise F5ModuleError(
320 'Failed to commit transaction {0}, status: {1}, contents: {2}'.format(
321 self.transid, resp.status, resp.content
322 )
323 )
324
325
326 def download_asm_file(client, url, dest, file_size):
327 """Download a large ASM file from the remote device
328
329 This method handles issues with ASM file endpoints that allow
330 downloads of ASM objects on the BIG-IP, as well as handles
331 chunking of large files.
332
333 Arguments:
334 client (object): The F5RestClient connection object.
335 url (string): The URL to download.
336 dest (string): The location on (Ansible controller) disk to store the file.
337 file_size (integer): The size of the remote file.
338
339 Returns:
340 bool: No response on success. Fail otherwise.
341 """
342
343 with open(dest, 'wb') as fileobj:
344 chunk_size = 512 * 1024
345 start = 0
346 end = chunk_size - 1
347 size = file_size
348 # current_bytes = 0
349
350 while True:
351 content_range = "%s-%s/%s" % (start, end, size)
352 headers = {
353 'Content-Range': content_range,
354 'Content-Type': 'application/json'
355 }
356 data = {
357 'headers': headers,
358 'verify': False,
359 'stream': False
360 }
361
362 response = client.api.get(url, headers=headers, json=data)
363 if response.status == 200:
364 if 'Content-Length' not in response.headers:
365 error_message = "The Content-Length header is not present."
366 raise F5ModuleError(error_message)
367 length = response.headers['Content-Length']
368 if int(length) > 0:
369 fileobj.write(response.content)
370 else:
371 error = "Invalid Content-Length value returned: %s ," \
372 "the value should be greater than 0" % length
373 raise F5ModuleError(error)
374 # fileobj.write(response.raw_content)
375 if end == size:
376 break
377 start += chunk_size
378 if start >= size:
379 break
380 if (end + chunk_size) > size:
381 end = size - 1
382 else:
383 end = start + chunk_size - 1
384
385
386 def download_file(client, url, dest):
387 """Download a file from the remote device
388
389 This method handles the chunking needed to download a file from
390 a given URL on the BIG-IP.
391
392 Arguments:
393 client (object): The F5RestClient connection object.
394 url (string): The URL to download.
395 dest (string): The location on (Ansible controller) disk to store the file.
396
397 Returns:
398 bool: True on success. False otherwise.
399 """
400 with open(dest, 'wb') as fileobj:
401 chunk_size = 512 * 1024
402 start = 0
403 end = chunk_size - 1
404 size = 0
405 current_bytes = 0
406
407 while True:
408 content_range = "%s-%s/%s" % (start, end, size)
409 headers = {
410 'Content-Range': content_range,
411 'Content-Type': 'application/octet-stream'
412 }
413 data = {
414 'headers': headers,
415 'verify': False,
416 'stream': False
417 }
418 response = client.api.get(url, headers=headers, json=data)
419 if response.status == 200:
420 # If the size is zero, then this is the first time through
421 # the loop and we don't want to write data because we
422 # haven't yet figured out the total size of the file.
423 if size > 0:
424 current_bytes += chunk_size
425 fileobj.write(response.raw_content)
426 # Once we've downloaded the entire file, we can break out of
427 # the loop
428 if end == size:
429 break
430 crange = response.headers['Content-Range']
431 # Determine the total number of bytes to read.
432 if size == 0:
433 size = int(crange.split('/')[-1]) - 1
434 # If the file is smaller than the chunk_size, the BigIP
435 # will return an HTTP 400. Adjust the chunk_size down to
436 # the total file size...
437 if chunk_size > size:
438 end = size
439 # ...and pass on the rest of the code.
440 continue
441 start += chunk_size
442 if (current_bytes + chunk_size) > size:
443 end = size
444 else:
445 end = start + chunk_size - 1
446 return True
447
448
449 def upload_file(client, url, src, dest=None):
450 """Upload a file to an arbitrary URL.
451
452 This method is responsible for correctly chunking an upload request to an
453 arbitrary file worker URL.
454
455 Arguments:
456 client (object): The F5RestClient connection object.
457 url (string): The URL to upload a file to.
458 src (string): The file to be uploaded.
459 dest (string): The file name to create on the remote device.
460
461 Examples:
462 The ``dest`` may be either an absolute or relative path. The basename
463 of the path is used as the remote file name upon upload. For instance,
464 in the example below, ``BIGIP-13.1.0.8-0.0.3.iso`` would be the name
465 of the remote file.
466
467 The specified URL should be the full URL to where you want to upload a
468 file. BIG-IP has many different URLs that can be used to handle different
469 types of files. This is why a full URL is required.
470
471 >>> from ansible_collections.f5networks.f5_modules.plugins.module_utils.icontrol import upload_client
472 >>> url = 'https://{0}:{1}/mgmt/cm/autodeploy/software-image-uploads'.format(
473 ... self.client.provider['server'],
474 ... self.client.provider['server_port']
475 ... )
476 >>> dest = '/path/to/BIGIP-13.1.0.8-0.0.3.iso'
477 >>> upload_file(self.client, url, dest)
478 True
479
480 Returns:
481 bool: True on success. False otherwise.
482
483 Raises:
484 F5ModuleError: Raised if ``retries`` limit is exceeded.
485 """
486 if isinstance(src, StringIO) or isinstance(src, BytesIO):
487 fileobj = src
488 else:
489 fileobj = open(src, 'rb')
490
491 try:
492 size = os.stat(src).st_size
493 is_file = True
494 except TypeError:
495 src.seek(0, os.SEEK_END)
496 size = src.tell()
497 src.seek(0)
498 is_file = False
499
500 # This appears to be the largest chunk size that iControlREST can handle.
501 #
502 # The trade-off you are making by choosing a chunk size is speed, over size of
503 # transmission. A lower chunk size will be slower because a smaller amount of
504 # data is read from disk and sent via HTTP. Lots of disk reads are slower and
505 # There is overhead in sending the request to the BIG-IP.
506 #
507 # Larger chunk sizes are faster because more data is read from disk in one
508 # go, and therefore more data is transmitted to the BIG-IP in one HTTP request.
509 #
510 # If you are transmitting over a slow link though, it may be more reliable to
511 # transmit many small chunks that fewer large chunks. It will clearly take
512 # longer, but it may be more robust.
513 chunk_size = 1024 * 7168
514 start = 0
515 retries = 0
516 if dest is None and is_file:
517 basename = os.path.basename(src)
518 else:
519 basename = dest
520 url = '{0}/{1}'.format(url.rstrip('/'), basename)
521
522 while True:
523 if retries == 3:
524 # Retries are used here to allow the REST API to recover if you kill
525 # an upload mid-transfer.
526 #
527 # There exists a case where retrying a new upload will result in the
528 # API returning the POSTed payload (in bytes) with a non-200 response
529 # code.
530 #
531 # Retrying (after seeking back to 0) seems to resolve this problem.
532 raise F5ModuleError(
533 "Failed to upload file too many times."
534 )
535 try:
536 file_slice = fileobj.read(chunk_size)
537 if not file_slice:
538 break
539
540 current_bytes = len(file_slice)
541 if current_bytes < chunk_size:
542 end = size
543 else:
544 end = start + current_bytes
545 headers = {
546 'Content-Range': '%s-%s/%s' % (start, end - 1, size),
547 'Content-Type': 'application/octet-stream'
548 }
549
550 # Data should always be sent using the ``data`` keyword and not the
551 # ``json`` keyword. This allows bytes to be sent (such as in the case
552 # of uploading ISO files.
553 response = client.api.post(url, headers=headers, data=file_slice)
554
555 if response.status != 200:
556 # When this fails, the output is usually the body of whatever you
557 # POSTed. This is almost always unreadable because it is a series
558 # of bytes.
559 #
560 # Therefore, we only inform on the returned HTTP error code.
561 raise F5ModuleError('Error during upload, http error code: {0}'.format(str(response.status)))
562 start += current_bytes
563 except F5ModuleError:
564 # You must seek back to the beginning of the file upon exception.
565 #
566 # If this is not done, then you risk uploading a partial file.
567 fileobj.seek(0)
568 retries += 1
569 return True
570
571
572 def tmos_version(client):
573 uri = "https://{0}:{1}/mgmt/tm/sys/".format(
574 client.provider['server'],
575 client.provider['server_port'],
576 )
577 resp = client.api.get(uri)
578
579 try:
580 response = resp.json()
581 except ValueError as ex:
582 raise F5ModuleError(str(ex))
583
584 if 'code' in response and response['code'] in [400, 403]:
585 if 'message' in response:
586 raise F5ModuleError(response['message'])
587 else:
588 raise F5ModuleError(resp.content)
589
590 to_parse = urlparse(response['selfLink'])
591 query = to_parse.query
592 version = query.split('=')[1]
593 return version
594
595
596 def bigiq_version(client):
597 uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-shared-all-big-iqs/devices".format(
598 client.provider['server'],
599 client.provider['server_port'],
600 )
601 query = "?$select=version"
602
603 resp = client.api.get(uri + query)
604
605 try:
606 response = resp.json()
607 except ValueError as ex:
608 raise F5ModuleError(str(ex))
609
610 if 'code' in response and response['code'] in [400, 403]:
611 if 'message' in response:
612 raise F5ModuleError(response['message'])
613 else:
614 raise F5ModuleError(resp.content)
615
616 if 'items' in response:
617 version = response['items'][0]['version']
618 return version
619
620 raise F5ModuleError(
621 'Failed to retrieve BIG-IQ version information.'
622 )
623
624
625 def module_provisioned(client, module_name):
626 provisioned = modules_provisioned(client)
627 if module_name in provisioned:
628 return True
629 return False
630
631
632 def package_installed(client, package_name):
633 provisioned = packages_installed(client)
634 if package_name in provisioned:
635 return True
636 return False
637
638
639 def modules_provisioned(client):
640 """Returns a list of all provisioned modules
641
642 Args:
643 client: Client connection to the BIG-IP
644
645 Returns:
646 A list of provisioned modules in their short name for.
647 For example, ['afm', 'asm', 'ltm']
648 """
649 uri = "https://{0}:{1}/mgmt/tm/sys/provision".format(
650 client.provider['server'],
651 client.provider['server_port']
652 )
653 resp = client.api.get(uri)
654
655 try:
656 response = resp.json()
657 except ValueError as ex:
658 raise F5ModuleError(str(ex))
659
660 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
661 raise F5ModuleError(resp.content)
662
663 if 'items' not in response:
664 return []
665 return [x['name'] for x in response['items'] if x['level'] != 'none']
666
667
668 def packages_installed(client):
669 """Returns a list of installed ATC packages
670
671 Args:
672 client: Client connection to the BIG-IP
673
674 Returns:
675 A list of installed packages in their short name for.
676 For example, ['as3', 'do', 'ts']
677 """
678 packages = {
679 "f5-declarative-onboarding": "do",
680 "f5-appsvcs": "as3",
681 "f5-appsvcs-templates": "fast",
682 "f5-cloud-failover": "cfe",
683 "f5-telemetry": "ts",
684 "f5-service-discovery": "sd"
685
686 }
687
688 uri = "https://{0}:{1}/mgmt/shared/iapp/global-installed-packages".format(
689 client.provider['server'],
690 client.provider['server_port']
691 )
692 resp = client.api.get(uri)
693
694 try:
695 response = resp.json()
696 except ValueError as ex:
697 raise F5ModuleError(str(ex))
698
699 if 'code' in response and response['code'] == 404:
700 return []
701 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
702 raise F5ModuleError(resp.content)
703 if 'items' not in response:
704 return []
705
706 result = [packages[x['appName']] for x in response['items'] if x['appName'] in packages.keys()]
707 return result