Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_message_routing_router
13 short_description: Manages router profiles for message-routing protocols
14 description:
15 - Manages router profiles for message-routing protocols.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the router profile.
21 required: True
22 type: str
23 description:
24 description:
25 - The user-defined description of the router profile.
26 type: str
27 type:
28 description:
29 - Parameter used to specify the type of the router profile to manage.
30 - Default setting is C(generic) with more options coming.
31 type: str
32 choices:
33 - generic
34 default: generic
35 parent:
36 description:
37 - The parent template of this router profile. Once this value has been set, it cannot be changed.
38 - The default values are set by the system if not specified and they correspond to the router type created,
39 for example, C(/Common/messagerouter) for C(generic) C(type) and so on.
40 type: str
41 ignore_client_port:
42 description:
43 - When C(true), the remote port on clientside connections (connections where the peer connected to the BIG-IP)
44 is ignored when searching for an existing connection.
45 type: bool
46 inherited_traffic_group:
47 description:
48 - When set to C(true), the C(traffic_group) is inherited from the containing folder. When not specified, the
49 system sets this to C(false) when creating new router profile.
50 type: bool
51 traffic_group:
52 description:
53 - Specifies the traffic-group of the router profile.
54 - Setting the C(traffic_group) to an empty string value C("") will cause the device to inherit from containing
55 folder, which means the value of C(inherited_traffic_group) on device will be C(true).
56 type: str
57 use_local_connection:
58 description:
59 - If C(true), the router will route a message to an existing connection on the same TMM as the message was
60 received.
61 type: bool
62 max_pending_bytes:
63 description:
64 - The maximum number of bytes worth of pending messages that will be held while waiting for a connection to a
65 peer to be created. Once reached, any additional messages to the peer will be flagged as undeliverable
66 and returned to the originator.
67 - The accepted range is between 0 and 4294967295 inclusive.
68 type: int
69 max_pending_messages:
70 description:
71 - The maximum number of pending messages that will be held while waiting for a connection to a peer to be created.
72 Once reached, any additional messages to the peer will be flagged as undeliverable and returned
73 to the originator.
74 - The accepted range is between 0 and 65535 inclusive.
75 type: int
76 max_retries:
77 description:
78 - Sets the maximum number of time a message may be resubmitted for rerouting by the C(MR::retry) iRule command.
79 - The accepted range is between 0 and 4294967295 inclusive.
80 type: int
81 mirror:
82 description:
83 - Enables or disables state mirroring. State mirroring can be used to maintain the same state information in the
84 standby unit that is in the active unit.
85 type: bool
86 mirrored_msg_sweeper_interval:
87 description:
88 - Specifies the maximum time in milliseconds that a message will be held on the standby device as it waits for
89 the active device to route the message.
90 - Messages on the standby device held for longer than the configurable sweeper interval, will be dropped.
91 - The acceptable range is between 0 and 4294967295 inclusive.
92 type: int
93 routes:
94 description:
95 - Specifies a list of static routes for the router instance to use.
96 - The route must be on the same partition as router profile.
97 type: list
98 elements: str
99 partition:
100 description:
101 - Device partition to create router profile on.
102 type: str
103 default: Common
104 state:
105 description:
106 - When C(present), ensures the router profile exists.
107 - When C(absent), ensures the router profile is removed.
108 type: str
109 choices:
110 - present
111 - absent
112 default: present
113 notes:
114 - Requires BIG-IP >= 14.0.0
115 extends_documentation_fragment: f5networks.f5_modules.f5
116 author:
117 - Wojciech Wypior (@wojtek0806)
118 '''
119
120 EXAMPLES = r'''
121 - name: Create a generic router profile
122 bigip_message_routing_router:
123 name: foo
124 max_retries: 10
125 ignore_client_port: true
126 routes:
127 - /Common/route1
128 - /Common/route2
129 provider:
130 password: secret
131 server: lb.mydomain.com
132 user: admin
133 delegate_to: localhost
134
135 - name: Modify a generic router profile
136 bigip_message_routing_router:
137 name: foo
138 ignore_client_port: false
139 mirror: true
140 mirrored_msg_sweeper_interval: 4000
141 traffic_group: /Common/traffic-group-2
142 provider:
143 password: secret
144 server: lb.mydomain.com
145 user: admin
146 delegate_to: localhost
147
148 - name: Remove a generic router profile
149 bigip_message_routing_router:
150 name: foo
151 state: absent
152 provider:
153 password: secret
154 server: lb.mydomain.com
155 user: admin
156 delegate_to: localhost
157 '''
158
159 RETURN = r'''
160 description:
161 description: The user-defined description of the router profile.
162 returned: changed
163 type: str
164 sample: My description
165 parent:
166 description: The parent template of this router profile.
167 returned: changed
168 type: str
169 sample: /Common/messagerouter
170 ignore_client_port:
171 description: Enables ignoring of the remote port on clientside connections when searching for an existing connection.
172 returned: changed
173 type: bool
174 sample: false
175 inherited_traffic_group:
176 description: Specifies if a traffic-group should be inherited from containing folder.
177 returned: changed
178 type: bool
179 sample: true
180 traffic_group:
181 description: The traffic-group of the router profile.
182 returned: changed
183 type: str
184 sample: /Common/traffic-group-1
185 use_local_connection:
186 description: Enables routing of messages to an existing connection on the same TMM as the message was received.
187 returned: changed
188 type: bool
189 sample: true
190 max_pending_bytes:
191 description: The maximum number of bytes worth of pending messages that will be held.
192 returned: changed
193 type: int
194 sample: 10000
195 max_pending_messages:
196 description: The maximum number of pending messages that will be held.
197 returned: changed
198 type: int
199 sample: 64
200 max_retries:
201 description: The maximum number of time a message may be resubmitted for rerouting.
202 returned: changed
203 type: int
204 sample: 10
205 mirror:
206 description: Enables or disables state mirroring.
207 returned: changed
208 type: bool
209 sample: true
210 mirrored_msg_sweeper_interval:
211 description: The maximum time in milliseconds that a message will be held on the standby device.
212 returned: changed
213 type: int
214 sample: 2000
215 routes:
216 description: The list of static routes for the router instance to use.
217 returned: changed
218 type: list
219 sample: ['/Common/route1', '/Common/route2']
220 '''
221 import traceback
222 from datetime import datetime
223
224 try:
225 from packaging.version import Version
226 except ImportError:
227 HAS_PACKAGING = False
228 Version = None
229 PACKAGING_IMPORT_ERROR = traceback.format_exc()
230 else:
231 HAS_PACKAGING = True
232 PACKAGING_IMPORT_ERROR = None
233
234 from ansible.module_utils.basic import (
235 AnsibleModule, missing_required_lib, env_fallback
236 )
237
238 from ..module_utils.bigip import F5RestClient
239 from ..module_utils.common import (
240 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
241 )
242 from ..module_utils.compare import (
243 cmp_str_with_none, cmp_simple_list
244 )
245 from ..module_utils.icontrol import tmos_version
246 from ..module_utils.teem import send_teem
247
248
249 class Parameters(AnsibleF5Parameters):
250 api_map = {
251 'defaultsFrom': 'parent',
252 'useLocalConnection': 'use_local_connection',
253 'ignoreClientPort': 'ignore_client_port',
254 'inheritedTrafficGroup': 'inherited_traffic_group',
255 'maxPendingBytes': 'max_pending_bytes',
256 'maxPendingMessages': 'max_pending_messages',
257 'maxRetries': 'max_retries',
258 'mirroredMessageSweeperInterval': 'mirrored_msg_sweeper_interval',
259 'trafficGroup': 'traffic_group',
260 }
261
262 api_attributes = [
263 'description',
264 'useLocalConnection',
265 'ignoreClientPort',
266 'inheritedTrafficGroup',
267 'maxPendingBytes',
268 'maxPendingMessages',
269 'maxRetries',
270 'mirror',
271 'mirroredMessageSweeperInterval',
272 'trafficGroup',
273 'routes',
274 'defaultsFrom',
275 ]
276
277 returnables = [
278 'parent',
279 'description',
280 'use_local_connection',
281 'ignore_client_port',
282 'inherited_traffic_group',
283 'max_pending_bytes',
284 'max_pending_messages',
285 'max_retries',
286 'mirrored_msg_sweeper_interval',
287 'traffic_group',
288 'mirror',
289 'routes',
290 ]
291
292 updatables = [
293 'description',
294 'use_local_connection',
295 'ignore_client_port',
296 'inherited_traffic_group',
297 'max_pending_bytes',
298 'max_pending_messages',
299 'max_retries',
300 'mirrored_msg_sweeper_interval',
301 'traffic_group',
302 'mirror',
303 'routes',
304 'parent',
305 ]
306
307 @property
308 def ignore_client_port(self):
309 return flatten_boolean(self._values['ignore_client_port'])
310
311 @property
312 def use_local_connection(self):
313 return flatten_boolean(self._values['use_local_connection'])
314
315
316 class ApiParameters(Parameters):
317 pass
318
319
320 class ModuleParameters(Parameters):
321 @property
322 def parent(self):
323 if self._values['parent'] is None:
324 return None
325 result = fq_name(self.partition, self._values['parent'])
326 return result
327
328 @property
329 def inherited_traffic_group(self):
330 result = flatten_boolean(self._values['inherited_traffic_group'])
331 if result is None:
332 return None
333 if result == 'yes':
334 return 'true'
335 return 'false'
336
337 @property
338 def mirror(self):
339 result = flatten_boolean(self._values['mirror'])
340 if result is None:
341 return None
342 if result == 'yes':
343 return 'enabled'
344 return 'disabled'
345
346 @property
347 def max_pending_bytes(self):
348 if self._values['max_pending_bytes'] is None:
349 return None
350 if 0 <= self._values['max_pending_bytes'] <= 4294967295:
351 return self._values['max_pending_bytes']
352 raise F5ModuleError(
353 "Valid 'max_pending_bytes' must be in range 0 - 4294967295 bytes."
354 )
355
356 @property
357 def max_retries(self):
358 if self._values['max_retries'] is None:
359 return None
360 if 0 <= self._values['max_retries'] <= 4294967295:
361 return self._values['max_retries']
362 raise F5ModuleError(
363 "Valid 'max_retries' must be in range 0 - 4294967295."
364 )
365
366 @property
367 def max_pending_messages(self):
368 if self._values['max_pending_messages'] is None:
369 return None
370 if 0 <= self._values['max_pending_messages'] <= 65535:
371 return self._values['max_pending_messages']
372 raise F5ModuleError(
373 "Valid 'max_pending_messages' must be in range 0 - 65535 messages."
374 )
375
376 @property
377 def mirrored_msg_sweeper_interval(self):
378 if self._values['mirrored_msg_sweeper_interval'] is None:
379 return None
380 if 0 <= self._values['mirrored_msg_sweeper_interval'] <= 4294967295:
381 return self._values['mirrored_msg_sweeper_interval']
382 raise F5ModuleError(
383 "Valid 'mirrored_msg_sweeper_interval' must be in range 0 - 4294967295 milliseconds."
384 )
385
386 @property
387 def routes(self):
388 if self._values['routes'] is None:
389 return None
390 if len(self._values['routes']) == 1 and self._values['routes'][0] == "":
391 return ""
392 result = [fq_name(self.partition, peer) for peer in self._values['routes']]
393 return result
394
395 @property
396 def traffic_group(self):
397 if self._values['traffic_group'] is None:
398 return None
399 if self._values['traffic_group'] == "":
400 return ""
401 result = fq_name('Common', self._values['traffic_group'])
402 return result
403
404
405 class Changes(Parameters):
406 def to_return(self):
407 result = {}
408 try:
409 for returnable in self.returnables:
410 result[returnable] = getattr(self, returnable)
411 result = self._filter_params(result)
412 except Exception:
413 raise
414 return result
415
416
417 class UsableChanges(Changes):
418 pass
419
420
421 class ReportableChanges(Changes):
422 @property
423 def mirror(self):
424 result = flatten_boolean(self._values['mirror'])
425 return result
426
427 @property
428 def inherited_traffic_group(self):
429 result = self._values['inherited_traffic_group']
430 if result == 'true':
431 return 'yes'
432 if result == 'false':
433 return 'no'
434 return None
435
436
437 class Difference(object):
438 def __init__(self, want, have=None):
439 self.want = want
440 self.have = have
441
442 def compare(self, param):
443 try:
444 result = getattr(self, param)
445 return result
446 except AttributeError:
447 return self.__default(param)
448
449 def __default(self, param):
450 attr1 = getattr(self.want, param)
451 try:
452 attr2 = getattr(self.have, param)
453 if attr1 != attr2:
454 return attr1
455 except AttributeError:
456 return attr1
457
458 @property
459 def description(self):
460 return cmp_str_with_none(self.want.description, self.have.description)
461
462 @property
463 def parent(self):
464 if self.want.parent is None:
465 return None
466 if self.want.parent != self.have.parent:
467 raise F5ModuleError(
468 "The parent router profile cannot be changed."
469 )
470
471 @property
472 def routes(self):
473 result = cmp_simple_list(self.want.routes, self.have.routes)
474 return result
475
476
477 class BaseManager(object):
478 def __init__(self, *args, **kwargs):
479 self.module = kwargs.get('module', None)
480 self.client = F5RestClient(**self.module.params)
481 self.want = ModuleParameters(params=self.module.params)
482 self.have = ApiParameters()
483 self.changes = UsableChanges()
484
485 def _set_changed_options(self):
486 changed = {}
487 for key in Parameters.returnables:
488 if getattr(self.want, key) is not None:
489 changed[key] = getattr(self.want, key)
490 if changed:
491 self.changes = UsableChanges(params=changed)
492
493 def _update_changed_options(self):
494 diff = Difference(self.want, self.have)
495 updatables = Parameters.updatables
496 changed = dict()
497 for k in updatables:
498 change = diff.compare(k)
499 if change is None:
500 continue
501 else:
502 if isinstance(change, dict):
503 changed.update(change)
504 else:
505 changed[k] = change
506 if changed:
507 self.changes = UsableChanges(params=changed)
508 return True
509 return False
510
511 def _announce_deprecations(self, result):
512 warnings = result.pop('__warnings', [])
513 for warning in warnings:
514 self.client.module.deprecate(
515 msg=warning['msg'],
516 version=warning['version']
517 )
518
519 def exec_module(self):
520 start = datetime.now().isoformat()
521 version = tmos_version(self.client)
522 changed = False
523 result = dict()
524 state = self.want.state
525
526 if state == "present":
527 changed = self.present()
528 elif state == "absent":
529 changed = self.absent()
530
531 reportable = ReportableChanges(params=self.changes.to_return())
532 changes = reportable.to_return()
533 result.update(**changes)
534 result.update(dict(changed=changed))
535 self._announce_deprecations(result)
536 send_teem(start, self.client, self.module, version)
537 return result
538
539 def present(self):
540 if self.exists():
541 return self.update()
542 else:
543 return self.create()
544
545 def absent(self):
546 if self.exists():
547 return self.remove()
548 return False
549
550 def should_update(self):
551 result = self._update_changed_options()
552 if result:
553 return True
554 return False
555
556 def update(self):
557 self.have = self.read_current_from_device()
558 if not self.should_update():
559 return False
560 if self.module.check_mode:
561 return True
562 self.update_on_device()
563 return True
564
565 def remove(self):
566 if self.module.check_mode:
567 return True
568 self.remove_from_device()
569 if self.exists():
570 raise F5ModuleError("Failed to delete the resource.")
571 return True
572
573 def create(self):
574 self._set_changed_options()
575 if self.module.check_mode:
576 return True
577 self.create_on_device()
578 return True
579
580
581 class GenericModuleManager(BaseManager):
582 def exists(self):
583 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/router/{2}".format(
584 self.client.provider['server'],
585 self.client.provider['server_port'],
586 transform_name(self.want.partition, self.want.name)
587 )
588 resp = self.client.api.get(uri)
589 try:
590 response = resp.json()
591 except ValueError as ex:
592 raise F5ModuleError(str(ex))
593
594 if resp.status == 404 or 'code' in response and response['code'] == 404:
595 return False
596 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
597 return True
598
599 errors = [401, 403, 409, 500, 501, 502, 503, 504]
600
601 if resp.status in errors or 'code' in response and response['code'] in errors:
602 if 'message' in response:
603 raise F5ModuleError(response['message'])
604 else:
605 raise F5ModuleError(resp.content)
606
607 def create_on_device(self):
608 params = self.changes.api_params()
609 params['name'] = self.want.name
610 params['partition'] = self.want.partition
611 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/router/".format(
612 self.client.provider['server'],
613 self.client.provider['server_port'],
614 )
615 resp = self.client.api.post(uri, json=params)
616 try:
617 response = resp.json()
618 except ValueError as ex:
619 raise F5ModuleError(str(ex))
620
621 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
622 return True
623 raise F5ModuleError(resp.content)
624
625 def update_on_device(self):
626 params = self.changes.api_params()
627 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/router/{2}".format(
628 self.client.provider['server'],
629 self.client.provider['server_port'],
630 transform_name(self.want.partition, self.want.name)
631 )
632 resp = self.client.api.patch(uri, json=params)
633 try:
634 response = resp.json()
635 except ValueError as ex:
636 raise F5ModuleError(str(ex))
637
638 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
639 return True
640 raise F5ModuleError(resp.content)
641
642 def remove_from_device(self):
643 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/router/{2}".format(
644 self.client.provider['server'],
645 self.client.provider['server_port'],
646 transform_name(self.want.partition, self.want.name)
647 )
648 response = self.client.api.delete(uri)
649 if response.status == 200:
650 return True
651 raise F5ModuleError(response.content)
652
653 def read_current_from_device(self):
654 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/router/{2}".format(
655 self.client.provider['server'],
656 self.client.provider['server_port'],
657 transform_name(self.want.partition, self.want.name)
658 )
659 resp = self.client.api.get(uri)
660 try:
661 response = resp.json()
662 except ValueError as ex:
663 raise F5ModuleError(str(ex))
664
665 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
666 return ApiParameters(params=response)
667 raise F5ModuleError(resp.content)
668
669
670 class ModuleManager(object):
671 def __init__(self, *args, **kwargs):
672 self.module = kwargs.get('module', None)
673 self.client = F5RestClient(**self.module.params)
674 self.kwargs = kwargs
675
676 def version_less_than_14(self):
677 version = tmos_version(self.client)
678 if Version(version) < Version('14.0.0'):
679 return True
680 return False
681
682 def exec_module(self):
683 if self.version_less_than_14():
684 raise F5ModuleError('Message routing is not supported on TMOS version below 14.x')
685 if self.module.params['type'] == 'generic':
686 manager = self.get_manager('generic')
687 else:
688 raise F5ModuleError(
689 "Unknown type specified."
690 )
691 return manager.exec_module()
692
693 def get_manager(self, type):
694 if type == 'generic':
695 return GenericModuleManager(**self.kwargs)
696
697
698 class ArgumentSpec(object):
699 def __init__(self):
700 self.supports_check_mode = True
701 argument_spec = dict(
702 name=dict(required=True),
703 description=dict(),
704 parent=dict(),
705 ignore_client_port=dict(type='bool'),
706 inherited_traffic_group=dict(type='bool'),
707 use_local_connection=dict(type='bool'),
708 max_pending_bytes=dict(type='int'),
709 max_pending_messages=dict(type='int'),
710 max_retries=dict(type='int'),
711 mirror=dict(type='bool'),
712 mirrored_msg_sweeper_interval=dict(type='int'),
713 routes=dict(
714 type='list',
715 elements='str',
716 ),
717 traffic_group=dict(),
718 type=dict(
719 choices=['generic'],
720 default='generic'
721 ),
722 partition=dict(
723 default='Common',
724 fallback=(env_fallback, ['F5_PARTITION'])
725 ),
726 state=dict(
727 default='present',
728 choices=['present', 'absent']
729 )
730
731 )
732 self.argument_spec = {}
733 self.argument_spec.update(f5_argument_spec)
734 self.argument_spec.update(argument_spec)
735
736
737 def main():
738 spec = ArgumentSpec()
739
740 module = AnsibleModule(
741 argument_spec=spec.argument_spec,
742 supports_check_mode=spec.supports_check_mode,
743 )
744
745 if not HAS_PACKAGING:
746 module.fail_json(
747 msg=missing_required_lib('packaging'),
748 exception=PACKAGING_IMPORT_ERROR
749 )
750
751 try:
752 mm = ModuleManager(module=module)
753 results = mm.exec_module()
754 module.exit_json(**results)
755 except F5ModuleError as ex:
756 module.fail_json(msg=str(ex))
757
758
759 if __name__ == '__main__':
760 main()