Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_ucs_fetch.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_ucs_fetch
13 short_description: Fetches a UCS file from remote nodes
14 description:
15 - This module is used for fetching UCS files from remote machines and
16 storing them locally in a file tree, organized by hostname. This module
17 was written to create and transfer UCS files that might not be present,
18 it does not require UCS file to be pre-created. So a missing remote UCS
19 is not an error unless C(fail_on_missing) is set to 'yes'.
20 version_added: "1.0.0"
21 options:
22 backup:
23 description:
24 - Creates a backup file including the timestamp information so you can
25 get the original file back if you overwrote it incorrectly.
26 type: bool
27 default: false
28 create_on_missing:
29 description:
30 - Creates the UCS based on the value of C(src), if the file does not already
31 exist on the remote system.
32 - When set to C(false), with C(fail_on_missing) set to C(false) the module will return no change
33 if the ucs file is missing on device.
34 type: bool
35 default: true
36 dest:
37 description:
38 - A directory to save the UCS file into.
39 - This option is mandatory when C(only_create_file) is set to C(false).
40 type: path
41 encryption_password:
42 description:
43 - Password to use to encrypt the UCS file if desired.
44 type: str
45 fail_on_missing:
46 description:
47 - Make the module fail if the UCS file on the remote system is missing.
48 - This option always takes precedence over C(create_on_missing), hence when set to C(true), the module will
49 always fail if the UCS is missing, even if C(create_on_missing) option is set to C(true).
50 - When set to C(false), with C(create_on_missing) set to C(false) the module will return no change
51 if the ucs file is missing on device.
52 type: bool
53 default: false
54 force:
55 description:
56 - If C(false), the file is only transferred if the destination does not
57 exist.
58 type: bool
59 default: true
60 src:
61 description:
62 - The name of the UCS file to create on the remote server for downloading.
63 - The file is retrieved or created in /var/local/ucs/.
64 - This option is mandatory when C(only_create_file) is set to C(true).
65 type: str
66 async_timeout:
67 description:
68 - Parameter used when creating new UCS file on a device.
69 - The number of seconds to wait for the API async interface to complete its task.
70 - The accepted value range is between C(150) and C(1800) seconds.
71 type: int
72 default: 150
73 only_create_file:
74 description:
75 - If C(true), the file is created on the device and not downloaded. If the UCS archive exists on the device,
76 no change is made and the file is not downloaded.
77 - To recreate UCS files left on the device, remove them with the C(bigip_ucs) module before running this
78 module with C(only_create_file) set to C(true).
79 type: bool
80 default: false
81 version_added: "1.12.0"
82 notes:
83 - BIG-IP provides no way to get a checksum of the UCS files on the system
84 via any interface with the possible exception of logging in directly to the box (which
85 would not support appliance mode). Therefore, the best this module can
86 do is check for the existence of the file on disk; no check-summing.
87 - If you are using this module with either Ansible Tower or Ansible AWX, you
88 should be aware of how these Ansible products execute jobs in restricted
89 environments. More information can be found here
90 https://clouddocs.f5.com/products/orchestration/ansible/devel/usage/module-usage-with-tower.html
91 - Some longer running tasks might cause the REST interface on BIG-IP to time out, to avoid this adjust the timers as
92 per this KB article https://support.f5.com/csp/article/K94602685
93 extends_documentation_fragment:
94 - f5networks.f5_modules.f5
95 - ansible.builtin.files
96 author:
97 - Tim Rupp (@caphrim007)
98 - Wojciech Wypior (@wojtek0806)
99 '''
100
101 EXAMPLES = r'''
102 - name: Download a new UCS
103 bigip_ucs_fetch:
104 src: cs_backup.ucs
105 dest: /tmp/cs_backup.ucs
106 provider:
107 server: lb.mydomain.com
108 user: admin
109 password: secret
110 delegate_to: localhost
111
112 - name: Only create new UCS, no download
113 bigip_ucs_fetch:
114 src: cs_backup.ucs
115 only_create_file: true
116 provider:
117 server: lb.mydomain.com
118 user: admin
119 password: secret
120 delegate_to: localhost
121
122 - name: Recreate UCS file left on device - remove file first
123 bigip_ucs:
124 ucs: cs_backup.ucs
125 state: absent
126 provider:
127 server: lb.mydomain.com
128 user: admin
129 password: secret
130 delegate_to: localhost
131
132 - name: Recreate UCS file left on device - create new file
133 bigip_ucs_fetch:
134 src: cs_backup.ucs
135 only_create_file: true
136 provider:
137 server: lb.mydomain.com
138 user: admin
139 password: secret
140 delegate_to: localhost
141 '''
142
143 RETURN = r'''
144 checksum:
145 description: The SHA1 checksum of the downloaded file.
146 returned: success or changed
147 type: str
148 sample: 7b46bbe4f8ebfee64761b5313855618f64c64109
149 dest:
150 description: Location on the Ansible host the UCS was saved to.
151 returned: success
152 type: str
153 sample: /path/to/file.txt
154 src:
155 description:
156 - Name of the UCS file on the remote BIG-IP to download. If not
157 specified, this is a randomly generated filename.
158 returned: changed
159 type: str
160 sample: cs_backup.ucs
161 backup_file:
162 description: Name of the backup file.
163 returned: changed and if backup=yes
164 type: str
165 sample: /path/to/file.txt.2015-02-12@22:09~
166 gid:
167 description: Group ID of the UCS file, after execution.
168 returned: success
169 type: int
170 sample: 100
171 group:
172 description: Group of the UCS file, after execution.
173 returned: success
174 type: str
175 sample: httpd
176 owner:
177 description: Owner of the UCS file, after execution.
178 returned: success
179 type: str
180 sample: httpd
181 uid:
182 description: Owner ID of the UCS file, after execution.
183 returned: success
184 type: int
185 sample: 100
186 md5sum:
187 description: The MD5 checksum of the downloaded file.
188 returned: changed or success
189 type: str
190 sample: 96cacab4c259c4598727d7cf2ceb3b45
191 mode:
192 description: Permissions of the target UCS, after execution.
193 returned: success
194 type: str
195 sample: 0644
196 size:
197 description: Size of the target UCS, after execution.
198 returned: success
199 type: int
200 sample: 1220
201 '''
202
203 import os
204 import re
205 import tempfile
206 import time
207 import traceback
208 from datetime import datetime
209
210 try:
211 from packaging.version import Version
212 except ImportError:
213 HAS_PACKAGING = False
214 Version = None
215 PACKAGING_IMPORT_ERROR = traceback.format_exc()
216 else:
217 HAS_PACKAGING = True
218 PACKAGING_IMPORT_ERROR = None
219
220 from ansible.module_utils.basic import (
221 AnsibleModule, missing_required_lib
222 )
223
224 from ..module_utils.bigip import F5RestClient
225 from ..module_utils.common import (
226 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
227 )
228 from ..module_utils.icontrol import (
229 tmos_version, download_file
230 )
231 from ..module_utils.teem import send_teem
232
233
234 class Parameters(AnsibleF5Parameters):
235 updatables = []
236 returnables = [
237 'dest',
238 'src',
239 'md5sum',
240 'checksum',
241 'backup_file'
242 ]
243 api_attributes = []
244 api_map = {}
245
246
247 class ModuleParameters(Parameters):
248 @property
249 def options(self):
250 result = []
251 if self.passphrase:
252 result.append(dict(
253 passphrase=self.want.passphrase
254 ))
255 return result
256
257 @property
258 def src(self):
259 if self._values['src'] is not None:
260 return self._values['src']
261 result = next(tempfile._get_candidate_names()) + '.ucs'
262 self._values['src'] = result
263 return result
264
265 @property
266 def fulldest(self):
267 result = None
268 if os.path.isdir(self.dest):
269 result = os.path.join(self.dest, self.src)
270 else:
271 if os.path.exists(os.path.dirname(self.dest)):
272 result = self.dest
273 else:
274 try:
275 # os.path.exists() can return false in some
276 # circumstances where the directory does not have
277 # the execute bit for the current user set, in
278 # which case the stat() call will raise an OSError
279 os.stat(os.path.dirname(self.dest))
280 except OSError as e:
281 if "permission denied" in str(e).lower():
282 raise F5ModuleError(
283 "Destination directory {0} is not accessible".format(os.path.dirname(self.dest))
284 )
285 raise F5ModuleError(
286 "Destination directory {0} does not exist".format(os.path.dirname(self.dest))
287 )
288
289 if not os.access(os.path.dirname(result), os.W_OK):
290 raise F5ModuleError(
291 "Destination {0} not writable".format(os.path.dirname(result))
292 )
293 return result
294
295 @property
296 def async_timeout(self):
297 divisor = 100
298 timeout = self._values['async_timeout']
299 if timeout < 150 or timeout > 1800:
300 raise F5ModuleError(
301 "Timeout value must be between 150 and 1800 seconds."
302 )
303
304 delay = timeout / divisor
305
306 return delay, divisor
307
308
309 class Changes(Parameters):
310 def to_return(self):
311 result = {}
312 try:
313 for returnable in self.returnables:
314 result[returnable] = getattr(self, returnable)
315 result = self._filter_params(result)
316 except Exception:
317 raise
318 return result
319
320
321 class UsableChanges(Changes):
322 pass
323
324
325 class ReportableChanges(Changes):
326 pass
327
328
329 class ModuleManager(object):
330 def __init__(self, *args, **kwargs):
331 self.kwargs = kwargs
332 self.module = kwargs.get('module', None)
333 self.client = F5RestClient(**self.module.params)
334
335 def exec_module(self):
336 if self.is_version_v1():
337 manager = self.get_manager('v1')
338 else:
339 manager = self.get_manager('v2')
340 return manager.exec_module()
341
342 def get_manager(self, type):
343 if type == 'v1':
344 return V1Manager(**self.kwargs)
345 elif type == 'v2':
346 return V2Manager(**self.kwargs)
347
348 def is_version_v1(self):
349 """Checks to see if the TMOS version is less than 12.1.0
350
351 Versions prior to 12.1.0 have a bug which prevents the REST
352 API from properly listing any UCS files when you query the
353 /mgmt/tm/sys/ucs endpoint. Therefore you need to do everything
354 through tmsh over REST.
355
356 :return: bool
357 """
358 version = tmos_version(self.client)
359 if Version(version) < Version('12.1.0'):
360 return True
361 else:
362 return False
363
364
365 class BaseManager(object):
366 def __init__(self, *args, **kwargs):
367 self.module = kwargs.get('module', None)
368 self.client = F5RestClient(**self.module.params)
369 self.want = ModuleParameters(params=self.module.params)
370 self.changes = UsableChanges()
371
372 def exec_module(self):
373 start = datetime.now().isoformat()
374 version = tmos_version(self.client)
375 result = dict()
376
377 self.present()
378
379 reportable = ReportableChanges(params=self.changes.to_return())
380 changes = reportable.to_return()
381 result.update(**changes)
382 result.update(dict(changed=True))
383 send_teem(start, self.client, self.module, version)
384 return result
385
386 def present(self):
387 if self.exists():
388 if not self.want.only_create_file:
389 self.update()
390 else:
391 self.create()
392
393 def update(self):
394 if os.path.exists(self.want.fulldest):
395 if not self.want.force:
396 raise F5ModuleError(
397 "File '{0}' already exists".format(self.want.fulldest)
398 )
399 self.execute()
400
401 def _get_backup_file(self):
402 return self.module.backup_local(self.want.fulldest)
403
404 def execute(self):
405 try:
406 if self.want.backup:
407 if os.path.exists(self.want.fulldest):
408 backup_file = self._get_backup_file()
409 self.changes.update({'backup_file': backup_file})
410 self.download()
411 except IOError:
412 raise F5ModuleError(
413 "Failed to copy: {0} to {1}".format(self.want.src, self.want.fulldest)
414 )
415 self._set_checksum()
416 self._set_md5sum()
417 self.changes.update({'src': self.want.src})
418 self.changes.update({'md5sum': self.want.md5sum})
419 self.changes.update({'checksum': self.want.checksum})
420 file_args = self.module.load_file_common_arguments(self.module.params)
421 return self.module.set_fs_attributes_if_different(file_args, True)
422
423 def _set_checksum(self):
424 try:
425 result = self.module.sha1(self.want.fulldest)
426 self.want.update({'checksum': result})
427 except ValueError:
428 pass
429
430 def _set_md5sum(self):
431 try:
432 result = self.module.md5(self.want.fulldest)
433 self.want.update({'md5sum': result})
434 except ValueError:
435 pass
436
437 def create(self):
438 if self.want.fail_on_missing:
439 raise F5ModuleError(
440 "UCS '{0}' was not found".format(self.want.src)
441 )
442
443 if not self.want.create_on_missing:
444 raise F5ModuleError(
445 "UCS '{0}' was not found".format(self.want.src)
446 )
447
448 if self.module.check_mode:
449 return True
450 if self.want.create_on_missing:
451 self.create_on_device()
452 if not self.want.only_create_file:
453 self.execute()
454 return True
455
456 def create_on_device(self):
457 task = self.create_async_task_on_device()
458 self._start_task_on_device(task)
459 self.async_wait(task)
460
461 def create_async_task_on_device(self):
462 if self.want.encryption_password:
463 params = dict(
464 command='save',
465 name=self.want.src,
466 options=[{'passphrase': self.want.encryption_password}]
467 )
468 else:
469 params = dict(
470 command='save',
471 name=self.want.src,
472 )
473
474 uri = "https://{0}:{1}/mgmt/tm/task/sys/ucs".format(
475 self.client.provider['server'],
476 self.client.provider['server_port']
477 )
478 resp = self.client.api.post(uri, json=params)
479 try:
480 response = resp.json()
481 except ValueError as ex:
482 raise F5ModuleError(str(ex))
483
484 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
485 return response['_taskId']
486 raise F5ModuleError(resp.content)
487
488 def _start_task_on_device(self, task):
489 payload = {"_taskState": "VALIDATING"}
490 uri = "https://{0}:{1}/mgmt/tm/task/sys/ucs/{2}".format(
491 self.client.provider['server'],
492 self.client.provider['server_port'],
493 task
494 )
495 resp = self.client.api.put(uri, json=payload)
496 try:
497 response = resp.json()
498 except ValueError as ex:
499 raise F5ModuleError(str(ex))
500
501 if resp.status in [200, 201, 202] or 'code' in response and response['code'] in [200, 201, 202]:
502 return True
503 raise F5ModuleError(resp.content)
504
505 def async_wait(self, task):
506 delay, period = self.want.async_timeout
507 uri = "https://{0}:{1}/mgmt/tm/task/sys/ucs/{2}/result".format(
508 self.client.provider['server'],
509 self.client.provider['server_port'],
510 task
511 )
512 for x in range(0, period):
513 resp = self.client.api.get(uri)
514 try:
515 response = resp.json()
516 except ValueError:
517 # It is possible that the API call can return invalid JSON.
518 # This invalid JSON appears to be just empty strings.
519 continue
520 if resp.status in [200, 201, 202] or 'code' in response and response['code'] in [200, 201, 202]:
521 if response['_taskState'] == 'FAILED':
522 raise F5ModuleError("Task failed unexpectedly.")
523 if response['_taskState'] == 'COMPLETED':
524 return True
525
526 time.sleep(delay)
527 # at times we time out waiting on task as sometimes task is gone from async queue after services reboot
528 # we are adding existence check here to catch where the file is created but async task is removed.
529 if not self.exists():
530 raise F5ModuleError(
531 "Module timeout reached, state change is unknown, "
532 "please increase the async_timeout parameter for long lived actions."
533 )
534
535 def download(self):
536 self.download_from_device(self.want.dest)
537 if os.path.exists(self.want.dest):
538 return True
539 raise F5ModuleError(
540 "Failed to download the remote file"
541 )
542
543
544 class V1Manager(BaseManager):
545 def __init__(self, *args, **kwargs):
546 super(V1Manager, self).__init__(**kwargs)
547 self.remote_dir = '/var/config/rest/madm'
548
549 def read_current(self):
550 result = None
551 output = self.read_current_from_device()
552 if 'commandResult' in output:
553 result = self._read_ucs_files_from_output(output['commandResult'])
554 return result
555
556 def read_current_from_device(self):
557 params = dict(
558 command='run',
559 utilCmdArgs='-c "tmsh list sys ucs"'
560 )
561
562 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
563 self.client.provider['server'],
564 self.client.provider['server_port']
565 )
566
567 resp = self.client.api.post(uri, json=params)
568
569 try:
570 response = resp.json()
571 except ValueError as ex:
572 raise F5ModuleError(str(ex))
573 if 'code' in response and response['code'] in [400, 403]:
574 if 'message' in response:
575 raise F5ModuleError(response['message'])
576 else:
577 raise F5ModuleError(resp.content)
578 return response
579
580 def _read_ucs_files_from_output(self, output):
581 search = re.compile(r'filename\s+(.*)').search
582 lines = output.split("\n")
583 result = [m.group(1) for m in map(search, lines) if m]
584 return result
585
586 def exists(self):
587 collection = self.read_current()
588 base = os.path.basename(self.want.src)
589 if any(base == os.path.basename(x) for x in collection):
590 return True
591 return False
592
593 def download_from_device(self, dest):
594 url = 'https://{0}:{1}/mgmt/shared/file-transfer/madm/{2}'.format(
595 self.client.provider['server'],
596 self.client.provider['server_port'],
597 self.want.filename
598 )
599 try:
600 download_file(self.client, url, dest)
601 except F5ModuleError:
602 raise F5ModuleError(
603 "Failed to download the file."
604 )
605 if os.path.exists(self.want.dest):
606 return True
607 return False
608
609 def _move_to_download(self):
610 move_path = '/var/local/ucs/{0} {1}/{0}'.format(
611 self.want.filename, self.remote_dir
612 )
613 params = dict(
614 command='run',
615 utilCmdArgs=move_path
616 )
617
618 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
619 self.client.provider['server'],
620 self.client.provider['server_port']
621 )
622
623 resp = self.client.api.post(uri, json=params)
624
625 try:
626 response = resp.json()
627 if 'commandResult' in response:
628 if 'cannot stat' in response['commandResult']:
629 raise F5ModuleError(response['commandResult'])
630 except ValueError as ex:
631 raise F5ModuleError(str(ex))
632
633 if 'code' in response and response['code'] in [400, 403]:
634 if 'message' in response:
635 raise F5ModuleError(response['message'])
636 else:
637 raise F5ModuleError(resp.content)
638
639 return True
640
641
642 class V2Manager(BaseManager):
643 def read_current_from_device(self):
644 uri = "https://{0}:{1}/mgmt/tm/sys/ucs".format(
645 self.client.provider['server'],
646 self.client.provider['server_port'],
647 )
648 resp = self.client.api.get(uri)
649
650 try:
651 response = resp.json()
652 except ValueError as ex:
653 raise F5ModuleError(str(ex))
654
655 if 'code' in response and response['code'] == 400:
656 if 'message' in response:
657 raise F5ModuleError(response['message'])
658 else:
659 raise F5ModuleError(resp.content)
660
661 return response
662
663 def read_current(self):
664 collection = self.read_current_from_device()
665 if 'items' not in collection:
666 return []
667 resources = collection['items']
668 result = [x['apiRawValues']['filename'] for x in resources]
669 return result
670
671 def exists(self):
672 collection = self.read_current()
673 base = os.path.basename(self.want.src)
674 if any(base == os.path.basename(x) for x in collection):
675 return True
676 return False
677
678 def download_from_device(self, dest):
679 url = 'https://{0}:{1}/mgmt/shared/file-transfer/ucs-downloads/{2}'.format(
680 self.client.provider['server'],
681 self.client.provider['server_port'],
682 self.want.src
683 )
684 try:
685 download_file(self.client, url, dest)
686 except F5ModuleError:
687 raise F5ModuleError(
688 "Failed to download the file."
689 )
690 if os.path.exists(self.want.dest):
691 return True
692 return False
693
694
695 class ArgumentSpec(object):
696 def __init__(self):
697 self.supports_check_mode = True
698 argument_spec = dict(
699 backup=dict(
700 default='no',
701 type='bool'
702 ),
703 create_on_missing=dict(
704 default='yes',
705 type='bool'
706 ),
707 encryption_password=dict(no_log=True),
708 dest=dict(
709 type='path'
710 ),
711 force=dict(
712 default='yes',
713 type='bool'
714 ),
715 fail_on_missing=dict(
716 default='no',
717 type='bool'
718 ),
719 src=dict(),
720 only_create_file=dict(
721 default='no',
722 type='bool'
723 ),
724 async_timeout=dict(
725 type='int',
726 default=150
727 ),
728 )
729 self.required_if = [
730 ['only_create_file', 'no', ['dest']],
731 ['only_create_file', 'yes', ['src']]
732 ]
733 self.argument_spec = {}
734 self.argument_spec.update(f5_argument_spec)
735 self.argument_spec.update(argument_spec)
736 self.add_file_common_args = True
737
738
739 def main():
740 spec = ArgumentSpec()
741
742 module = AnsibleModule(
743 argument_spec=spec.argument_spec,
744 supports_check_mode=spec.supports_check_mode,
745 required_if=spec.required_if,
746 add_file_common_args=spec.add_file_common_args
747 )
748
749 if not HAS_PACKAGING:
750 module.fail_json(
751 msg=missing_required_lib('packaging'),
752 exception=PACKAGING_IMPORT_ERROR
753 )
754
755 try:
756 mm = ModuleManager(module=module)
757 results = mm.exec_module()
758 module.exit_json(**results)
759 except F5ModuleError as ex:
760 module.fail_json(msg=str(ex))
761
762
763 if __name__ == '__main__':
764 main()