Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_qkview.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_qkview
13 short_description: Manage QKviews on the device
14 description:
15 - Manages creating and downloading QKviews from a BIG-IP. The qkview utility automatically
16 collects configuration and diagnostic information from BIG-IP systems, and combines
17 the data into a QKView file. F5 Support may request you send or upload this
18 QKview to assist in troubleshooting.
19 version_added: "1.0.0"
20 options:
21 filename:
22 description:
23 - Name of the QKview file to create on the remote BIG-IP.
24 type: str
25 default: "localhost.localdomain.qkview"
26 dest:
27 description:
28 - Destination on your local filesystem where you want to save the QKview.
29 type: path
30 asm_request_log:
31 description:
32 - When C(true), includes ASM request log data. When C(False),
33 excludes ASM request log data.
34 type: bool
35 default: no
36 max_file_size:
37 description:
38 - Maximum file size of the QKview file, in bytes. By default, no max
39 file size is specified.
40 type: int
41 complete_information:
42 description:
43 - Include complete (all applicable) information in the QKview.
44 type: bool
45 default: false
46 exclude_core:
47 description:
48 - Exclude core files from the QKview.
49 type: bool
50 default: false
51 exclude:
52 description:
53 - Exclude various file from the QKview.
54 type: list
55 elements: str
56 choices:
57 - all
58 - audit
59 - secure
60 - bash_history
61 force:
62 description:
63 - If C(no), the file will only be transferred if the destination does not
64 exist.
65 type: bool
66 default: true
67 only_create_file:
68 description:
69 - If C(true), the file is created on the device and not downloaded. The file will not be deleted by the
70 module from the device.
71 type: bool
72 default: false
73 version_added: "1.20.0"
74 notes:
75 - This module does not include the "max time" or "restrict to blade" options.
76 - If you are using this module with either Ansible Tower or Ansible AWX, you
77 should be aware of how these Ansible products execute jobs in restricted
78 environments. More information can be found here
79 https://clouddocs.f5.com/products/orchestration/ansible/devel/usage/module-usage-with-tower.html
80 - Some longer running tasks might cause the REST interface on BIG-IP to time out, to avoid this adjust the timers as
81 per this KB article https://support.f5.com/csp/article/K94602685
82 extends_documentation_fragment: f5networks.f5_modules.f5
83 author:
84 - Tim Rupp (@caphrim007)
85 '''
86
87 EXAMPLES = r'''
88 - name: Fetch a qkview from the remote device
89 bigip_qkview:
90 asm_request_log: true
91 exclude:
92 - audit
93 - secure
94 dest: /tmp/localhost.localdomain.qkview
95 provider:
96 password: secret
97 server: lb.mydomain.com
98 user: admin
99 delegate_to: localhost
100 '''
101
102 RETURN = r'''
103 # only common fields returned
104 '''
105
106 import os
107 import re
108 import socket
109 import ssl
110 import time
111 import traceback
112 from datetime import datetime
113
114 try:
115 from packaging.version import Version
116 except ImportError:
117 HAS_PACKAGING = False
118 Version = None
119 PACKAGING_IMPORT_ERROR = traceback.format_exc()
120 else:
121 HAS_PACKAGING = True
122 PACKAGING_IMPORT_ERROR = None
123
124 from ansible.module_utils.basic import (
125 AnsibleModule, missing_required_lib
126 )
127
128 from ..module_utils.bigip import F5RestClient
129 from ..module_utils.common import (
130 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
131 )
132 from ..module_utils.icontrol import (
133 download_file, tmos_version
134 )
135 from ..module_utils.teem import send_teem
136
137
138 class Parameters(AnsibleF5Parameters):
139 api_attributes = [
140 'asm_request_log',
141 'complete_information',
142 'exclude',
143 'exclude_core',
144 'filename_cmd',
145 'max_file_size',
146 ]
147
148 returnables = ['stdout', 'stdout_lines', 'warnings']
149
150 @property
151 def exclude(self):
152 if self._values['exclude'] is None:
153 return None
154 exclude = ' '.join(self._values['exclude'])
155 return "--exclude='{0}'".format(exclude)
156
157 @property
158 def exclude_raw(self):
159 return self._values['exclude']
160
161 @property
162 def exclude_core(self):
163 if self._values['exclude']:
164 return '-C'
165 else:
166 return None
167
168 @property
169 def complete_information(self):
170 if self._values['complete_information']:
171 return '-c'
172 return None
173
174 @property
175 def max_file_size(self):
176 if self._values['max_file_size'] in [None]:
177 return None
178 return '-s {0}'.format(self._values['max_file_size'])
179
180 @property
181 def asm_request_log(self):
182 if self._values['asm_request_log']:
183 return '-o asm-request-log'
184 return None
185
186 @property
187 def filename(self):
188 pattern = r'^[\w\.]+$'
189 filename = os.path.basename(self._values['filename'])
190 if re.match(pattern, filename):
191 return filename
192 else:
193 raise F5ModuleError(
194 "The provided filename must contain word characters only."
195 )
196
197 @property
198 def filename_cmd(self):
199 return '-f {0}'.format(self.filename)
200
201 def to_return(self):
202 result = {}
203 try:
204 for returnable in self.returnables:
205 result[returnable] = getattr(self, returnable)
206 result = self._filter_params(result)
207 except Exception:
208 pass
209 return result
210
211 def api_params(self):
212 result = {}
213 for api_attribute in self.api_attributes:
214 if self.api_map is not None and api_attribute in self.api_map:
215 result[api_attribute] = getattr(self, self.api_map[api_attribute])
216 else:
217 result[api_attribute] = getattr(self, api_attribute)
218 result = self._filter_params(result)
219 return result
220
221
222 class ModuleManager(object):
223 def __init__(self, *args, **kwargs):
224 self.module = kwargs.get('module', None)
225 self.client = F5RestClient(**self.module.params)
226 self.kwargs = kwargs
227
228 def exec_module(self):
229 if self.is_version_less_than_14():
230 manager = self.get_manager('madm')
231 else:
232 manager = self.get_manager('bulk')
233 return manager.exec_module()
234
235 def get_manager(self, type):
236 if type == 'madm':
237 return MadmLocationManager(**self.kwargs)
238 elif type == 'bulk':
239 return BulkLocationManager(**self.kwargs)
240
241 def is_version_less_than_14(self):
242 version = tmos_version(self.client)
243 if Version(version) < Version('14.0.0'):
244 return True
245 else:
246 return False
247
248
249 class BaseManager(object):
250 def __init__(self, *args, **kwargs):
251 self.module = kwargs.get('module', None)
252 self.client = F5RestClient(**self.module.params)
253 self.have = None
254 self.want = Parameters(params=self.module.params)
255 self.changes = Parameters()
256
257 def _set_changed_options(self):
258 changed = {}
259 for key in Parameters.returnables:
260 if getattr(self.want, key) is not None:
261 changed[key] = getattr(self.want, key)
262 if changed:
263 self.changes = Parameters(params=changed)
264
265 def exec_module(self):
266 start = datetime.now().isoformat()
267 version = tmos_version(self.client)
268 result = dict()
269
270 self.present()
271
272 result.update(**self.changes.to_return())
273 result.update(dict(changed=False))
274 send_teem(start, self.client, self.module, version)
275 return result
276
277 def present(self):
278 if not self.want.only_create_file:
279 if os.path.exists(self.want.dest) and not self.want.force:
280 raise F5ModuleError(
281 "The specified 'dest' file already exists."
282 )
283 if not os.path.exists(os.path.dirname(self.want.dest)):
284 raise F5ModuleError(
285 "The directory of your 'dest' file does not exist."
286 )
287 if self.want.exclude:
288 choices = ['all', 'audit', 'secure', 'bash_history']
289 if not all(x in choices for x in self.want.exclude_raw):
290 raise F5ModuleError(
291 "The specified excludes must be in the following list: "
292 "{0}".format(','.join(choices))
293 )
294 self.execute()
295
296 def exists(self):
297 params = dict(
298 command='run',
299 utilCmdArgs=self.remote_dir
300 )
301 uri = "https://{0}:{1}/mgmt/tm/util/unix-ls".format(
302 self.client.provider['server'],
303 self.client.provider['server_port'],
304 )
305 resp = self.client.api.post(uri, json=params)
306 try:
307 response = resp.json()
308 except ValueError:
309 return False
310 if resp.status == 404 or 'code' in response and response['code'] == 404:
311 return False
312
313 try:
314 if self.want.filename in response['commandResult']:
315 return True
316 except KeyError:
317 return False
318
319 def execute(self):
320 response = self.execute_on_device()
321 if not response:
322 raise F5ModuleError(
323 "Failed to create qkview on device."
324 )
325
326 if not self.want.only_create_file:
327 result = self._move_qkview_to_download()
328 if not result:
329 raise F5ModuleError(
330 "Failed to move the file to a downloadable location"
331 )
332
333 self._download_file()
334 if not os.path.exists(self.want.dest):
335 raise F5ModuleError(
336 "Failed to save the qkview to local disk"
337 )
338
339 self._delete_qkview()
340 result = self.exists()
341 if result:
342 raise F5ModuleError(
343 "Failed to remove the remote qkview"
344 )
345
346 def _delete_qkview(self):
347 tpath_name = '{0}/{1}'.format(self.remote_dir, self.want.filename)
348 params = dict(
349 command='run',
350 utilCmdArgs=tpath_name
351 )
352 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format(
353 self.client.provider['server'],
354 self.client.provider['server_port'],
355 )
356 resp = self.client.api.post(uri, json=params)
357 try:
358 response = resp.json()
359 except ValueError:
360 return False
361 if resp.status == 404 or 'code' in response and response['code'] == 404:
362 return False
363
364 def execute_on_device(self):
365 self._upsert_temporary_cli_script_on_device()
366 task_id = self._create_async_task_on_device()
367 self._exec_async_task_on_device(task_id)
368 self._wait_for_async_task_to_finish_on_device(task_id)
369 self._remove_temporary_cli_script_from_device()
370 return True
371
372 def _upsert_temporary_cli_script_on_device(self):
373 args = {
374 "name": "__ansible_mkqkview",
375 "apiAnonymous": """
376 proc script::run {} {
377 set cmd [lreplace $tmsh::argv 0 0]; eval "exec $cmd 2> /dev/null"
378 }
379 """
380 }
381 result = self._create_temporary_cli_script_on_device(args)
382 if result:
383 return True
384 return self._update_temporary_cli_script_on_device(args)
385
386 def _create_temporary_cli_script_on_device(self, args):
387 uri = "https://{0}:{1}/mgmt/tm/cli/script".format(
388 self.client.provider['server'],
389 self.client.provider['server_port'],
390 )
391 resp = self.client.api.post(uri, json=args)
392 try:
393 response = resp.json()
394 if 'code' in response and response['code'] in [404, 409]:
395 return False
396 except ValueError:
397 pass
398 if resp.status in [404, 409]:
399 return False
400 return True
401
402 def _update_temporary_cli_script_on_device(self, args):
403 uri = "https://{0}:{1}/mgmt/tm/cli/script/{2}".format(
404 self.client.provider['server'],
405 self.client.provider['server_port'],
406 transform_name('Common', '__ansible_mkqkview')
407 )
408 resp = self.client.api.put(uri, json=args)
409 try:
410 resp.json()
411 return True
412 except ValueError:
413 raise F5ModuleError(
414 "Failed to update temporary cli script on device."
415 )
416
417 def _create_async_task_on_device(self):
418 """Creates an async cli script task in the REST API
419
420 Returns:
421 int: The ID of the task staged for running.
422
423 :return:
424 """
425 command = ' '.join(self.want.api_params().values())
426 args = {
427 "command": "run",
428 "name": "__ansible_mkqkview",
429 "utilCmdArgs": "/usr/bin/qkview {0}".format(command)
430 }
431 uri = "https://{0}:{1}/mgmt/tm/task/cli/script".format(
432 self.client.provider['server'],
433 self.client.provider['server_port'],
434 )
435 resp = self.client.api.post(uri, json=args)
436 try:
437 response = resp.json()
438 return response['_taskId']
439 except ValueError:
440 raise F5ModuleError(
441 "Failed to create the async task on the device."
442 )
443
444 def _exec_async_task_on_device(self, task_id):
445 args = {"_taskState": "VALIDATING"}
446 uri = "https://{0}:{1}/mgmt/tm/task/cli/script/{2}".format(
447 self.client.provider['server'],
448 self.client.provider['server_port'],
449 task_id
450 )
451 resp = self.client.api.put(uri, json=args)
452 try:
453 resp.json()
454 return True
455 except ValueError:
456 raise F5ModuleError(
457 "Failed to execute the async task on the device"
458 )
459
460 def _wait_for_async_task_to_finish_on_device(self, task_id):
461 uri = "https://{0}:{1}/mgmt/tm/task/cli/script/{2}/result".format(
462 self.client.provider['server'],
463 self.client.provider['server_port'],
464 task_id
465 )
466 while True:
467 try:
468 resp = self.client.api.get(uri, timeout=10)
469 except (socket.timeout, ssl.SSLError):
470 continue
471 try:
472 response = resp.json()
473 except ValueError:
474 # It is possible that the API call can return invalid JSON.
475 # This invalid JSON appears to be just empty strings.
476 continue
477 if response['_taskState'] == 'FAILED':
478 raise F5ModuleError(
479 "qkview creation task failed unexpectedly."
480 )
481 if response['_taskState'] == 'COMPLETED':
482 return True
483 time.sleep(3)
484
485 def _remove_temporary_cli_script_from_device(self):
486 uri = "https://{0}:{1}/mgmt/tm/task/cli/script/{2}".format(
487 self.client.provider['server'],
488 self.client.provider['server_port'],
489 transform_name('Common', '__ansible_mkqkview')
490 )
491 try:
492 self.client.api.delete(uri)
493 return True
494 except ValueError:
495 raise F5ModuleError(
496 "Failed to remove the temporary cli script from the device."
497 )
498
499 def _move_qkview_to_download(self):
500 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
501 self.client.provider['server'],
502 self.client.provider['server_port']
503 )
504 args = dict(
505 command='run',
506 utilCmdArgs='/var/tmp/{0} {1}/{0}'.format(self.want.filename, self.remote_dir)
507 )
508 self.client.api.post(uri, json=args)
509 return True
510
511
512 class BulkLocationManager(BaseManager):
513 def __init__(self, *args, **kwargs):
514 super(BulkLocationManager, self).__init__(**kwargs)
515 self.remote_dir = '/var/config/rest/bulk'
516
517 def _download_file(self):
518 uri = "https://{0}:{1}/mgmt/shared/file-transfer/bulk/{2}".format(
519 self.client.provider['server'],
520 self.client.provider['server_port'],
521 self.want.filename
522 )
523 download_file(self.client, uri, self.want.dest)
524 if os.path.exists(self.want.dest):
525 return True
526 return False
527
528
529 class MadmLocationManager(BaseManager):
530 def __init__(self, *args, **kwargs):
531 super(MadmLocationManager, self).__init__(**kwargs)
532 self.remote_dir = '/var/config/rest/madm'
533
534 def _download_file(self):
535 uri = "https://{0}:{1}/mgmt/shared/file-transfer/madm/{2}".format(
536 self.client.provider['server'],
537 self.client.provider['server_port'],
538 self.want.filename
539 )
540 download_file(self.client, uri, self.want.dest)
541 if os.path.exists(self.want.dest):
542 return True
543 return False
544
545
546 class ArgumentSpec(object):
547 def __init__(self):
548 self.supports_check_mode = True
549 argument_spec = dict(
550 filename=dict(
551 default='localhost.localdomain.qkview'
552 ),
553 asm_request_log=dict(
554 type='bool',
555 default='no',
556 ),
557 max_file_size=dict(
558 type='int',
559 ),
560 complete_information=dict(
561 default='no',
562 type='bool'
563 ),
564 exclude_core=dict(
565 default="no",
566 type='bool'
567 ),
568 force=dict(
569 default=True,
570 type='bool'
571 ),
572 exclude=dict(
573 type='list',
574 elements='str',
575 choices=[
576 'all', 'audit', 'secure', 'bash_history'
577 ]
578 ),
579 only_create_file=dict(
580 default='no',
581 type='bool'
582 ),
583 dest=dict(
584 type='path'
585 )
586 )
587 self.required_if = [
588 ['only_create_file', 'no', ['dest']]
589 ]
590 self.argument_spec = {}
591 self.argument_spec.update(f5_argument_spec)
592 self.argument_spec.update(argument_spec)
593
594
595 def main():
596 spec = ArgumentSpec()
597
598 module = AnsibleModule(
599 argument_spec=spec.argument_spec,
600 supports_check_mode=spec.supports_check_mode,
601 )
602
603 if not HAS_PACKAGING:
604 module.fail_json(
605 msg=missing_required_lib('packaging'),
606 exception=PACKAGING_IMPORT_ERROR
607 )
608
609 try:
610 mm = ModuleManager(module=module)
611 results = mm.exec_module()
612 module.exit_json(**results)
613 except F5ModuleError as ex:
614 module.fail_json(msg=str(ex))
615
616
617 if __name__ == '__main__':
618 main()