Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/module_utils/common.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 import copy
10 import os
11 import re
12 import datetime
13
14 from ansible.module_utils._text import to_text
15 from ansible.module_utils.connection import exec_command
16 from ansible.module_utils.basic import env_fallback
17 from ansible.module_utils.six import iteritems
18 from ansible.module_utils.parsing.convert_bool import (
19 BOOLEANS_TRUE, BOOLEANS_FALSE
20 )
21 from collections import defaultdict
22
23 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
24 NetworkConfig, ConfigLine, ignore_line
25 )
26 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
27 to_list, ComplexList
28 )
29 from .constants import (
30 MANAGED_BY_ANNOTATION_MODIFIED, MANAGED_BY_ANNOTATION_VERSION
31 )
32
33 f5_provider_spec = {
34 'server': dict(
35 required=True,
36 fallback=(env_fallback, ['F5_SERVER'])
37 ),
38 'server_port': dict(
39 type='int',
40 default=443,
41 fallback=(env_fallback, ['F5_SERVER_PORT'])
42 ),
43 'user': dict(
44 required=True,
45 fallback=(env_fallback, ['F5_USER', 'ANSIBLE_NET_USERNAME'])
46 ),
47 'password': dict(
48 required=True,
49 no_log=True,
50 aliases=['pass', 'pwd'],
51 fallback=(env_fallback, ['F5_PASSWORD', 'ANSIBLE_NET_PASSWORD']),
52 ),
53 'validate_certs': dict(
54 type='bool',
55 default='yes',
56 fallback=(env_fallback, ['F5_VALIDATE_CERTS'])
57 ),
58 'transport': dict(
59 choices=['rest'],
60 default='rest'
61 ),
62 'timeout': dict(type='int'),
63 'no_f5_teem': dict(
64 type='bool',
65 default=False,
66 fallback=(env_fallback, ['F5_TEEM', 'F5_TELEMETRY_OFF'])
67 ),
68 'auth_provider': dict(),
69 }
70
71 f5_argument_spec = {
72 'provider': dict(type='dict', options=f5_provider_spec),
73 }
74
75
76 def get_provider_argspec():
77 return f5_provider_spec
78
79
80 def load_params(params):
81 provider = params.get('provider') or dict()
82 for key, value in iteritems(provider):
83 if key in f5_argument_spec:
84 if params.get(key) is None and value is not None:
85 params[key] = value
86
87
88 def is_empty_list(seq):
89 if len(seq) == 1:
90 if seq[0] == '' or seq[0] == 'none':
91 return True
92 return False
93
94
95 def fq_name(partition, value, sub_path=''):
96 """Returns a 'Fully Qualified' name
97
98 A BIG-IP expects most names of resources to be in a fully-qualified
99 form. This means that both the simple name, and the partition need
100 to be combined.
101
102 The Ansible modules, however, can accept (as names for several
103 resources) their name in the FQ format. This becomes an issue when
104 the FQ name and the partition are both specified as separate values.
105
106 Consider the following examples.
107
108 # Name not FQ
109 name: foo
110 partition: Common
111
112 # Name FQ
113 name: /Common/foo
114 partition: Common
115
116 This method will rectify the above situation and will, in both cases,
117 return the following for name.
118
119 /Common/foo
120
121 Args:
122 partition (string): The partition that you would want attached to
123 the name if the name has no partition.
124 value (string): The name that you want to attach a partition to.
125 This value will be returned unchanged if it has a partition
126 attached to it already.
127 sub_path (string): The sub path element. If defined the sub_path
128 will be inserted between partition and value.
129 This will also work on FQ names.
130 Returns:
131 string: The fully qualified name, given the input parameters.
132 """
133 if value is not None and sub_path == '':
134 try:
135 int(value)
136 return '/{0}/{1}'.format(partition, value)
137 except (ValueError, TypeError):
138 if not value.startswith('/'):
139 return '/{0}/{1}'.format(partition, value)
140 if value is not None and sub_path != '':
141 try:
142 int(value)
143 return '/{0}/{1}/{2}'.format(partition, sub_path, value)
144 except (ValueError, TypeError):
145 if value.startswith('/'):
146 dummy, partition, name = value.split('/')
147 return '/{0}/{1}/{2}'.format(partition, sub_path, name)
148 if not value.startswith('/'):
149 return '/{0}/{1}/{2}'.format(partition, sub_path, value)
150 return value
151
152
153 # Fully Qualified name (with partition) for a list
154 def fq_list_names(partition, list_names):
155 if list_names is None:
156 return None
157 return map(lambda x: fq_name(partition, x), list_names)
158
159
160 def to_commands(module, commands):
161 spec = {
162 'command': dict(key=True),
163 'prompt': dict(),
164 'answer': dict()
165 }
166 transform = ComplexList(spec, module)
167 return transform(commands)
168
169
170 def run_commands(module, commands, check_rc=True):
171 responses = list()
172 commands = to_commands(module, to_list(commands))
173 for cmd in commands:
174 cmd = module.jsonify(cmd)
175 rc, out, err = exec_command(module, cmd)
176 if check_rc and rc != 0:
177 raise F5ModuleError(to_text(err, errors='surrogate_then_replace'))
178 result = to_text(out, errors='surrogate_then_replace')
179 responses.append(result)
180 return responses
181
182
183 def flatten_boolean(value):
184 truthy = list(BOOLEANS_TRUE) + ['enabled', 'True', 'true']
185 falsey = list(BOOLEANS_FALSE) + ['disabled', 'False', 'false']
186 if value is None:
187 return None
188 elif value in truthy:
189 return 'yes'
190 elif value in falsey:
191 return 'no'
192
193
194 def is_cli(module):
195 transport = module.params.get('transport', None)
196 provider_transport = (module.params['provider'] or {}).get('transport')
197 result = 'cli' in (transport, provider_transport)
198 return result
199
200
201 def is_valid_hostname(host):
202 """Reasonable attempt at validating a hostname
203
204 Compiled from various paragraphs outlined here
205 https://tools.ietf.org/html/rfc3696#section-2
206 https://tools.ietf.org/html/rfc1123
207
208 Notably,
209 * Host software MUST handle host names of up to 63 characters and
210 SHOULD handle host names of up to 255 characters.
211 * The "LDH rule", after the characters that it permits. (letters, digits, hyphen)
212 * If the hyphen is used, it is not permitted to appear at
213 either the beginning or end of a label
214
215 :param host:
216 :return:
217 """
218 if len(host) > 255:
219 return False
220 host = host.rstrip(".")
221 allowed = re.compile(r'(?!-)[A-Z0-9-]{1,63}(?<!-)$', re.IGNORECASE)
222 result = all(allowed.match(x) for x in host.split("."))
223 return result
224
225
226 def is_valid_fqdn(host):
227 """Reasonable attempt at validating a hostname
228
229 Compiled from various paragraphs outlined here
230 https://tools.ietf.org/html/rfc3696#section-2
231 https://tools.ietf.org/html/rfc1123
232
233 Notably,
234 * Host software MUST handle host names of up to 63 characters and
235 SHOULD handle host names of up to 255 characters.
236 * The "LDH rule", after the characters that it permits. (letters, digits, hyphen)
237 * If the hyphen is used, it is not permitted to appear at
238 either the beginning or end of a label
239
240 :param host:
241 :return:
242 """
243 if len(host) > 255:
244 return False
245 host = host.rstrip(".")
246 allowed = re.compile(r'(?!-)[A-Z0-9-*]{1,63}(?<!-)$', re.IGNORECASE)
247 result = all(allowed.match(x) for x in host.split("."))
248 if result:
249 parts = host.split('.')
250 if len(parts) > 1:
251 return True
252 return False
253
254
255 def transform_name(partition='', name='', sub_path=''):
256 if partition != '':
257 if name.startswith(partition + '/'):
258 name = name.replace(partition + '/', '')
259 if name.startswith('/' + partition + '/'):
260 name = name.replace('/' + partition + '/', '')
261
262 if name:
263 name = name.replace('/', '~')
264 name = name.replace('%', '%25')
265
266 if partition:
267 partition = partition.replace('/', '~')
268 if not partition.startswith('~'):
269 partition = '~' + partition
270 else:
271 if sub_path:
272 raise F5ModuleError(
273 'When giving the subPath component include partition as well.'
274 )
275
276 if sub_path and partition:
277 sub_path = '~' + sub_path
278
279 if name and partition:
280 name = '~' + name
281
282 result = partition + sub_path + name
283 return result
284
285
286 def is_ansible_debug(module):
287 if module._debug and module._verbosity >= 4:
288 return True
289 return False
290
291
292 def is_uuid(uuid=None):
293 """Check to see if value is an F5 UUID
294
295 UUIDs are used in BIG-IQ and in select areas of BIG-IP (notably ASM). This method
296 will check to see if the provided value matches a UUID as known by these products.
297
298 Args:
299 uuid (string): The value to check for UUID-ness
300
301 Returns:
302 bool:
303 """
304 if uuid is None:
305 return False
306 pattern = r'[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}'
307 if re.match(pattern, uuid):
308 return True
309 return False
310
311
312 def on_bigip():
313 if os.path.exists('/usr/bin/tmsh'):
314 return True
315 return False
316
317
318 def mark_managed_by(ansible_version, params):
319 metadata = []
320 result = copy.deepcopy(params)
321 found1 = False
322 found2 = False
323 mark1 = dict(
324 name=MANAGED_BY_ANNOTATION_VERSION,
325 value=ansible_version,
326 persist='true'
327 )
328 mark2 = dict(
329 name=MANAGED_BY_ANNOTATION_MODIFIED,
330 value=str(datetime.datetime.utcnow()),
331 persist='true'
332 )
333
334 if 'metadata' not in result:
335 result['metadata'] = [mark1, mark2]
336 return result
337
338 for x in params['metadata']:
339 if x['name'] == MANAGED_BY_ANNOTATION_VERSION:
340 found1 = True
341 metadata.append(mark1)
342 if x['name'] == MANAGED_BY_ANNOTATION_MODIFIED:
343 found2 = True
344 metadata.append(mark1)
345 else:
346 metadata.append(x)
347 if not found1:
348 metadata.append(mark1)
349 if not found2:
350 metadata.append(mark2)
351
352 result['metadata'] = metadata
353 return result
354
355
356 def only_has_managed_metadata(metadata):
357 managed = [
358 MANAGED_BY_ANNOTATION_MODIFIED,
359 MANAGED_BY_ANNOTATION_VERSION,
360 ]
361
362 for x in metadata:
363 if x['name'] not in managed:
364 return False
365 return True
366
367
368 def merge_two_dicts(x, y):
369 """ Merge any two dicts passed to the function
370 This does not do a deep copy, just a shallow
371 copy. However, it does create a new object,
372 so there's that.
373 """
374 z = x.copy()
375 z.update(y)
376 return z
377
378
379 class Noop(object):
380 """Represent no-operation required
381
382 This class is used in the Difference engine to specify when an attribute
383 has not changed. Difference attributes may return an instance of this
384 class as a means to indicate when the attribute has not changed.
385
386 The Noop object allows attributes to be set to None when sending updates
387 to the API. `None` is technically a valid value in some cases (it indicates
388 that the attribute should be removed from the resource).
389 """
390 pass
391
392
393 class F5BaseClient(object):
394 def __init__(self, *args, **kwargs):
395 self.params = kwargs
396 self.module = kwargs.get('module', None)
397 load_params(self.params)
398 self._client = None
399
400 @property
401 def api(self):
402 raise F5ModuleError("Management root must be used from the concrete product classes.")
403
404 def reconnect(self):
405 """Attempts to reconnect to a device
406
407 The existing token from a ManagementRoot can become invalid if you,
408 for example, upgrade the device (such as is done in the *_software
409 module.
410
411 This method can be used to reconnect to a remote device without
412 having to re-instantiate the ArgumentSpec and AnsibleF5Client classes
413 it will use the same values that were initially provided to those
414 classes
415
416 :return:
417 :raises iControlUnexpectedHTTPError
418 """
419 self._client = None
420
421 @staticmethod
422 def validate_params(key, store):
423 if key in store and store[key] is not None:
424 return True
425 else:
426 return False
427
428 def merge_provider_params(self):
429 result = dict()
430 provider = self.params.get('provider', None)
431 if not provider:
432 provider = {}
433
434 self.merge_provider_server_param(result, provider)
435 self.merge_provider_server_port_param(result, provider)
436 self.merge_provider_validate_certs_param(result, provider)
437 self.merge_provider_auth_provider_param(result, provider)
438 self.merge_provider_user_param(result, provider)
439 self.merge_provider_timeout_param(result, provider)
440 self.merge_provider_password_param(result, provider)
441 self.merge_provider_no_f5_teem_param(result, provider)
442 return result
443
444 def merge_provider_server_param(self, result, provider):
445 if self.validate_params('server', provider):
446 result['server'] = provider['server']
447 elif self.validate_params('F5_SERVER', os.environ):
448 result['server'] = os.environ['F5_SERVER']
449 else:
450 raise F5ModuleError('Server parameter cannot be None or missing, please provide a valid value')
451
452 def merge_provider_server_port_param(self, result, provider):
453 if self.validate_params('server_port', provider):
454 result['server_port'] = provider['server_port']
455 elif self.validate_params('F5_SERVER_PORT', os.environ):
456 result['server_port'] = os.environ['F5_SERVER_PORT']
457 else:
458 result['server_port'] = 443
459
460 def merge_provider_validate_certs_param(self, result, provider):
461 if self.validate_params('validate_certs', provider):
462 result['validate_certs'] = provider['validate_certs']
463 elif self.validate_params('F5_VALIDATE_CERTS', os.environ):
464 result['validate_certs'] = os.environ['F5_VALIDATE_CERTS']
465 else:
466 result['validate_certs'] = True
467 if result['validate_certs'] in BOOLEANS_TRUE:
468 result['validate_certs'] = True
469 else:
470 result['validate_certs'] = False
471
472 def merge_provider_auth_provider_param(self, result, provider):
473 if self.validate_params('auth_provider', provider):
474 result['auth_provider'] = provider['auth_provider']
475 elif self.validate_params('F5_AUTH_PROVIDER', os.environ):
476 result['auth_provider'] = os.environ['F5_AUTH_PROVIDER']
477 else:
478 result['auth_provider'] = None
479
480 # Handle a specific case of the user specifying ``|default(omit)``
481 # as the value to the auth_provider.
482 #
483 # In this case, Ansible will inject the omit-placeholder value
484 # and the module params incorrectly interpret this. This case
485 # can occur when specifying ``|default(omit)`` for a variable
486 # value defined in the ``environment`` section of a Play.
487 #
488 # An example of the omit placeholder is shown below.
489 #
490 # __omit_place_holder__11bd71a2840bff144594b9cc2149db814256f253
491 #
492 if result['auth_provider'] is not None and '__omit_place_holder__' in result['auth_provider']:
493 result['auth_provider'] = None
494
495 def merge_provider_user_param(self, result, provider):
496 if self.validate_params('user', provider):
497 result['user'] = provider['user']
498 elif self.validate_params('F5_USER', os.environ):
499 result['user'] = os.environ.get('F5_USER')
500 elif self.validate_params('ANSIBLE_NET_USERNAME', os.environ):
501 result['user'] = os.environ.get('ANSIBLE_NET_USERNAME')
502 else:
503 result['user'] = None
504
505 def merge_provider_timeout_param(self, result, provider):
506 if self.validate_params('timeout', provider):
507 result['timeout'] = provider['timeout']
508 elif self.validate_params('F5_TIMEOUT', os.environ):
509 result['timeout'] = os.environ.get('F5_TIMEOUT')
510 else:
511 result['timeout'] = None
512
513 def merge_provider_password_param(self, result, provider):
514 if self.validate_params('password', provider):
515 result['password'] = provider['password']
516 elif self.validate_params('F5_PASSWORD', os.environ):
517 result['password'] = os.environ.get('F5_PASSWORD')
518 elif self.validate_params('ANSIBLE_NET_PASSWORD', os.environ):
519 result['password'] = os.environ.get('ANSIBLE_NET_PASSWORD')
520 else:
521 result['password'] = None
522
523 def merge_provider_no_f5_teem_param(self, result, provider):
524 if self.validate_params('no_f5_teem', provider):
525 result['no_f5_teem'] = provider['no_f5_teem']
526 elif self.validate_params('F5_TEEM', os.environ):
527 result['no_f5_teem'] = os.environ['F5_TEEM']
528 elif self.validate_params('F5_TELEMETRY_OFF', os.environ):
529 result['no_f5_teem'] = os.environ['F5_TELEMETRY_OFF']
530 else:
531 result['no_f5_teem'] = False
532
533 if result['no_f5_teem'] in BOOLEANS_TRUE:
534 result['no_f5_teem'] = True
535 else:
536 result['no_f5_teem'] = False
537
538
539 class AnsibleF5Parameters(object):
540 def __init__(self, *args, **kwargs):
541 self._values = defaultdict(lambda: None)
542 self._values['__warnings'] = []
543 self.client = kwargs.pop('client', None)
544 self._module = kwargs.pop('module', None)
545 self._params = {}
546
547 params = kwargs.pop('params', None)
548 if params:
549 self.update(params=params)
550 self._params.update(params)
551
552 def update(self, params=None):
553 if params:
554 self._params.update(params)
555 for k, v in iteritems(params):
556 # Adding this here because ``username`` is a connection parameter
557 # and in cases where it is also an API parameter, we run the risk
558 # of overriding the specified parameter with the connection parameter.
559 #
560 # Since this is a problem, and since "username" is never a valid
561 # parameter outside its usage in connection params (where we do not
562 # use the ApiParameter or ModuleParameters classes) it is safe to
563 # skip over it if it is provided.
564 if k == 'password':
565 continue
566 if self.api_map is not None and k in self.api_map:
567 map_key = self.api_map[k]
568 else:
569 map_key = k
570
571 # Handle weird API parameters like `dns.proxy.__iter__` by
572 # using a map provided by the module developer
573 class_attr = getattr(type(self), map_key, None)
574 if isinstance(class_attr, property):
575 # There is a mapped value for the api_map key
576 if class_attr.fset is None:
577 # If the mapped value does not have
578 # an associated setter
579 self._values[map_key] = v
580 else:
581 # The mapped value has a setter
582 setattr(self, map_key, v)
583 else:
584 # If the mapped value is not a @property
585 self._values[map_key] = v
586
587 def api_params(self):
588 result = {}
589 for api_attribute in self.api_attributes:
590 if self.api_map is not None and api_attribute in self.api_map:
591 result[api_attribute] = getattr(self, self.api_map[api_attribute])
592 else:
593 result[api_attribute] = getattr(self, api_attribute)
594 result = self._filter_params(result)
595 return result
596
597 def __getattr__(self, item):
598 # Ensures that properties that weren't defined, and therefore stashed
599 # in the `_values` dict, will be retrievable.
600 return self._values[item]
601
602 @property
603 def partition(self):
604 if self._values['partition'] is None:
605 return 'Common'
606 return self._values['partition'].strip('/')
607
608 @partition.setter
609 def partition(self, value):
610 self._values['partition'] = value
611
612 def _filter_params(self, params):
613 return dict((k, v) for k, v in iteritems(params) if v is not None)
614
615
616 class ImishConfig(NetworkConfig):
617 def add(self, lines, parents=None, duplicates=False):
618 ancestors = list()
619 offset = 0
620 obj = None
621
622 # global config command
623 if not parents:
624 for line in lines:
625 # handle ignore lines
626 if ignore_line(line):
627 continue
628
629 item = ConfigLine(line)
630 item.raw = line
631 if item not in self.items:
632 self.items.append(item)
633
634 else:
635 for index, p in enumerate(parents):
636 try:
637 i = index + 1
638 obj = self.get_block(parents[:i])[0]
639 ancestors.append(obj)
640
641 except ValueError:
642 # add parent to config
643 offset = index * self._indent
644 obj = ConfigLine(p)
645 obj.raw = p.rjust(len(p) + offset)
646 if ancestors:
647 obj._parents = list(ancestors)
648 ancestors[-1]._children.append(obj)
649 self.items.append(obj)
650 ancestors.append(obj)
651
652 # add child objects
653 for line in lines:
654 # handle ignore lines
655 if ignore_line(line):
656 continue
657
658 # check if child already exists
659 for child in ancestors[-1]._children:
660 if child.text == line and not duplicates:
661 break
662 else:
663 offset = len(parents) * self._indent
664 item = ConfigLine(line)
665 item.raw = line.rjust(len(line) + offset)
666 item._parents = ancestors
667 ancestors[-1]._children.append(item)
668 self.items.append(item)
669
670
671 class F5ModuleError(Exception):
672 pass