Debian Codegraph @

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