Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_monitor_icmp.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_monitor_icmp
13 short_description: Manages F5 BIG-IP LTM ICMP monitors
14 description:
15 - Manages ICMP monitors on a BIG-IP.
16 version_added: "1.1.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the monitor.
21 type: str
22 required: True
23 app_service:
24 description:
25 - The iApp service to be associated with this profile. When no service is
26 specified, the default is None.
27 type: str
28 parent:
29 description:
30 - The parent template of this monitor template. Once this value has
31 been set, it cannot be changed.
32 - When creating a new monitor, if this parameter is not specified, the default
33 is the system-supplied C(icmp) monitor.
34 type: str
35 description:
36 description:
37 - The description of the monitor.
38 type: str
39 ip:
40 description:
41 - Specifies the IP address of the resource that is the destination of this monitor.
42 - When set to B(*), the device performs a health check on the IP address of the node.
43 - "When set to an B(<IP>) the device performs a health check on that IP address and marks the associated node up
44 or down as a result of the response. This option is set by the device by default when not defined during monitor
45 creation."
46 - "When set to an B(<IP>) and C(transparent) is C(true), the device performs a health check on that IP address,
47 routes the check through the associated node IP address, and marks the associated node IP address up or down
48 accordingly."
49 type: str
50 interval:
51 description:
52 - Specifies the frequency, in seconds, at which the system issues the
53 monitor check when either the resource is down or the status of the
54 resource is unknown.
55 type: int
56 timeout:
57 description:
58 - Specifies the number of seconds the target has in which to respond to
59 the monitor request.
60 - If the target responds within the set time period, it is considered 'up'.
61 If the target does not respond within the set time period, it is considered
62 'down'. When this value is set to 0 (zero), the system uses the interval
63 from the parent monitor.
64 - Note that C(timeout) and C(time_until_up) combine to control when a
65 resource is set to up.
66 type: int
67 time_until_up:
68 description:
69 - Specifies the number of seconds to wait after a resource first responds
70 correctly to the monitor before setting the resource to 'up'.
71 - During the interval, all responses from the resource must be correct.
72 - When the interval expires, the resource is marked 'up'.
73 - A value of 0 means the resource is marked up immediately upon
74 receipt of the first correct response.
75 type: int
76 up_interval:
77 description:
78 - Specifies the interval for the system to use to perform the health check
79 when a resource is up.
80 - When C(0), specifies the system uses the interval specified in
81 C(interval) to check the health of the resource.
82 - When any other number, enables you to specify a different interval to
83 use when checking the health of a resource that is up.
84 type: int
85 manual_resume:
86 description:
87 - Specifies whether the system automatically changes the status of a resource
88 to B(enabled) at the next successful monitor check.
89 - If you set this option to C(true), you must manually re-enable the resource
90 before the system can use it for load balancing connections.
91 - When C(true), specifies you must manually re-enable the resource after an
92 unsuccessful monitor check.
93 - When C(false), specifies the system automatically changes the status of a
94 resource to B(enabled) at the next successful monitor check.
95 type: bool
96 adaptive:
97 description:
98 - Specifies whether adaptive response time monitoring is enabled for this monitor.
99 - When C(true), the monitor determines the state of a service based on how divergent
100 from the mean latency a monitor probe for that service is allowed to be.
101 Also, values for the C(allowed_divergence), C(adaptive_limit), and
102 and C(sampling_timespan) will be enforced.
103 - When C(disabled), the monitor determines the state of a service based on the
104 C(interval), C(up_interval), C(time_until_up), and C(timeout) monitor settings.
105 type: bool
106 allowed_divergence_type:
107 description:
108 - When specifying a new monitor, if C(adaptive) is C(true), the default is
109 C(relative).
110 - When C(absolute), the number of milliseconds the latency of a monitor probe
111 can exceed the mean latency of a monitor probe for the service being probed.
112 In typical cases, if the monitor detects three probes in a row that miss the
113 latency value you set, the pool member or node is marked down.
114 - When C(relative), the percentage of deviation the latency of a monitor probe
115 can exceed the mean latency of a monitor probe for the service being probed.
116 type: str
117 choices:
118 - relative
119 - absolute
120 allowed_divergence_value:
121 description:
122 - When specifying a new monitor, if C(adaptive) is C(true), and C(type) is
123 C(relative), the default is C(25) percent.
124 type: int
125 adaptive_limit:
126 description:
127 - Specifies the absolute number of milliseconds that may not be exceeded by a monitor
128 probe, regardless of C(allowed_divergence) setting, for a probe to be
129 considered successful.
130 - This value applies regardless of the value of the C(allowed_divergence) setting.
131 - While this value can be configured when C(adaptive) is C(false), it will not take
132 effect on the system until C(adaptive) is C(true).
133 type: int
134 sampling_timespan:
135 description:
136 - Specifies the length, in seconds, of the probe history window the system
137 uses to calculate the mean latency and standard deviation of a monitor probe.
138 - While this value can be configured when C(adaptive) is C(false), it will not take
139 effect on the system until C(adaptive) is C(true).
140 type: int
141 transparent:
142 description:
143 - Specifies whether the monitor operates in transparent mode.
144 - A monitor in transparent mode directs traffic through the associated pool members
145 or nodes (usually a router or firewall) to the aliased destination (that is, it
146 probes the C(ip)-C(port) combination specified in the monitor).
147 - If the monitor cannot successfully reach the aliased destination, the pool member
148 or node through which the monitor traffic was sent is marked down.
149 - When creating a new monitor, if this parameter is not provided, the default
150 value will be whatever is provided by the C(parent).
151 type: bool
152 partition:
153 description:
154 - Device partition to manage resources on.
155 type: str
156 default: Common
157 state:
158 description:
159 - When C(present), ensures that the monitor exists.
160 - When C(absent), ensures the monitor is removed.
161 type: str
162 choices:
163 - present
164 - absent
165 default: present
166 extends_documentation_fragment: f5networks.f5_modules.f5
167 author:
168 - Wojciech Wypior (@wojtek0806)
169 '''
170
171 EXAMPLES = r'''
172 - name: Create an ICMP monitor
173 bigip_monitor_icmp:
174 name: icmp1
175 adaptive: false
176 interval: 1
177 time_until_up: 0
178 timeout: 3
179 provider:
180 password: secret
181 server: lb.mydomain.com
182 user: admin
183 delegate_to: localhost
184
185 - name: Update an ICMP monitor
186 bigip_monitor_icmp:
187 name: icmp1
188 manual_resume: true
189 interval: 5
190 provider:
191 password: secret
192 server: lb.mydomain.com
193 user: admin
194 delegate_to: localhost
195
196 - name: Remove an ICMP monitor
197 bigip_monitor_icmp:
198 name: icmp1
199 state: absent
200 provider:
201 password: secret
202 server: lb.mydomain.com
203 user: admin
204 delegate_to: localhost
205 '''
206
207 RETURN = r'''
208 app_service:
209 description: The iApp service associated with this monitor.
210 returned: changed
211 type: str
212 sample: /Common/good_service.app/good_service
213 parent:
214 description: New parent template of the monitor.
215 returned: changed
216 type: str
217 sample: gateway-icmp
218 ip:
219 description: The new IP of IP/port definition.
220 returned: changed
221 type: str
222 sample: 10.12.13.14
223 interval:
224 description: The new interval in which to run the monitor check.
225 returned: changed
226 type: int
227 sample: 2
228 timeout:
229 description: The new timeout in which the remote system must respond to the monitor.
230 returned: changed
231 type: int
232 sample: 10
233 time_until_up:
234 description: The new time in which to mark a system as up after first successful response.
235 returned: changed
236 type: int
237 sample: 2
238 adaptive:
239 description: Whether adaptive is enabled or not.
240 returned: changed
241 type: bool
242 sample: true
243 allowed_divergence_type:
244 description: Type of divergence used for adaptive response time monitoring.
245 returned: changed
246 type: str
247 sample: absolute
248 allowed_divergence_value:
249 description:
250 - Value of the type of divergence used for adaptive response time monitoring.
251 - May be C(percent) or C(ms) depending on whether C(relative) or C(absolute).
252 returned: changed
253 type: int
254 sample: 25
255 description:
256 description: The description of the monitor.
257 returned: changed
258 type: str
259 sample: Important Monitor
260 adaptive_limit:
261 description: Absolute number of milliseconds that may not be exceeded by a monitor probe.
262 returned: changed
263 type: int
264 sample: 200
265 sampling_timespan:
266 description: Absolute number of milliseconds that may not be exceeded by a monitor probe.
267 returned: changed
268 type: int
269 sample: 200
270 up_interval:
271 description: Interval for the system to use to perform the health check when a resource is up.
272 returned: changed
273 type: int
274 sample: 0
275 port:
276 description:
277 - Alias port or service for the monitor to check, on behalf of the pools or pool
278 members with which the monitor is associated.
279 returned: changed
280 type: str
281 sample: 80
282 transparent:
283 description: Whether the monitor operates in transparent mode.
284 returned: changed
285 type: bool
286 sample: false
287 '''
288 from datetime import datetime
289
290 from ansible.module_utils.basic import (
291 AnsibleModule, env_fallback
292 )
293
294 from ..module_utils.bigip import F5RestClient
295 from ..module_utils.common import (
296 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
297 )
298 from ..module_utils.compare import cmp_str_with_none
299 from ..module_utils.ipaddress import is_valid_ip
300 from ..module_utils.icontrol import tmos_version
301 from ..module_utils.teem import send_teem
302
303
304 class Parameters(AnsibleF5Parameters):
305 api_map = {
306 'appService': 'app_service',
307 'adaptiveDivergenceType': 'allowed_divergence_type',
308 'adaptiveDivergenceValue': 'allowed_divergence_value',
309 'adaptiveLimit': 'adaptive_limit',
310 'adaptiveSamplingTimespan': 'sampling_timespan',
311 'timeUntilUp': 'time_until_up',
312 'upInterval': 'up_interval',
313 'defaultsFrom': 'parent',
314 'destination': 'ip',
315 }
316
317 api_attributes = [
318 'adaptive',
319 'adaptiveDivergenceType',
320 'adaptiveDivergenceValue',
321 'adaptiveLimit',
322 'adaptiveSamplingTimespan',
323 'defaultsFrom',
324 'description',
325 'destination',
326 'interval',
327 'manualResume',
328 'timeout',
329 'timeUntilUp',
330 'transparent',
331 'upInterval',
332 'destination',
333 'appService',
334 ]
335
336 returnables = [
337 'app_service',
338 'adaptive',
339 'allowed_divergence_type',
340 'allowed_divergence_value',
341 'description',
342 'adaptive_limit',
343 'sampling_timespan',
344 'manual_resume',
345 'time_until_up',
346 'up_interval',
347 'timeout',
348 'interval',
349 'transparent',
350 'parent',
351 'ip',
352 ]
353
354 updatables = [
355 'app_service',
356 'adaptive',
357 'allowed_divergence_type',
358 'allowed_divergence_value',
359 'adaptive_limit',
360 'sampling_timespan',
361 'description',
362 'manual_resume',
363 'time_until_up',
364 'up_interval',
365 'timeout',
366 'interval',
367 'transparent',
368 'ip',
369 'interval',
370 ]
371
372
373 class ApiParameters(Parameters):
374 @property
375 def description(self):
376 if self._values['description'] in [None, 'none']:
377 return None
378 return self._values['description']
379
380
381 class ModuleParameters(Parameters):
382 @property
383 def description(self):
384 if self._values['description'] is None:
385 return None
386 elif self._values['description'] in ['none', '']:
387 return ''
388 return self._values['description']
389
390 @property
391 def parent(self):
392 if self._values['parent'] is None:
393 return None
394 result = fq_name(self.partition, self._values['parent'])
395 return result
396
397 @property
398 def interval(self):
399 if self._values['interval'] is None:
400 return None
401 if 1 > self._values['interval'] > 86400:
402 raise F5ModuleError(
403 "Interval value must be between 1 and 86400."
404 )
405 return self._values['interval']
406
407 @property
408 def timeout(self):
409 if self._values['timeout'] is None:
410 return None
411 if self._values['timeout'] is None:
412 return None
413 if 1 > self._values['timeout'] > 86400:
414 raise F5ModuleError(
415 "Timeout value must be between 1 and 86400."
416 )
417 return self._values['timeout']
418
419 @property
420 def ip(self):
421 if self._values['ip'] is None:
422 return None
423 if self._values['ip'] in ['*', '0.0.0.0']:
424 return '*'
425 elif is_valid_ip(self._values['ip']) or is_valid_ip(self._values['ip'].split("%")[0]):
426 return self._values['ip']
427 else:
428 raise F5ModuleError(
429 "The provided 'ip' parameter is not an IP address."
430 )
431
432 @property
433 def time_until_up(self):
434 if self._values['time_until_up'] is None:
435 return None
436 if self._values['time_until_up'] is None:
437 return None
438 if 0 > self._values['time_until_up'] > 86400:
439 raise F5ModuleError(
440 "Time_until_up value must be between 0 and 86400."
441 )
442 return self._values['time_until_up']
443
444 @property
445 def manual_resume(self):
446 result = flatten_boolean(self._values['manual_resume'])
447 if result == 'yes':
448 return 'enabled'
449 if result == 'no':
450 return 'disabled'
451
452 @property
453 def transparent(self):
454 result = flatten_boolean(self._values['transparent'])
455 if result == 'yes':
456 return 'enabled'
457 if result == 'no':
458 return 'disabled'
459
460 @property
461 def adaptive(self):
462 result = flatten_boolean(self._values['adaptive'])
463 if result == 'yes':
464 return 'enabled'
465 if result == 'no':
466 return 'disabled'
467
468
469 class Changes(Parameters):
470 def to_return(self):
471 result = {}
472 try:
473 for returnable in self.returnables:
474 result[returnable] = getattr(self, returnable)
475 result = self._filter_params(result)
476 except Exception:
477 raise
478 return result
479
480
481 class UsableChanges(Changes):
482 pass
483
484
485 class ReportableChanges(Changes):
486 @property
487 def manual_resume(self):
488 return flatten_boolean(self._values['manual_resume'])
489
490 @property
491 def transparent(self):
492 return flatten_boolean(self._values['transparent'])
493
494 @property
495 def adaptive(self):
496 return flatten_boolean(self._values['adaptive'])
497
498
499 class Difference(object):
500 def __init__(self, want, have=None):
501 self.want = want
502 self.have = have
503
504 def compare(self, param):
505 try:
506 result = getattr(self, param)
507 return result
508 except AttributeError:
509 return self.__default(param)
510
511 def __default(self, param):
512 attr1 = getattr(self.want, param)
513 try:
514 attr2 = getattr(self.have, param)
515 if attr1 != attr2:
516 return attr1
517 except AttributeError:
518 return attr1
519
520 @property
521 def interval(self):
522 if self.want.timeout is not None and self.want.interval is not None:
523 if self.want.interval >= self.want.timeout:
524 raise F5ModuleError(
525 "Parameter 'interval' must be less than 'timeout'."
526 )
527 elif self.want.timeout is not None:
528 if self.have.interval >= self.want.timeout:
529 raise F5ModuleError(
530 "Parameter 'interval' must be less than 'timeout'."
531 )
532 elif self.want.interval is not None:
533 if self.want.interval >= self.have.timeout:
534 raise F5ModuleError(
535 "Parameter 'interval' must be less than 'timeout'."
536 )
537 if self.want.interval != self.have.interval:
538 return self.want.interval
539
540 @property
541 def description(self):
542 return cmp_str_with_none(self.want.description, self.have.description)
543
544
545 class ModuleManager(object):
546 def __init__(self, *args, **kwargs):
547 self.module = kwargs.get('module', None)
548 self.client = F5RestClient(**self.module.params)
549 self.want = ModuleParameters(params=self.module.params)
550 self.have = ApiParameters()
551 self.changes = UsableChanges()
552
553 def _set_changed_options(self):
554 changed = {}
555 for key in Parameters.returnables:
556 if getattr(self.want, key) is not None:
557 changed[key] = getattr(self.want, key)
558 if changed:
559 self.changes = UsableChanges(params=changed)
560
561 def _update_changed_options(self):
562 diff = Difference(self.want, self.have)
563 updatables = Parameters.updatables
564 changed = dict()
565 for k in updatables:
566 change = diff.compare(k)
567 if change is None:
568 continue
569 else:
570 if isinstance(change, dict):
571 changed.update(change)
572 else:
573 changed[k] = change
574 if changed:
575 self.changes = UsableChanges(params=changed)
576 return True
577 return False
578
579 def _announce_deprecations(self, result):
580 warnings = result.pop('__warnings', [])
581 for warning in warnings:
582 self.client.module.deprecate(
583 msg=warning['msg'],
584 version=warning['version']
585 )
586
587 def exec_module(self):
588 start = datetime.now().isoformat()
589 version = tmos_version(self.client)
590 changed = False
591 result = dict()
592 state = self.want.state
593
594 if state == "present":
595 changed = self.present()
596 elif state == "absent":
597 changed = self.absent()
598
599 reportable = ReportableChanges(params=self.changes.to_return())
600 changes = reportable.to_return()
601 result.update(**changes)
602 result.update(dict(changed=changed))
603 self._announce_deprecations(result)
604 send_teem(start, self.client, self.module, version)
605 return result
606
607 def present(self):
608 if self.exists():
609 return self.update()
610 else:
611 return self.create()
612
613 def absent(self):
614 if self.exists():
615 return self.remove()
616 return False
617
618 def should_update(self):
619 result = self._update_changed_options()
620 if result:
621 return True
622 return False
623
624 def update(self):
625 self.have = self.read_current_from_device()
626 if not self.should_update():
627 return False
628 if self.module.check_mode:
629 return True
630 self.update_on_device()
631 return True
632
633 def remove(self):
634 if self.module.check_mode:
635 return True
636 self.remove_from_device()
637 if self.exists():
638 raise F5ModuleError("Failed to delete the resource.")
639 return True
640
641 def create(self):
642 self._set_changed_options()
643 if self.module.check_mode:
644 return True
645 self.create_on_device()
646 return True
647
648 def exists(self):
649 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/icmp/{2}".format(
650 self.client.provider['server'],
651 self.client.provider['server_port'],
652 transform_name(self.want.partition, self.want.name)
653 )
654 resp = self.client.api.get(uri)
655 try:
656 response = resp.json()
657 except ValueError as ex:
658 raise F5ModuleError(str(ex))
659
660 if resp.status == 404 or 'code' in response and response['code'] == 404:
661 return False
662 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
663 return True
664
665 errors = [401, 403, 409, 500, 501, 502, 503, 504]
666
667 if resp.status in errors or 'code' in response and response['code'] in errors:
668 if 'message' in response:
669 raise F5ModuleError(response['message'])
670 else:
671 raise F5ModuleError(resp.content)
672
673 def create_on_device(self):
674 params = self.changes.api_params()
675 params['name'] = self.want.name
676 params['partition'] = self.want.partition
677 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/icmp/".format(
678 self.client.provider['server'],
679 self.client.provider['server_port'],
680 )
681 resp = self.client.api.post(uri, json=params)
682 try:
683 response = resp.json()
684 except ValueError as ex:
685 raise F5ModuleError(str(ex))
686
687 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
688 return True
689 raise F5ModuleError(resp.content)
690
691 def update_on_device(self):
692 params = self.changes.api_params()
693 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/icmp/{2}".format(
694 self.client.provider['server'],
695 self.client.provider['server_port'],
696 transform_name(self.want.partition, self.want.name)
697 )
698 resp = self.client.api.patch(uri, json=params)
699 try:
700 response = resp.json()
701 except ValueError as ex:
702 raise F5ModuleError(str(ex))
703
704 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
705 return True
706 raise F5ModuleError(resp.content)
707
708 def remove_from_device(self):
709 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/icmp/{2}".format(
710 self.client.provider['server'],
711 self.client.provider['server_port'],
712 transform_name(self.want.partition, self.want.name)
713 )
714 response = self.client.api.delete(uri)
715 if response.status == 200:
716 return True
717 raise F5ModuleError(response.content)
718
719 def read_current_from_device(self):
720 uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/icmp/{2}".format(
721 self.client.provider['server'],
722 self.client.provider['server_port'],
723 transform_name(self.want.partition, self.want.name)
724 )
725 resp = self.client.api.get(uri)
726 try:
727 response = resp.json()
728 except ValueError as ex:
729 raise F5ModuleError(str(ex))
730
731 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
732 return ApiParameters(params=response)
733 raise F5ModuleError(resp.content)
734
735
736 class ArgumentSpec(object):
737 def __init__(self):
738 self.supports_check_mode = True
739 argument_spec = dict(
740 name=dict(required=True),
741 app_service=dict(),
742 parent=dict(),
743 ip=dict(),
744 description=dict(),
745 interval=dict(type='int'),
746 timeout=dict(type='int'),
747 time_until_up=dict(type='int'),
748 up_interval=dict(type='int'),
749 manual_resume=dict(type='bool'),
750 adaptive=dict(type='bool'),
751 allowed_divergence_type=dict(choices=['relative', 'absolute']),
752 allowed_divergence_value=dict(type='int'),
753 adaptive_limit=dict(type='int'),
754 sampling_timespan=dict(type='int'),
755 transparent=dict(type='bool'),
756 state=dict(
757 default='present',
758 choices=['present', 'absent']
759 ),
760 partition=dict(
761 default='Common',
762 fallback=(env_fallback, ['F5_PARTITION'])
763 )
764 )
765 self.argument_spec = {}
766 self.argument_spec.update(f5_argument_spec)
767 self.argument_spec.update(argument_spec)
768
769
770 def main():
771 spec = ArgumentSpec()
772
773 module = AnsibleModule(
774 argument_spec=spec.argument_spec,
775 supports_check_mode=spec.supports_check_mode,
776 )
777
778 try:
779 mm = ModuleManager(module=module)
780 results = mm.exec_module()
781 module.exit_json(**results)
782 except F5ModuleError as ex:
783 module.fail_json(msg=str(ex))
784
785
786 if __name__ == '__main__':
787 main()