Debian Codegraph @

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