Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_message_routing_peer.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_peer
13 short_description: Manage peers for routing generic message protocol messages
14 description:
15 - Manage peers for routing generic message protocol messages.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the peer to manage.
21 type: str
22 required: True
23 description:
24 description:
25 - The user-defined description of the peer.
26 type: str
27 type:
28 description:
29 - Parameter used to specify the type of the peer to manage.
30 - Default setting is C(generic) with more options coming.
31 type: str
32 choices:
33 - generic
34 default: generic
35 auto_init:
36 description:
37 - If C(true), the BIG-IP automatically creates outbound connections to the active pool members in the
38 specified C(pool) using the configuration of the specified C(transport_config).
39 - For auto-initialization to attempt to create a connection, the peer must be included in a route that is attached
40 to a router instance. For each router instance the peer is contained in, a connection is initiated.
41 - The C(auto_init) logic verifies at C(auto_init_interval) if the a connection exists between
42 the BIG-IP and the pool members of the pool. If a connection does not exist, it attempts to reestablish one.
43 type: bool
44 auto_init_interval:
45 description:
46 - Specifies the interval at which attempts to initiate a connection occur.
47 - The default value upon peer object creation, that is supplied by the system is C(5000) milliseconds.
48 - The accepted range is between 0 and 4294967295 inclusive.
49 type: int
50 connection_mode:
51 description:
52 - Specifies how the number of connections per host are to be limited.
53 type: str
54 choices:
55 - per-blade
56 - per-client
57 - per-peer
58 - per-tmm
59 number_of_connections:
60 description:
61 - Specifies the distribution of connections between the BIG-IP and a remote host.
62 - The accepted range is between 0 and 65535 inclusive.
63 type: int
64 pool:
65 description:
66 - Specifies the name of the pool that messages are routed towards.
67 - The specified pool must be on the same partition as the peer.
68 type: str
69 ratio:
70 description:
71 - Specifies the ratio to be used for selection of a peer within a list of peers in a LTM route.
72 - The accepted range is between 0 and 4294967295 inclusive.
73 type: int
74 transport_config:
75 description:
76 - The name of the LTM virtual or LTM transport-config to use for creating an outgoing connection.
77 - The resource must exist on the same partition as the peer object.
78 type: str
79 partition:
80 description:
81 - Device partition to create peer object on.
82 type: str
83 default: Common
84 state:
85 description:
86 - When C(present), ensures the peer exists.
87 - When C(absent), ensures the peer is removed.
88 type: str
89 choices:
90 - present
91 - absent
92 default: present
93 notes:
94 - Requires BIG-IP >= 14.0.0
95 extends_documentation_fragment: f5networks.f5_modules.f5
96 author:
97 - Wojciech Wypior (@wojtek0806)
98 '''
99
100 EXAMPLES = r'''
101 - name: Create a simple peer
102 bigip_message_routing_peer:
103 name: foobar
104 provider:
105 password: secret
106 server: lb.mydomain.com
107 user: admin
108 delegate_to: localhost
109
110 - name: Create message routing peer with additional settings
111 bigip_message_routing_peer:
112 name: foobar
113 connection_mode: per-blade
114 pool: /baz/bar
115 partition: baz
116 transport_config: foovirtual
117 ratio: 10
118 auto_init: true
119 provider:
120 password: secret
121 server: lb.mydomain.com
122 user: admin
123 delegate_to: localhost
124
125 - name: Modify message routing peer settings
126 bigip_message_routing_peer:
127 name: foobar
128 partition: baz
129 ratio: 20
130 auto_init_interval: 2000
131 provider:
132 password: secret
133 server: lb.mydomain.com
134 user: admin
135 delegate_to: localhost
136
137 - name: Remove message routing peer
138 bigip_message_routing_peer:
139 name: foobar
140 partition: baz
141 state: absent
142 provider:
143 password: secret
144 server: lb.mydomain.com
145 user: admin
146 delegate_to: localhost
147 '''
148
149 RETURN = r'''
150 auto_init:
151 description: Enables creation of outbound connections to the active pool members.
152 returned: changed
153 type: bool
154 sample: true
155 auto_init_interval:
156 description: The interval at which attempts to initiate a connection occur.
157 returned: changed
158 type: int
159 sample: 2000
160 connection_mode:
161 description: Specifies how the number of connections per host are to be limited.
162 returned: changed
163 type: str
164 sample: per-peer
165 number_of_connections:
166 description: The distribution of connections between the BIG-IP and a remote host.
167 returned: changed
168 type: int
169 sample: 2000
170 transport_config:
171 description: The LTM virtual or LTM transport-config to use for creating an outgoing connection.
172 returned: changed
173 type: str
174 sample: /Common/foobar
175 description:
176 description: The user defined description of the peer.
177 returned: changed
178 type: str
179 sample: Some description
180 pool:
181 description: The name of the pool that messages are routed towards.
182 returned: changed
183 type: str
184 sample: /Bazbar/foobar
185 ratio:
186 description: The ratio to be used for selection of a peer within a list of peers in a LTM route.
187 returned: changed
188 type: int
189 sample: 500
190 '''
191 import traceback
192 from datetime import datetime
193
194 try:
195 from packaging.version import Version
196 except ImportError:
197 HAS_PACKAGING = False
198 Version = None
199 PACKAGING_IMPORT_ERROR = traceback.format_exc()
200 else:
201 HAS_PACKAGING = True
202 PACKAGING_IMPORT_ERROR = None
203
204 from ansible.module_utils.basic import (
205 AnsibleModule, missing_required_lib, env_fallback
206 )
207
208 from ..module_utils.bigip import F5RestClient
209 from ..module_utils.common import (
210 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
211 )
212 from ..module_utils.compare import cmp_str_with_none
213 from ..module_utils.icontrol import tmos_version
214 from ..module_utils.teem import send_teem
215
216
217 class Parameters(AnsibleF5Parameters):
218 api_map = {
219 'autoInitialization': 'auto_init',
220 'autoInitializationInterval': 'auto_init_interval',
221 'connectionMode': 'connection_mode',
222 'numberConnections': 'number_of_connections',
223 'transportConfig': 'transport_config',
224 }
225
226 api_attributes = [
227 'autoInitialization',
228 'autoInitializationInterval',
229 'connectionMode',
230 'description',
231 'numberConnections',
232 'pool',
233 'ratio',
234 'transportConfig',
235 ]
236
237 returnables = [
238 'auto_init',
239 'auto_init_interval',
240 'connection_mode',
241 'number_of_connections',
242 'transport_config',
243 'description',
244 'pool',
245 'ratio',
246 ]
247
248 updatables = [
249 'auto_init',
250 'auto_init_interval',
251 'connection_mode',
252 'number_of_connections',
253 'transport_config',
254 'description',
255 'pool',
256 'ratio',
257 ]
258
259
260 class ApiParameters(Parameters):
261 pass
262
263
264 class ModuleParameters(Parameters):
265 @property
266 def auto_init(self):
267 result = flatten_boolean(self._values['auto_init'])
268 if result is None:
269 return None
270 if result == 'yes':
271 return 'enabled'
272 return 'disabled'
273
274 @property
275 def auto_init_interval(self):
276 if self._values['auto_init_interval'] is None:
277 return None
278 if 0 <= self._values['auto_init_interval'] <= 4294967295:
279 return self._values['auto_init_interval']
280 raise F5ModuleError(
281 "Valid 'auto_init_interval' must be in range 0 - 4294967295 milliseconds."
282 )
283
284 @property
285 def number_of_connections(self):
286 if self._values['number_of_connections'] is None:
287 return None
288 if 0 <= self._values['number_of_connections'] <= 65535:
289 return self._values['number_of_connections']
290 raise F5ModuleError(
291 "Valid 'number_of_connections' must be in range 0 - 65535."
292 )
293
294 @property
295 def ratio(self):
296 if self._values['ratio'] is None:
297 return None
298 if 0 <= self._values['ratio'] <= 4294967295:
299 return self._values['ratio']
300 raise F5ModuleError(
301 "Valid 'ratio' must be in range 0 - 4294967295."
302 )
303
304 @property
305 def pool(self):
306 if self._values['pool'] is None:
307 return None
308 if self._values['pool'] == "":
309 return ""
310 result = fq_name(self.partition, self._values['pool'])
311 return result
312
313 @property
314 def transport_config(self):
315 if self._values['transport_config'] is None:
316 return None
317 if self._values['transport_config'] == "":
318 return ""
319 result = fq_name(self.partition, self._values['transport_config'])
320 return result
321
322
323 class Changes(Parameters):
324 def to_return(self):
325 result = {}
326 try:
327 for returnable in self.returnables:
328 result[returnable] = getattr(self, returnable)
329 result = self._filter_params(result)
330 except Exception:
331 raise
332 return result
333
334
335 class UsableChanges(Changes):
336 pass
337
338
339 class ReportableChanges(Changes):
340 @property
341 def auto_init(self):
342 result = flatten_boolean(self._values['auto_init'])
343 return result
344
345
346 class Difference(object):
347 def __init__(self, want, have=None):
348 self.want = want
349 self.have = have
350
351 def compare(self, param):
352 try:
353 result = getattr(self, param)
354 return result
355 except AttributeError:
356 return self.__default(param)
357
358 def __default(self, param):
359 attr1 = getattr(self.want, param)
360 try:
361 attr2 = getattr(self.have, param)
362 if attr1 != attr2:
363 return attr1
364 except AttributeError:
365 return attr1
366
367 @property
368 def description(self):
369 result = cmp_str_with_none(self.want.description, self.have.description)
370 return result
371
372 @property
373 def transport_config(self):
374 result = cmp_str_with_none(self.want.transport_config, self.have.transport_config)
375 return result
376
377 @property
378 def pool(self):
379 result = cmp_str_with_none(self.want.pool, self.have.pool)
380 return result
381
382
383 class BaseManager(object):
384 def __init__(self, *args, **kwargs):
385 self.module = kwargs.get('module', None)
386 self.client = F5RestClient(**self.module.params)
387 self.want = ModuleParameters(params=self.module.params)
388 self.have = ApiParameters()
389 self.changes = UsableChanges()
390
391 def _set_changed_options(self):
392 changed = {}
393 for key in Parameters.returnables:
394 if getattr(self.want, key) is not None:
395 changed[key] = getattr(self.want, key)
396 if changed:
397 self.changes = UsableChanges(params=changed)
398
399 def _update_changed_options(self):
400 diff = Difference(self.want, self.have)
401 updatables = Parameters.updatables
402 changed = dict()
403 for k in updatables:
404 change = diff.compare(k)
405 if change is None:
406 continue
407 else:
408 if isinstance(change, dict):
409 changed.update(change)
410 else:
411 changed[k] = change
412 if changed:
413 self.changes = UsableChanges(params=changed)
414 return True
415 return False
416
417 def _announce_deprecations(self, result):
418 warnings = result.pop('__warnings', [])
419 for warning in warnings:
420 self.client.module.deprecate(
421 msg=warning['msg'],
422 version=warning['version']
423 )
424
425 def exec_module(self):
426 start = datetime.now().isoformat()
427 version = tmos_version(self.client)
428 changed = False
429 result = dict()
430 state = self.want.state
431
432 if state == "present":
433 changed = self.present()
434 elif state == "absent":
435 changed = self.absent()
436
437 reportable = ReportableChanges(params=self.changes.to_return())
438 changes = reportable.to_return()
439 result.update(**changes)
440 result.update(dict(changed=changed))
441 self._announce_deprecations(result)
442 send_teem(start, self.client, self.module, version)
443 return result
444
445 def present(self):
446 if self.exists():
447 return self.update()
448 else:
449 return self.create()
450
451 def absent(self):
452 if self.exists():
453 return self.remove()
454 return False
455
456 def should_update(self):
457 result = self._update_changed_options()
458 if result:
459 return True
460 return False
461
462 def update(self):
463 self.have = self.read_current_from_device()
464 if not self.should_update():
465 return False
466 if self.module.check_mode:
467 return True
468 self.update_on_device()
469 return True
470
471 def remove(self):
472 if self.module.check_mode:
473 return True
474 self.remove_from_device()
475 if self.exists():
476 raise F5ModuleError("Failed to delete the resource.")
477 return True
478
479 def create(self):
480 self._set_changed_options()
481 if self.module.check_mode:
482 return True
483 self.create_on_device()
484 return True
485
486
487 class GenericModuleManager(BaseManager):
488 def exists(self):
489 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/peer/{2}".format(
490 self.client.provider['server'],
491 self.client.provider['server_port'],
492 transform_name(self.want.partition, self.want.name)
493 )
494 resp = self.client.api.get(uri)
495 try:
496 response = resp.json()
497 except ValueError as ex:
498 raise F5ModuleError(str(ex))
499
500 if resp.status == 404 or 'code' in response and response['code'] == 404:
501 return False
502 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
503 return True
504
505 errors = [401, 403, 409, 500, 501, 502, 503, 504]
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 def create_on_device(self):
514 params = self.changes.api_params()
515 params['name'] = self.want.name
516 params['partition'] = self.want.partition
517 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/peer/".format(
518 self.client.provider['server'],
519 self.client.provider['server_port'],
520 )
521 resp = self.client.api.post(uri, json=params)
522 try:
523 response = resp.json()
524 except ValueError as ex:
525 raise F5ModuleError(str(ex))
526
527 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
528 return True
529 raise F5ModuleError(resp.content)
530
531 def update_on_device(self):
532 params = self.changes.api_params()
533 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/peer/{2}".format(
534 self.client.provider['server'],
535 self.client.provider['server_port'],
536 transform_name(self.want.partition, self.want.name)
537 )
538 resp = self.client.api.patch(uri, json=params)
539 try:
540 response = resp.json()
541 except ValueError as ex:
542 raise F5ModuleError(str(ex))
543
544 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
545 return True
546 raise F5ModuleError(resp.content)
547
548 def remove_from_device(self):
549 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/peer/{2}".format(
550 self.client.provider['server'],
551 self.client.provider['server_port'],
552 transform_name(self.want.partition, self.want.name)
553 )
554 response = self.client.api.delete(uri)
555 if response.status == 200:
556 return True
557 raise F5ModuleError(response.content)
558
559 def read_current_from_device(self):
560 uri = "https://{0}:{1}/mgmt/tm/ltm/message-routing/generic/peer/{2}".format(
561 self.client.provider['server'],
562 self.client.provider['server_port'],
563 transform_name(self.want.partition, self.want.name)
564 )
565 resp = self.client.api.get(uri)
566 try:
567 response = resp.json()
568 except ValueError as ex:
569 raise F5ModuleError(str(ex))
570
571 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
572 return ApiParameters(params=response)
573 raise F5ModuleError(resp.content)
574
575
576 class ModuleManager(object):
577 def __init__(self, *args, **kwargs):
578 self.module = kwargs.get('module', None)
579 self.client = F5RestClient(**self.module.params)
580 self.kwargs = kwargs
581
582 def version_less_than_14(self):
583 version = tmos_version(self.client)
584 if Version(version) < Version('14.0.0'):
585 return True
586 return False
587
588 def exec_module(self):
589 if self.version_less_than_14():
590 raise F5ModuleError('Message routing is not supported on TMOS version below 14.x')
591 if self.module.params['type'] == 'generic':
592 manager = self.get_manager('generic')
593 else:
594 raise F5ModuleError(
595 "Unknown type specified."
596 )
597 return manager.exec_module()
598
599 def get_manager(self, type):
600 if type == 'generic':
601 return GenericModuleManager(**self.kwargs)
602
603
604 class ArgumentSpec(object):
605 def __init__(self):
606 self.supports_check_mode = True
607 argument_spec = dict(
608 name=dict(required=True),
609 auto_init=dict(type='bool'),
610 auto_init_interval=dict(type='int'),
611 connection_mode=dict(
612 choices=['per-blade', 'per-client', 'per-peer', 'per-tmm']
613 ),
614 description=dict(),
615 number_of_connections=dict(type='int'),
616 pool=dict(),
617 ratio=dict(type='int'),
618 transport_config=dict(),
619 type=dict(
620 choices=['generic'],
621 default='generic'
622 ),
623 partition=dict(
624 default='Common',
625 fallback=(env_fallback, ['F5_PARTITION'])
626 ),
627 state=dict(
628 default='present',
629 choices=['present', 'absent']
630 )
631 )
632 self.required_if = [
633 ['auto_init', True, ['transport_config']]
634 ]
635 self.argument_spec = {}
636 self.argument_spec.update(f5_argument_spec)
637 self.argument_spec.update(argument_spec)
638
639
640 def main():
641 spec = ArgumentSpec()
642
643 module = AnsibleModule(
644 argument_spec=spec.argument_spec,
645 supports_check_mode=spec.supports_check_mode,
646 required_if=spec.required_if,
647 )
648
649 if not HAS_PACKAGING:
650 module.fail_json(
651 msg=missing_required_lib('packaging'),
652 exception=PACKAGING_IMPORT_ERROR
653 )
654
655 try:
656 mm = ModuleManager(module=module)
657 results = mm.exec_module()
658 module.exit_json(**results)
659 except F5ModuleError as ex:
660 module.fail_json(msg=str(ex))
661
662
663 if __name__ == '__main__':
664 main()