Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_provision.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_provision
13 short_description: Manage BIG-IP module provisioning
14 description:
15 - Manage BIG-IP module provisioning. This module will only provision at the
16 standard levels of Dedicated, Nominal, and Minimum.
17 version_added: "1.0.0"
18 options:
19 module:
20 description:
21 - The module to provision in BIG-IP.
22 type: str
23 required: True
24 choices:
25 - am
26 - afm
27 - apm
28 - asm
29 - avr
30 - cgnat
31 - fps
32 - gtm
33 - ilx
34 - lc
35 - ltm
36 - mgmt
37 - pem
38 - sam
39 - sslo
40 - swg
41 - urldb
42 - vcmp
43 aliases:
44 - name
45 level:
46 description:
47 - Sets the provisioning level for the requested modules. Changing the
48 level for one module may require modifying the level of another module.
49 For example, changing one module to C(dedicated) requires setting all
50 others to C(none). Setting the level of a module to C(none) means
51 the module is not activated.
52 - Use a C(state) of B(absent) to set c(level) to none and de-provision the module.
53 - This parameter is not relevant to C(cgnat - pre tmos 15.0) or C(mgmt) and will not be
54 applied to the C(cgnat - pre tmos 15.0) or C(mgmt) module.
55 type: str
56 choices:
57 - dedicated
58 - nominal
59 - minimum
60 default: nominal
61 memory:
62 description:
63 - Sets additional memory for the management module. This is in addition to
64 minimum allocated RAM of 1264MB.
65 - The accepted value range is C(0 - 8192). Maximum value is restricted by
66 the available RAM in the system.
67 - Specifying C(large) reserves an additional 500MB for the mgmt module.
68 - Specifying C(medium) reserves an additional 200MB for the mgmt module.
69 - Specifying C(small) reserves no additional RAM for the mgmt module.
70 - Use C(large) for configurations containing more than 2000 objects, or
71 more specifically, for any configuration that exceeds 1000 objects
72 per 2 GB of installed memory. Changing the Management C(mgmt) size
73 after initial provisioning causes a reprovision operation.
74 type: str
75 state:
76 description:
77 - The state of the provisioned module on the system. When C(present),
78 guarantees the specified module is provisioned at the requested
79 level, provided there are sufficient resources on the device (such
80 as physical RAM) to support the module.
81 - When C(absent), de-provision the module.
82 - C(absent), is not a relevent option for the C(mgmt) module, as it can not be de-provisioned.
83 type: str
84 choices:
85 - present
86 - absent
87 default: present
88 extends_documentation_fragment: f5networks.f5_modules.f5
89 author:
90 - Tim Rupp (@caphrim007)
91 - Greg Crosby (@crosbygw)
92 '''
93
94 EXAMPLES = r'''
95 - name: Provision PEM at "nominal" level
96 bigip_provision:
97 module: pem
98 level: nominal
99 provider:
100 server: lb.mydomain.com
101 password: secret
102 user: admin
103 delegate_to: localhost
104
105 - name: Provision a dedicated SWG. This will unprovision every other module
106 bigip_provision:
107 module: swg
108 level: dedicated
109 provider:
110 server: lb.mydomain.com
111 password: secret
112 user: admin
113 delegate_to: localhost
114
115 - name: Provision mgmt with medium amount of memory.
116 bigip_provision:
117 module: mgmt
118 memory: medium
119 provider:
120 server: lb.mydomain.com
121 password: secret
122 user: admin
123 delegate_to: localhost
124 '''
125
126 RETURN = r'''
127 level:
128 description: The new provisioning level of the module.
129 returned: changed
130 type: str
131 sample: minimum
132 memory:
133 description: The new provisioned amount of memory for mgmt module.
134 returned: changed
135 type: str
136 sample: large
137 '''
138
139 import time
140 import traceback
141 from datetime import datetime
142
143 try:
144 from packaging.version import Version
145 except ImportError:
146 HAS_PACKAGING = False
147 Version = None
148 PACKAGING_IMPORT_ERROR = traceback.format_exc()
149 else:
150 HAS_PACKAGING = True
151 PACKAGING_IMPORT_ERROR = None
152
153 from ansible.module_utils.basic import (
154 AnsibleModule, missing_required_lib
155 )
156
157 from ..module_utils.bigip import F5RestClient
158 from ..module_utils.common import (
159 F5ModuleError, AnsibleF5Parameters, f5_argument_spec,
160 )
161 from ..module_utils.icontrol import (
162 TransactionContextManager, tmos_version
163 )
164 from ..module_utils.teem import send_teem
165
166
167 class Parameters(AnsibleF5Parameters):
168 api_map = {
169 'value': 'memory',
170 }
171
172 api_attributes = [
173 'level',
174 'value',
175 ]
176
177 returnables = [
178 'level',
179 'memory',
180 ]
181
182 updatables = [
183 'level',
184 'cgnat',
185 'memory',
186 ]
187
188
189 class ApiParameters(Parameters):
190 pass
191
192
193 class ModuleParameters(Parameters):
194
195 def _validate_memory_limit(self, limit):
196 if self._values['memory'] == 'small':
197 return '0'
198 if self._values['memory'] == 'medium':
199 return '200'
200 if self._values['memory'] == 'large':
201 return '500'
202 if 0 <= int(limit) <= 8192:
203 return str(limit)
204 raise F5ModuleError(
205 "Valid 'memory' must be in range 0 - 8192, 'small', 'medium', or 'large'."
206 )
207
208 @property
209 def level(self):
210 if self._values['level'] is None:
211 return None
212 if self._values['module'] == 'mgmt':
213 return None
214 if self.state == 'absent':
215 return 'none'
216 return str(self._values['level'])
217
218 @property
219 def memory(self):
220 if self._values['memory'] is None:
221 return None
222 if self._values['module'] != 'mgmt':
223 return None
224 return int(self._validate_memory_limit(self._values['memory']))
225
226
227 class Changes(Parameters):
228 def to_return(self):
229 result = {}
230 try:
231 for returnable in self.returnables:
232 result[returnable] = getattr(self, returnable)
233 result = self._filter_params(result)
234 return result
235 except Exception:
236 return result
237
238
239 class UsableChanges(Changes):
240 pass
241
242
243 class ReportableChanges(Changes):
244 @property
245 def memory(self):
246 if self._values['memory'] is None:
247 return None
248 if self._values['memory'] == '0':
249 return 'small'
250 if self._values['memory'] == '200':
251 return 'medium'
252 if self._values['memory'] == '500':
253 return 'large'
254 return str(self._values['memory'])
255
256
257 class Difference(object):
258 def __init__(self, want, have=None):
259 self.want = want
260 self.have = have
261
262 def compare(self, param):
263 try:
264 result = getattr(self, param)
265 return result
266 except AttributeError:
267 result = self.__default(param)
268 return result
269
270 def __default(self, param):
271 attr1 = getattr(self.want, param)
272 try:
273 attr2 = getattr(self.have, param)
274 if attr1 != attr2:
275 return attr1
276 except AttributeError:
277 return attr1
278
279 @property
280 def cgnat(self):
281 if self.want.module == 'cgnat':
282 if self.want.state == 'absent' and self.have.enabled is True:
283 return True
284 if self.want.state == 'present' and self.have.disabled is True:
285 return True
286
287
288 class ModuleManager(object):
289 def __init__(self, *args, **kwargs):
290 self.module = kwargs.get('module', None)
291 self.client = F5RestClient(**self.module.params)
292 self.have = None
293 self.want = ModuleParameters(params=self.module.params)
294 self.changes = UsableChanges()
295
296 def _update_changed_options(self):
297 diff = Difference(self.want, self.have)
298 updatables = Parameters.updatables
299 changed = dict()
300 for k in updatables:
301 change = diff.compare(k)
302 if change is None:
303 continue
304 else:
305 if isinstance(change, dict):
306 changed.update(change)
307 else:
308 changed[k] = change
309 if changed:
310 self.changes = UsableChanges(params=changed)
311 return True
312 return False
313
314 def exec_module(self):
315 start = datetime.now().isoformat()
316 version = tmos_version(self.client)
317 changed = False
318 result = dict()
319 state = self.want.state
320
321 if state == "present":
322 changed = self.present()
323 elif state == "absent":
324 changed = self.absent()
325 reportable = ReportableChanges(params=self.changes.to_return())
326 changes = reportable.to_return()
327 result.update(**changes)
328 result.update(dict(changed=changed))
329 send_teem(start, self.client, self.module, version)
330 return result
331
332 def version_is_greater_or_equal_15(self):
333 version = tmos_version(self.client)
334 if Version(version) >= Version('15.0.0'):
335 return True
336 else:
337 return False
338
339 def present(self):
340 if self.exists():
341 return False
342 return self.update()
343
344 def exists(self):
345 if self.want.module == 'cgnat' and not self.version_is_greater_or_equal_15():
346 uri = "https://{0}:{1}/mgmt/tm/sys/feature-module/cgnat/".format(
347 self.client.provider['server'],
348 self.client.provider['server_port'],
349 )
350 resp = self.client.api.get(uri)
351 try:
352 response = resp.json()
353 except ValueError as ex:
354 raise F5ModuleError(str(ex))
355
356 if 'code' in response and response['code'] in [400, 404]:
357 if 'message' in response:
358 raise F5ModuleError(response['message'])
359 else:
360 raise F5ModuleError(resp.content)
361 if 'disabled' in response and response['disabled'] is True:
362 return False
363 elif 'enabled' in response and response['enabled'] is True:
364 return True
365 elif self.want.module == 'mgmt':
366 uri = "https://{0}:{1}/mgmt/tm/sys/db/provision.extramb/".format(
367 self.client.provider['server'],
368 self.client.provider['server_port'],
369 )
370 resp = self.client.api.get(uri)
371 try:
372 response = resp.json()
373 except ValueError:
374 return False
375 if resp.status == 404 or 'code' in response and response['code'] == 404:
376 return False
377 if str(response['value']) != 0 and self.want.memory == 0:
378 return False
379 if str(response['value']) == 0 and self.want.memory == 0:
380 return True
381 if str(response['value']) == self.want.memory:
382 return True
383 return False
384 try:
385 for x in range(0, 5):
386 uri = "https://{0}:{1}/mgmt/tm/sys/provision/{2}".format(
387 self.client.provider['server'],
388 self.client.provider['server_port'],
389 self.want.module
390 )
391 resp = self.client.api.get(uri)
392 try:
393 response = resp.json()
394 except ValueError as ex:
395 raise F5ModuleError(str(ex))
396
397 if 'code' in response and response['code'] in [400, 404]:
398 if 'message' in response:
399 raise F5ModuleError(response['message'])
400 else:
401 raise F5ModuleError(resp.content)
402
403 if str(response['level']) != 'none' and self.want.level == 'none':
404 return True
405 if str(response['level']) == 'none' and self.want.level == 'none':
406 return False
407 if str(response['level']) == self.want.level:
408 return True
409 return False
410 except Exception as ex:
411 if 'not registered' in str(ex):
412 return False
413 time.sleep(1)
414
415 def update(self):
416 self.have = self.read_current_from_device()
417 if not self.should_update():
418 return False
419 if self.module.check_mode:
420 return True
421 result = self.update_on_device()
422 if self.want.module == 'cgnat' and not self.version_is_greater_or_equal_15():
423 return result
424 self._wait_for_module_provisioning()
425 self._wait_for_rest_api_available()
426
427 if self.want.module == 'vcmp':
428 self._wait_for_reboot()
429 self._wait_for_module_provisioning()
430 self._wait_for_rest_api_available()
431
432 if self.want.module == 'asm':
433 self._wait_for_asm_ready()
434 if self.want.module == 'afm':
435 self._wait_for_afm_ready()
436 if self.want.module == 'cgnat':
437 self._wait_for_cgnat_ready()
438 if self.want.module == 'mgmt':
439 self._wait_for_mgmt_ready()
440 return True
441
442 def should_reboot(self):
443 for x in range(0, 24):
444 try:
445 uri = "https://{0}:{1}/mgmt/tm/sys/db/{2}".format(
446 self.client.provider['server'],
447 self.client.provider['server_port'],
448 'provision.action'
449 )
450 resp = self.client.api.get(uri)
451 try:
452 response = resp.json()
453 except ValueError as ex:
454 raise F5ModuleError(str(ex))
455
456 if 'code' in response and response['code'] in [400, 404]:
457 if 'message' in response:
458 raise F5ModuleError(response['message'])
459 else:
460 raise F5ModuleError(resp.content)
461
462 if response['value'] == 'reboot':
463 return True
464 elif response['value'] == 'none':
465 time.sleep(5)
466 except Exception:
467 time.sleep(5)
468 return False
469
470 def reboot_device(self):
471 nops = 0
472 last_reboot = self._get_last_reboot()
473
474 try:
475 params = dict(
476 command="run",
477 utilCmdArgs='-c "/sbin/reboot"'
478 )
479 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
480 self.client.provider['server'],
481 self.client.provider['server_port']
482 )
483 resp = self.client.api.post(uri, json=params)
484
485 try:
486 response = resp.json()
487 except ValueError as ex:
488 raise F5ModuleError(str(ex))
489
490 if 'code' in response and response['code'] in [400, 403]:
491 if 'message' in response:
492 raise F5ModuleError(response['message'])
493 else:
494 raise F5ModuleError(resp.content)
495 if 'commandResult' in response:
496 return str(response['commandResult'])
497 except Exception:
498 pass
499
500 # Sleep a little to let rebooting take effect
501 time.sleep(20)
502
503 while nops < 3:
504 try:
505 self.client.reconnect()
506 next_reboot = self._get_last_reboot()
507 if next_reboot is None:
508 nops = 0
509 if next_reboot == last_reboot:
510 nops = 0
511 else:
512 nops += 1
513 except Exception:
514 # This can be caused by restjavad restarting.
515 pass
516 time.sleep(10)
517 return None
518
519 def should_update(self):
520 result = self._update_changed_options()
521 if result:
522 return True
523 return False
524
525 def update_on_device(self):
526 if self.want.module == 'cgnat' and not self.version_is_greater_or_equal_15():
527 if self.changes.cgnat:
528 return self.provision_cgnat_on_device()
529 return False
530 elif self.want.level == 'dedicated' and self.want.module != 'mgmt':
531 self.provision_dedicated_on_device()
532 else:
533 self.provision_non_dedicated_on_device()
534
535 def provision_cgnat_on_device(self):
536 uri = "https://{0}:{1}/mgmt/tm/sys/feature-module/cgnat/".format(
537 self.client.provider['server'],
538 self.client.provider['server_port'],
539 )
540 params = dict(enabled=True)
541 resp = self.client.api.patch(uri, json=params)
542 try:
543 response = resp.json()
544 except ValueError as ex:
545 raise F5ModuleError(str(ex))
546
547 if 'code' in response and response['code'] in [400, 404]:
548 if 'message' in response:
549 raise F5ModuleError(response['message'])
550 else:
551 raise F5ModuleError(resp.content)
552 return True
553
554 def provision_dedicated_on_device(self):
555 params = self.want.api_params()
556 uri = "https://{0}:{1}/mgmt/tm/sys/provision/".format(
557 self.client.provider['server'],
558 self.client.provider['server_port'],
559 )
560 resp = self.client.api.get(uri)
561 try:
562 response = resp.json()
563 except ValueError as ex:
564 raise F5ModuleError(str(ex))
565
566 if 'code' in response and response['code'] in [400, 404]:
567 if 'message' in response:
568 raise F5ModuleError(response['message'])
569 else:
570 raise F5ModuleError(resp.content)
571
572 resources = [x['name'] for x in response['items'] if x['name'] != self.want.module]
573
574 with TransactionContextManager(self.client) as transact:
575 for resource in resources:
576 target = uri + resource
577 resp = transact.api.patch(target, json=dict(level='none'))
578 try:
579 response = resp.json()
580 except ValueError as ex:
581 raise F5ModuleError(str(ex))
582
583 if 'code' in response and response['code'] in [400, 404]:
584 if 'message' in response:
585 raise F5ModuleError(response['message'])
586 else:
587 raise F5ModuleError(resp.content)
588
589 target = uri + self.want.module
590 resp = transact.api.patch(target, json=params)
591 try:
592 response = resp.json()
593 except ValueError as ex:
594 raise F5ModuleError(str(ex))
595
596 if 'code' in response and response['code'] in [400, 404]:
597 if 'message' in response:
598 raise F5ModuleError(response['message'])
599 else:
600 raise F5ModuleError(resp.content)
601
602 def provision_non_dedicated_on_device(self):
603 params = self.want.api_params()
604 if self.want.module == 'mgmt':
605 uri = "https://{0}:{1}/mgmt/tm/sys/db/provision.extramb/".format(
606 self.client.provider['server'],
607 self.client.provider['server_port'],
608 )
609 else:
610 uri = "https://{0}:{1}/mgmt/tm/sys/provision/{2}".format(
611 self.client.provider['server'],
612 self.client.provider['server_port'],
613 self.want.module
614 )
615 resp = self.client.api.patch(uri, json=params)
616 try:
617 response = resp.json()
618 except ValueError as ex:
619 raise F5ModuleError(str(ex))
620
621 if 'code' in response and response['code'] in [400, 404]:
622 if 'message' in response:
623 raise F5ModuleError(response['message'])
624 else:
625 raise F5ModuleError(resp.content)
626
627 def read_current_from_device(self):
628 if self.want.module == 'cgnat' and not self.version_is_greater_or_equal_15():
629 uri = "https://{0}:{1}/mgmt/tm/sys/feature-module/cgnat/".format(
630 self.client.provider['server'],
631 self.client.provider['server_port'],
632 )
633 resp = self.client.api.get(uri)
634 try:
635 response = resp.json()
636 except ValueError as ex:
637 raise F5ModuleError(str(ex))
638
639 if 'code' in response and response['code'] in [400, 404]:
640 if 'message' in response:
641 raise F5ModuleError(response['message'])
642 else:
643 raise F5ModuleError(resp.content)
644 elif self.want.module == 'mgmt':
645 uri = "https://{0}:{1}/mgmt/tm/sys/db/provision.extramb/".format(
646 self.client.provider['server'],
647 self.client.provider['server_port'],
648 )
649 resp = self.client.api.get(uri)
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'] in [400, 404]:
656 if 'message' in response:
657 raise F5ModuleError(response['message'])
658 else:
659 raise F5ModuleError(resp.content)
660 else:
661 uri = "https://{0}:{1}/mgmt/tm/sys/provision/{2}".format(
662 self.client.provider['server'],
663 self.client.provider['server_port'],
664 self.want.module
665 )
666 resp = self.client.api.get(uri)
667 try:
668 response = resp.json()
669 except ValueError as ex:
670 raise F5ModuleError(str(ex))
671
672 if 'code' in response and response['code'] in [400, 404]:
673 if 'message' in response:
674 raise F5ModuleError(response['message'])
675 else:
676 raise F5ModuleError(resp.content)
677 return ApiParameters(params=response)
678
679 def absent(self):
680 if self.exists():
681 return self.remove()
682 return False
683
684 def remove(self):
685 if self.module.check_mode:
686 return True
687 if self.want.module == 'cgnat' and not self.version_is_greater_or_equal_15():
688 return self.deprovision_cgnat_on_device()
689
690 self.remove_from_device()
691 self._wait_for_module_provisioning()
692 self._wait_for_rest_api_available()
693 # For vCMP, because it has to reboot, we also wait for mcpd to become available
694 # before "moving on", or else the REST API would not be available and subsequent
695 # Tasks would fail.
696 if self.want.module == 'vcmp':
697 self._wait_for_reboot()
698 self._wait_for_module_provisioning()
699 self._wait_for_rest_api_available()
700
701 if self.should_reboot():
702 self.save_on_device()
703 self.reboot_device()
704 self._wait_for_module_provisioning()
705 self._wait_for_rest_api_available()
706
707 if self.exists():
708 raise F5ModuleError("Failed to de-provision the module")
709 return True
710
711 def save_on_device(self):
712 command = 'tmsh save sys config'
713 params = dict(
714 command="run",
715 utilCmdArgs='-c "{0}"'.format(command)
716 )
717 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
718 self.client.provider['server'],
719 self.client.provider['server_port']
720 )
721 resp = self.client.api.post(uri, json=params)
722
723 try:
724 response = resp.json()
725 except ValueError as ex:
726 raise F5ModuleError(str(ex))
727 if 'code' in response and response['code'] in [400, 403]:
728 if 'message' in response:
729 raise F5ModuleError(response['message'])
730 else:
731 raise F5ModuleError(resp.content)
732
733 def remove_from_device(self):
734 uri = "https://{0}:{1}/mgmt/tm/sys/provision/{2}".format(
735 self.client.provider['server'],
736 self.client.provider['server_port'],
737 self.want.module
738 )
739 resp = self.client.api.patch(uri, json=dict(level='none'))
740 try:
741 response = resp.json()
742 except ValueError as ex:
743 raise F5ModuleError(str(ex))
744 if 'code' in response and response['code'] == 400:
745 if 'message' in response:
746 raise F5ModuleError(response['message'])
747 else:
748 raise F5ModuleError(resp.content)
749
750 def deprovision_cgnat_on_device(self):
751 uri = "https://{0}:{1}/mgmt/tm/sys/feature-module/cgnat/".format(
752 self.client.provider['server'],
753 self.client.provider['server_port'],
754 )
755 params = dict(disabled=True)
756 resp = self.client.api.patch(uri, json=params)
757 try:
758 response = resp.json()
759 except ValueError as ex:
760 raise F5ModuleError(str(ex))
761
762 if 'code' in response and response['code'] == 400:
763 if 'message' in response:
764 raise F5ModuleError(response['message'])
765 else:
766 raise F5ModuleError(resp.content)
767 return True
768
769 def _wait_for_module_provisioning(self):
770 # To prevent things from running forever, the hack is to check
771 # for mprov's status twice. If mprov is finished, then in most
772 # cases (not ASM) the provisioning is probably ready.
773 nops = 0
774
775 # Sleep a little to let provisioning settle and begin properly
776 time.sleep(5)
777
778 while nops < 3:
779 try:
780 if not self._is_mprov_running_on_device():
781 nops += 1
782 else:
783 nops = 0
784 except Exception:
785 # This can be caused by restjavad restarting.
786 try:
787 self.client.reconnect()
788 except Exception:
789 pass
790 time.sleep(5)
791
792 def _is_mprov_running_on_device(self):
793 # /usr/libexec/qemu-kvm is added here to prevent vcmp provisioning
794 # from never allowing the mprov provisioning to succeed.
795 #
796 # It turns out that the 'mprov' string is found when enabling vcmp. The
797 # qemu-kvm command that is run includes it.
798 #
799 # For example,
800 # /usr/libexec/qemu-kvm -rt-usecs 880 ... -mem-path /dev/mprov/vcmp -f5-tracing ...
801 #
802 try:
803 command = "ps aux | grep \'[m]prov\' | grep -v /usr/libexec/qemu-kvm"
804 params = dict(
805 command="run",
806 utilCmdArgs='-c "{0}"'.format(command)
807 )
808 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
809 self.client.provider['server'],
810 self.client.provider['server_port']
811 )
812 resp = self.client.api.post(uri, json=params)
813
814 try:
815 response = resp.json()
816 except ValueError as ex:
817 raise F5ModuleError(str(ex))
818
819 if 'code' in response and response['code'] in [400, 403]:
820 if 'message' in response:
821 raise F5ModuleError(response['message'])
822 else:
823 raise F5ModuleError(resp.content)
824
825 if 'commandResult' in response:
826 return True
827 except Exception:
828 pass
829 return False
830
831 def _wait_for_rest_api_available(self):
832 nops = 0
833 time.sleep(5)
834
835 while nops < 3:
836 try:
837 if self._is_rest_available():
838 nops += 1
839 else:
840 nops = 0
841 time.sleep(5)
842 except Exception:
843 # This can be caused by restjavad restarting.
844 try:
845 self.client.reconnect()
846 except Exception:
847 pass
848
849 def _is_rest_available(self):
850 try:
851 uri = "https://{0}:{1}/mgmt/tm/sys/available".format(
852 self.client.provider['server'],
853 self.client.provider['server_port']
854 )
855 resp = self.client.api.get(uri)
856
857 try:
858 response = resp.json()
859 except ValueError as ex:
860 raise F5ModuleError(str(ex))
861
862 if 'code' in response and response['code'] in [400, 403, 404]:
863 if 'message' in response:
864 raise F5ModuleError(response['message'])
865 else:
866 raise F5ModuleError(resp.content)
867
868 if resp.status in [200, 201]:
869 return True
870 except Exception:
871 pass
872 return False
873
874 def _wait_for_asm_ready(self):
875 """Waits specifically for ASM
876
877 On older versions, ASM can take longer to actually start up than
878 all the previous checks take. This check here is specifically waiting for
879 the Policies API to stop raising errors
880 :return:
881 """
882 nops = 0
883 restarted_asm = False
884 while nops < 3:
885 try:
886 uri = "https://{0}:{1}/mgmt/tm/asm/policies/".format(
887 self.client.provider['server'],
888 self.client.provider['server_port'],
889 )
890 resp = self.client.api.get(uri)
891
892 try:
893 response = resp.json()
894 except ValueError as ex:
895 raise F5ModuleError(str(ex))
896
897 if 'code' in response and response['code'] in [400, 403]:
898 if 'message' in response:
899 raise F5ModuleError(response['message'])
900 else:
901 raise F5ModuleError(resp.content)
902
903 if len(response['items']) >= 0:
904 nops += 1
905 else:
906 nops = 0
907 except Exception:
908 if not restarted_asm:
909 self._restart_asm()
910 restarted_asm = True
911 time.sleep(5)
912
913 def _wait_for_afm_ready(self):
914 """Waits specifically for AFM
915
916 AFM can take longer to actually start up than all the previous checks take.
917 This check here is specifically waiting for the Security API to stop raising
918 errors.
919 :return:
920 """
921 nops = 0
922 while nops < 3:
923 try:
924 uri = "https://{0}:{1}/mgmt/tm/security/".format(
925 self.client.provider['server'],
926 self.client.provider['server_port'],
927 )
928 resp = self.client.api.get(uri)
929
930 try:
931 response = resp.json()
932 except ValueError as ex:
933 raise F5ModuleError(str(ex))
934
935 if 'code' in response and response['code'] in [400, 403]:
936 if 'message' in response:
937 raise F5ModuleError(response['message'])
938 else:
939 raise F5ModuleError(resp.content)
940
941 if len(response['items']) >= 0:
942 nops += 1
943 else:
944 nops = 0
945 except Exception:
946 pass
947 time.sleep(5)
948
949 def _wait_for_cgnat_ready(self):
950 """Waits specifically for CGNAT
951
952 Starting in TMOS 15.0 cgnat can take longer to actually start up than all the previous checks take.
953 This check here is specifically waiting for a cgnat API to stop raising
954 errors.
955 :return:
956 """
957 nops = 0
958 while nops < 3:
959 try:
960 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool".format(
961 self.client.provider['server'],
962 self.client.provider['server_port'],
963 )
964 resp = self.client.api.get(uri)
965
966 try:
967 response = resp.json()
968 except ValueError as ex:
969 raise F5ModuleError(str(ex))
970
971 if 'code' in response and response['code'] in [400, 403]:
972 if 'message' in response:
973 raise F5ModuleError(response['message'])
974 else:
975 raise F5ModuleError(resp.content)
976
977 if len(response['items']) >= 0:
978 nops += 1
979 else:
980 nops = 0
981 except Exception:
982 pass
983 time.sleep(5)
984
985 def _wait_for_mgmt_ready(self):
986 """Waits specifically for MGMT
987
988 Modifying memory reserve for mgmt can take longer to actually start up than all the previous checks take.
989 This check here is specifically waiting for a MGMT API to stop raising
990 errors.
991 :return:
992 """
993 nops = 0
994 while nops < 3:
995 try:
996 uri = "https://{0}:{1}/mgmt/tm".format(
997 self.client.provider['server'],
998 self.client.provider['server_port'],
999 )
1000 resp = self.client.api.get(uri)
1001
1002 try:
1003 response = resp.json()
1004 except ValueError as ex:
1005 raise F5ModuleError(str(ex))
1006
1007 if 'code' in response and response['code'] in [400, 403]:
1008 if 'message' in response:
1009 raise F5ModuleError(response['message'])
1010 else:
1011 raise F5ModuleError(resp.content)
1012
1013 if len(response['items']) >= 0:
1014 nops += 1
1015 else:
1016 nops = 0
1017 except Exception:
1018 pass
1019 time.sleep(5)
1020
1021 def _restart_asm(self):
1022 try:
1023 params = dict(
1024 command="run",
1025 utilCmdArgs='-c "bigstart restart asm"'
1026 )
1027 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
1028 self.client.provider['server'],
1029 self.client.provider['server_port']
1030 )
1031 resp = self.client.api.post(uri, json=params)
1032
1033 try:
1034 response = resp.json()
1035 except ValueError as ex:
1036 raise F5ModuleError(str(ex))
1037
1038 if 'code' in response and response['code'] in [400, 403]:
1039 if 'message' in response:
1040 raise F5ModuleError(response['message'])
1041 else:
1042 raise F5ModuleError(resp.content)
1043 time.sleep(60)
1044 return True
1045 except Exception:
1046 pass
1047 return None
1048
1049 def _get_last_reboot(self):
1050 try:
1051 params = dict(
1052 command="run",
1053 utilCmdArgs='-c "/usr/bin/last reboot | head -1"'
1054 )
1055 uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
1056 self.client.provider['server'],
1057 self.client.provider['server_port']
1058 )
1059 resp = self.client.api.post(uri, json=params)
1060
1061 try:
1062 response = resp.json()
1063 except ValueError as ex:
1064 raise F5ModuleError(str(ex))
1065
1066 if 'code' in response and response['code'] in [400, 403]:
1067 if 'message' in response:
1068 raise F5ModuleError(response['message'])
1069 else:
1070 raise F5ModuleError(resp.content)
1071
1072 if 'commandResult' in response:
1073 return str(response['commandResult'])
1074 except Exception:
1075 pass
1076 return None
1077
1078 def _wait_for_reboot(self):
1079 nops = 0
1080
1081 last_reboot = self._get_last_reboot()
1082
1083 # Sleep a little to let provisioning settle and begin properly
1084 time.sleep(5)
1085
1086 while nops < 6:
1087 try:
1088 self.client.reconnect()
1089 next_reboot = self._get_last_reboot()
1090 if next_reboot is None:
1091 nops = 0
1092 if next_reboot == last_reboot:
1093 nops = 0
1094 else:
1095 nops += 1
1096 except Exception:
1097 # This can be caused by restjavad restarting.
1098 pass
1099 time.sleep(10)
1100
1101
1102 class ArgumentSpec(object):
1103 def __init__(self):
1104 self.supports_check_mode = True
1105 argument_spec = dict(
1106 module=dict(
1107 required=True,
1108 choices=[
1109 'afm', 'am', 'apm', 'asm', 'avr', 'cgnat',
1110 'fps', 'gtm', 'ilx', 'lc', 'ltm', 'mgmt',
1111 'pem', 'sam', 'sslo', 'swg', 'urldb', 'vcmp'
1112 ],
1113 aliases=['name']
1114 ),
1115 level=dict(
1116 default='nominal',
1117 choices=['nominal', 'dedicated', 'minimum']
1118 ),
1119 memory=dict(),
1120 state=dict(
1121 default='present',
1122 choices=['present', 'absent']
1123 )
1124 )
1125 self.argument_spec = {}
1126 self.argument_spec.update(f5_argument_spec)
1127 self.argument_spec.update(argument_spec)
1128
1129
1130 def main():
1131 spec = ArgumentSpec()
1132
1133 module = AnsibleModule(
1134 argument_spec=spec.argument_spec,
1135 supports_check_mode=spec.supports_check_mode,
1136
1137 )
1138
1139 if not HAS_PACKAGING:
1140 module.fail_json(
1141 msg=missing_required_lib('packaging'),
1142 exception=PACKAGING_IMPORT_ERROR
1143 )
1144
1145 try:
1146 mm = ModuleManager(module=module)
1147 results = mm.exec_module()
1148 module.exit_json(**results)
1149 except F5ModuleError as ex:
1150 module.fail_json(msg=str(ex))
1151
1152
1153 if __name__ == '__main__':
1154 main()