Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_software_install
13 short_description: Install software images on a BIG-IP
14 description:
15 - Install new software images on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 image:
19 description:
20 - Image to install on the remote device.
21 type: str
22 block_device_image:
23 description:
24 - Image to install on the remote device. In the case of a VCMP guest,
25 ensure this image is present on the VCMP host and is
26 referenced from there, and not from the VCMP guest. An ISO image
27 directly uploaded to the VCMP guest will not work.
28 type: str
29 version_added: "1.2.0"
30 volume:
31 description:
32 - The volume on which to install the software image.
33 type: str
34 state:
35 description:
36 - When C(installed), ensures the software is installed on the volume
37 and the volume is set to be booted from. The device is B(not) rebooted
38 into the new software.
39 - When C(activated), performs the same operation as C(installed), but
40 the system is rebooted to the new software.
41 type: str
42 choices:
43 - activated
44 - installed
45 default: activated
46 type:
47 description:
48 - The type of the BIG-IP.
49 - Defaults to C(standard), the other choice is C(vcmp).
50 type: str
51 default: standard
52 choices:
53 - standard
54 - vcmp
55 version_added: "1.2.0"
56 extends_documentation_fragment: f5networks.f5_modules.f5
57 author:
58 - Tim Rupp (@caphrim007)
59 - Wojciech Wypior (@wojtek0806)
60 - Nitin Khanna (@nitinthewiz)
61 '''
62 EXAMPLES = r'''
63 - name: Ensure an existing image is installed in specified volume
64 bigip_software_install:
65 image: BIGIP-13.0.0.0.0.1645.iso
66 volume: HD1.2
67 state: installed
68 provider:
69 password: secret
70 server: lb.mydomain.com
71 user: admin
72 delegate_to: localhost
73
74 - name: Ensure an existing image is activated in specified volume
75 bigip_software_install:
76 image: BIGIP-13.0.0.0.0.1645.iso
77 state: activated
78 volume: HD1.2
79 provider:
80 password: secret
81 server: lb.mydomain.com
82 user: admin
83 delegate_to: localhost
84
85 - name: Ensure an existing image is activated in specified volume in a VCMP guest
86 bigip_software_install:
87 block_device_image: BIGIP-13.0.0.0.0.1645.iso
88 type: vcmp
89 state: activated
90 volume: HD1.2
91 provider:
92 password: secret
93 server: lb.mydomain.com
94 user: admin
95 delegate_to: localhost
96 '''
97
98 RETURN = r'''
99 # only common fields returned
100 '''
101
102 import time
103 import ssl
104 from datetime import datetime
105
106 from ansible.module_utils.six.moves.urllib.error import URLError
107 from ansible.module_utils.urls import urlparse
108 from ansible.module_utils.basic import AnsibleModule
109
110 from ..module_utils.bigip import F5RestClient
111 from ..module_utils.common import (
112 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
113 )
114 from ..module_utils.icontrol import tmos_version
115 from ..module_utils.teem import send_teem
116
117
118 class Parameters(AnsibleF5Parameters):
119 api_map = {
120
121 }
122
123 api_attributes = [
124 'options',
125 'volume',
126 ]
127
128 returnables = [
129
130 ]
131
132 updatables = [
133
134 ]
135
136
137 class ApiParameters(Parameters):
138 @property
139 def image_names(self):
140 result = []
141 result += self.read_image_from_device('image')
142 result += self.read_image_from_device('hotfix')
143 return result
144
145 def read_image_from_device(self, t):
146 uri = "https://{0}:{1}/mgmt/tm/sys/software/{2}".format(
147 self.client.provider['server'],
148 self.client.provider['server_port'],
149 t,
150 )
151 resp = self.client.api.get(uri)
152 try:
153 response = resp.json()
154 except ValueError:
155 return []
156
157 if 'code' in response and response['code'] == 400:
158 if 'message' in response:
159 return []
160 else:
161 return []
162 if 'items' not in response:
163 return []
164 return [x['name'].split('/')[0] for x in response['items']]
165
166 @property
167 def block_device_image_names(self):
168 result = []
169 result += self.read_block_device_image_from_device()
170 result += self.read_block_device_hotfix_from_device()
171 return result
172
173 def read_block_device_image_from_device(self):
174 uri = "https://{0}:{1}/mgmt/tm/sys/software/block-device-image/".format(
175 self.client.provider['server'],
176 self.client.provider['server_port'],
177 )
178 resp = self.client.api.get(uri)
179 try:
180 response = resp.json()
181 except ValueError:
182 return []
183
184 if 'code' in response and response['code'] == 400:
185 if 'message' in response:
186 return []
187 else:
188 return []
189 if 'items' not in response:
190 return []
191 return [x['name'] for x in response['items']]
192
193 def read_block_device_hotfix_from_device(self):
194 uri = "https://{0}:{1}/mgmt/tm/sys/software/block-device-hotfix/".format(
195 self.client.provider['server'],
196 self.client.provider['server_port'],
197 )
198 resp = self.client.api.get(uri)
199 try:
200 response = resp.json()
201 except ValueError:
202 return []
203
204 if 'code' in response and response['code'] == 400:
205 if 'message' in response:
206 return []
207 else:
208 return []
209 if 'items' not in response:
210 return []
211 return [x['name'] for x in response['items']]
212
213
214 class ModuleParameters(Parameters):
215 @property
216 def version(self):
217 if self._values['version']:
218 return self._values['version']
219
220 if self._values['type'] == "standard":
221 self._values['version'] = self.image_info['version']
222 elif self._values['type'] == "vcmp":
223 self._values['version'] = self.block_device_image_info['version']
224 return self._values['version']
225
226 @property
227 def build(self):
228 # Return cached copy if we have it
229 if self._values['build']:
230 return self._values['build']
231
232 # Otherwise, get copy from image info cache
233 # self._values['build'] = self.image_info['build']
234
235 if self._values['type'] == "standard":
236 self._values['build'] = self.image_info['build']
237 elif self._values['type'] == "vcmp":
238 self._values['build'] = self.block_device_image_info['build']
239 return self._values['build']
240
241 @property
242 def image_info(self):
243 if self._values['image_info']:
244 image = self._values['image_info']
245 else:
246 # Otherwise, get a new copy and store in cache
247 image = self.read_image()
248 self._values['image_info'] = image
249 return image
250
251 @property
252 def block_device_image_info(self):
253 if self._values['block_device_image_info']:
254 block_device_image = self._values['block_device_image_info']
255 else:
256 # Otherwise, get a new copy and store in cache
257 block_device_image = self.read_block_device_image()
258 self._values['block_device_image_info'] = block_device_image
259 return block_device_image
260
261 @property
262 def image_type(self):
263 if self._values['image_type']:
264 return self._values['image_type']
265 if 'software:image' in self.image_info['kind']:
266 self._values['image_type'] = 'image'
267 else:
268 self._values['image_type'] = 'hotfix'
269 return self._values['image_type']
270
271 @property
272 def block_device_image_type(self):
273 if self._values['block_device_image_type']:
274 return self._values['block_device_image_type']
275 if 'software:block-device-image' in self.block_device_image_info['kind']:
276 self._values['block_device_image_type'] = 'block-device-image'
277 else:
278 self._values['block_device_image_type'] = 'block-device-hotfix'
279 return self._values['block_device_image_type']
280
281 def read_image(self):
282 image = self.read_image_from_device(type='image')
283 if image:
284 return image
285 image = self.read_image_from_device(type='hotfix')
286 if image:
287 return image
288 return None
289
290 def read_image_from_device(self, type):
291 uri = "https://{0}:{1}/mgmt/tm/sys/software/{2}/".format(
292 self.client.provider['server'],
293 self.client.provider['server_port'],
294 type,
295 )
296 resp = self.client.api.get(uri)
297
298 try:
299 response = resp.json()
300 except ValueError as ex:
301 raise F5ModuleError(str(ex))
302
303 if 'items' in response:
304 for item in response['items']:
305 if item['name'].startswith(self.image):
306 return item
307
308 def read_block_device_image(self):
309 block_device_image = self.read_block_device_image_from_device()
310 if block_device_image:
311 return block_device_image
312 block_device_image = self.read_block_device_hotfix_from_device()
313 if block_device_image:
314 return block_device_image
315 return None
316
317 def read_block_device_image_from_device(self):
318 uri = "https://{0}:{1}/mgmt/tm/sys/software/block-device-image/".format(
319 self.client.provider['server'],
320 self.client.provider['server_port'],
321 )
322 resp = self.client.api.get(uri)
323
324 try:
325 response = resp.json()
326 except ValueError as ex:
327 raise F5ModuleError(str(ex))
328
329 if 'items' in response:
330 for item in response['items']:
331 if item['name'].startswith(self.block_device_image):
332 return item
333
334 def read_block_device_hotfix_from_device(self):
335 uri = "https://{0}:{1}/mgmt/tm/sys/software/block-device-hotfix/".format(
336 self.client.provider['server'],
337 self.client.provider['server_port'],
338 )
339 resp = self.client.api.get(uri)
340
341 try:
342 response = resp.json()
343 except ValueError as ex:
344 raise F5ModuleError(str(ex))
345
346 if 'items' in response:
347 for item in response['items']:
348 if item['name'].startswith(self.block_device_image):
349 return item
350
351
352 class Changes(Parameters):
353 def to_return(self):
354 result = {}
355 try:
356 for returnable in self.returnables:
357 result[returnable] = getattr(self, returnable)
358 result = self._filter_params(result)
359 except Exception:
360 pass
361 return result
362
363
364 class UsableChanges(Changes):
365 pass
366
367
368 class ReportableChanges(Changes):
369 pass
370
371
372 class Difference(object):
373 def __init__(self, want, have=None):
374 self.want = want
375 self.have = have
376
377 def compare(self, param):
378 try:
379 result = getattr(self, param)
380 return result
381 except AttributeError:
382 return self.__default(param)
383
384 def __default(self, param):
385 attr1 = getattr(self.want, param)
386 try:
387 attr2 = getattr(self.have, param)
388 if attr1 != attr2:
389 return attr1
390 except AttributeError:
391 return attr1
392
393
394 class ModuleManager(object):
395 def __init__(self, *args, **kwargs):
396 self.module = kwargs.get('module', None)
397 self.client = F5RestClient(**self.module.params)
398 self.want = ModuleParameters(params=self.module.params, client=self.client)
399 self.have = ApiParameters(client=self.client)
400 self.changes = UsableChanges()
401 self.volume_url = None
402
403 def _set_changed_options(self):
404 changed = {}
405 for key in Parameters.returnables:
406 if getattr(self.want, key) is not None:
407 changed[key] = getattr(self.want, key)
408 if changed:
409 self.changes = UsableChanges(params=changed)
410
411 def _update_changed_options(self):
412 diff = Difference(self.want, self.have)
413 updatables = Parameters.updatables
414 changed = dict()
415 for k in updatables:
416 change = diff.compare(k)
417 if change is None:
418 continue
419 else:
420 if isinstance(change, dict):
421 changed.update(change)
422 else:
423 changed[k] = change
424 if changed:
425 self.changes = UsableChanges(params=changed)
426 return True
427 return False
428
429 def should_update(self):
430 result = self._update_changed_options()
431 if result:
432 return True
433 return False
434
435 def exec_module(self):
436 start = datetime.now().isoformat()
437 version = tmos_version(self.client)
438 result = dict()
439
440 changed = self.present()
441
442 reportable = ReportableChanges(params=self.changes.to_return())
443 changes = reportable.to_return()
444 result.update(**changes)
445 result.update(dict(changed=changed))
446 self._announce_deprecations(result)
447 send_teem(start, self.client, self.module, version)
448 return result
449
450 def _announce_deprecations(self, result):
451 warnings = result.pop('__warnings', [])
452 for warning in warnings:
453 self.client.module.deprecate(
454 msg=warning['msg'],
455 version=warning['version']
456 )
457
458 def present(self):
459 if self.exists():
460 return False
461 else:
462 return self.update()
463
464 def _set_volume_url(self, item):
465 path = urlparse(item['selfLink']).path
466 self.volume_url = "https://{0}:{1}{2}".format(
467 self.client.provider['server'],
468 self.client.provider['server_port'],
469 path
470 )
471
472 def volume_exists(self):
473 uri = "https://{0}:{1}/mgmt/tm/sys/software/volume/".format(
474 self.client.provider['server'],
475 self.client.provider['server_port']
476 )
477 resp = self.client.api.get(uri)
478
479 try:
480 collection = resp.json()
481 except ValueError as ex:
482 raise F5ModuleError(str(ex))
483
484 errors = [401, 403, 409, 500, 501, 502, 503, 504]
485
486 if resp.status in errors or 'code' in collection and collection['code'] in errors:
487 if 'message' in collection:
488 raise F5ModuleError(collection['message'])
489 else:
490 raise F5ModuleError(resp.content)
491
492 for item in collection['items']:
493 if item['name'].startswith(self.want.volume):
494 self._set_volume_url(item)
495 break
496
497 if not self.volume_url:
498 self.volume_url = uri + self.want.volume
499
500 resp = self.client.api.get(self.volume_url)
501
502 try:
503 response = resp.json()
504 except ValueError as ex:
505 raise F5ModuleError(str(ex))
506
507 if resp.status in errors or 'code' in response and response['code'] in errors:
508 if 'message' in response:
509 raise F5ModuleError(response['message'])
510 else:
511 raise F5ModuleError(resp.content)
512
513 if resp.status == 404 or 'code' in response and response['code'] == 404:
514 return False
515
516 return True
517
518 def software_installation_exists(self):
519 if self.volume_url is None:
520 return False
521
522 resp = self.client.api.get(self.volume_url)
523
524 try:
525 resp_json = resp.json()
526 except ValueError as ex:
527 raise F5ModuleError(str(ex))
528 if resp_json.get('status') and resp_json.get('status') == 404:
529 return False
530
531 same_version = self.want.version == resp_json.get('version', None)
532 same_build = self.want.build == resp_json.get('build', None)
533 if (not same_build) or (not same_version):
534 return False
535
536 return True
537
538 def remove_volume(self):
539 vol_url = self.volume_url.split('~')[0]
540 delresp = self.client.api.delete(vol_url)
541 if delresp.status == 200:
542 time.sleep(60)
543 return True
544
545 def exists(self):
546 if not self.volume_exists():
547 self.want.update({'options': [{'create-volume': True}]})
548 return False
549 if not self.software_installation_exists():
550 return False
551 return True
552
553 def update(self):
554 if self.module.check_mode:
555 return True
556
557 if self.want.type == "standard":
558 if self.want.image and self.want.image not in self.have.image_names:
559 raise F5ModuleError(
560 "The specified image was not found on the device."
561 )
562 elif self.want.type == "vcmp":
563 if self.want.block_device_image and not any(
564 have_block_device_image.startswith(self.want.block_device_image)
565 for have_block_device_image in self.have.block_device_image_names):
566 raise F5ModuleError(
567 "The specified block_device_image was not found on the device."
568 )
569
570 options = self.want.options if bool(self.want.options) else list()
571 if self.want.state == 'activated':
572 options.append({'reboot': True})
573 self.want.update({'options': options})
574
575 self.update_on_device()
576 self.wait_for_software_install_on_device()
577 if self.want.state == 'activated':
578 self.wait_for_device_reboot()
579 return True
580
581 def update_on_device(self):
582 if self.want.type == "standard":
583 params = {
584 "command": "install",
585 "name": self.want.image,
586 }
587 params.update(self.want.api_params())
588 uri = "https://{0}:{1}/mgmt/tm/sys/software/{2}".format(
589 self.client.provider['server'],
590 self.client.provider['server_port'],
591 self.want.image_type
592 )
593 elif self.want.type == "vcmp":
594 params = {
595 "command": "install",
596 "name": transform_name(name=self.want.block_device_image),
597 }
598 params.update(self.want.api_params())
599 uri = "https://{0}:{1}/mgmt/tm/sys/software/{2}".format(
600 self.client.provider['server'],
601 self.client.provider['server_port'],
602 transform_name(name=self.want.block_device_image_type)
603 )
604 resp = self.client.api.post(uri, json=params)
605 try:
606 response = resp.json()
607 if 'commandResult' in response and len(response['commandResult'].strip()) > 0:
608 raise F5ModuleError(response['commandResult'])
609 except ValueError as ex:
610 raise F5ModuleError(str(ex))
611 if 'code' in response and response['code'] in [400, 403]:
612 if 'message' in response:
613 raise F5ModuleError(response['message'])
614 else:
615 raise F5ModuleError(resp.content)
616 return True
617
618 def wait_for_device_reboot(self):
619 while True:
620 time.sleep(5)
621 try:
622 self.client.reconnect()
623 volume = self.read_volume_from_device()
624 if volume is None:
625 continue
626 if 'active' in volume and volume['active'] is True:
627 break
628 except F5ModuleError:
629 # Handle all exceptions because if the system is offline (for a
630 # reboot) the REST client will raise exceptions about
631 # connections
632 pass
633
634 def wait_for_software_install_on_device(self):
635 # We need to delay this slightly in case the the volume needs to be
636 # created first
637 for dummy in range(10):
638 try:
639 if self.volume_exists():
640 break
641 except F5ModuleError:
642 pass
643 time.sleep(5)
644 while True:
645 time.sleep(10)
646 volume = self.read_volume_from_device()
647 if volume is None or 'status' not in volume:
648 self.client.reconnect()
649 continue
650 if volume['status'] == 'complete':
651 break
652 elif volume['status'] == 'failed':
653 raise F5ModuleError
654
655 def read_volume_from_device(self):
656 try:
657 resp = self.client.api.get(self.volume_url)
658 response = resp.json()
659 except ValueError as ex:
660 raise F5ModuleError(str(ex))
661 except ssl.SSLError:
662 # Suggests BIG-IP is still in the middle of restarting itself or
663 # restjavad is restarting.
664 return None
665 except URLError:
666 # At times during reboot BIG-IP will reset or timeout connections so we catch and pass this here.
667 return None
668
669 if 'code' in response and response['code'] == 400:
670 if 'message' in response:
671 raise F5ModuleError(response['message'])
672 else:
673 raise F5ModuleError(resp.content)
674 return response
675
676
677 class ArgumentSpec(object):
678 def __init__(self):
679 self.supports_check_mode = True
680 argument_spec = dict(
681 image=dict(),
682 block_device_image=dict(),
683 volume=dict(),
684 state=dict(
685 default='activated',
686 choices=['activated', 'installed']
687 ),
688 type=dict(
689 choices=['standard', 'vcmp'],
690 default='standard'
691 ),
692 )
693 self.argument_spec = {}
694 self.argument_spec.update(f5_argument_spec)
695 self.argument_spec.update(argument_spec)
696
697
698 def main():
699 spec = ArgumentSpec()
700
701 module = AnsibleModule(
702 argument_spec=spec.argument_spec,
703 supports_check_mode=spec.supports_check_mode,
704 )
705
706 try:
707 mm = ModuleManager(module=module)
708 results = mm.exec_module()
709 module.exit_json(**results)
710 except F5ModuleError as ex:
711 module.fail_json(msg=str(ex))
712
713
714 if __name__ == '__main__':
715 main()