Debian Codegraph @

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