Debian Codegraph @

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