Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_timer_policy.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_timer_policy
13 short_description: Manage timer policies on a BIG-IP
14 description:
15 - Manage timer policies on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the timer policy.
21 type: str
22 required: True
23 description:
24 description:
25 - Specifies descriptive text that identifies the timer policy.
26 type: str
27 rules:
28 description:
29 - Rules you want assigned to the timer policy.
30 type: list
31 elements: dict
32 suboptions:
33 name:
34 description:
35 - The name of the rule.
36 type: str
37 required: True
38 protocol:
39 description:
40 - Specifies the IP protocol entry for which the timer policy rule is being
41 configured. This could be a layer-4 protocol (such as C(tcp), C(udp) or
42 C(sctp).
43 - Only flows matching the configured protocol will make use of this rule.
44 - When C(all-other) is specified, if there are no specific ip-protocol rules
45 that match the flow, the flow matches all the other ip-protocol rules.
46 - When specifying rules, if this parameter is not specified, the default is
47 C(all-other).
48 type: str
49 default: all-other
50 choices:
51 - all-other
52 - ah
53 - bna
54 - esp
55 - etherip
56 - gre
57 - icmp
58 - ipencap
59 - ipv6
60 - ipv6-auth
61 - ipv6-crypt
62 - ipv6-icmp
63 - isp-ip
64 - mux
65 - ospf
66 - sctp
67 - tcp
68 - udp
69 - udplite
70 destination_ports:
71 description:
72 - The list of destination ports on which to match the rule.
73 - Specify a port range by specifying start and end ports separated by a
74 dash (-).
75 - This field is only available if you have selected the C(sctp), C(tcp), or
76 C(udp) protocol.
77 type: list
78 elements: str
79 idle_timeout:
80 description:
81 - Specifies an idle timeout, in seconds, for protocol and port pairs that
82 match the timer policy rule.
83 - When C(infinite), specifies the protocol and port pairs that match
84 the timer policy rule have no idle timeout.
85 - When specifying rules, if this parameter is not specified, the default is
86 C(unspecified).
87 type: str
88 default: unspecified
89 partition:
90 description:
91 - Device partition to manage resources on.
92 type: str
93 default: Common
94 state:
95 description:
96 - When C(present), ensures the resource exists.
97 - When C(absent), ensures the resource is removed.
98 type: str
99 choices:
100 - present
101 - absent
102 default: present
103 extends_documentation_fragment: f5networks.f5_modules.f5
104 author:
105 - Tim Rupp (@caphrim007)
106 '''
107
108 EXAMPLES = r'''
109 - name: Create a timer policy
110 bigip_timer_policy:
111 name: timer1
112 description: My timer policy
113 rules:
114 - name: rule1
115 protocol: tcp
116 idle_timeout: indefinite
117 destination_ports:
118 - 443
119 - 80
120 - name: rule2
121 protocol: 200
122 - name: rule3
123 protocol: sctp
124 idle_timeout: 200
125 destination_ports:
126 - 21
127 state: present
128 provider:
129 password: secret
130 server: lb.mydomain.com
131 user: admin
132 delegate_to: localhost
133
134 - name: Remove a timer policy and all its associated rules
135 bigip_timer_policy:
136 name: timer1
137 description: My timer policy
138 state: absent
139 provider:
140 user: admin
141 password: secret
142 server: lb.mydomain.com
143 delegate_to: localhost
144 '''
145
146 RETURN = r'''
147 description:
148 description: The new description of the timer policy.
149 returned: changed
150 type: str
151 sample: true
152 '''
153 from datetime import datetime
154
155 from ansible.module_utils.basic import (
156 AnsibleModule, env_fallback
157 )
158
159 from ..module_utils.bigip import F5RestClient
160 from ..module_utils.common import (
161 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
162 )
163 from ..module_utils.compare import compare_complex_list
164 from ..module_utils.icontrol import tmos_version
165 from ..module_utils.teem import send_teem
166
167
168 class Parameters(AnsibleF5Parameters):
169 api_map = {
170
171 }
172
173 api_attributes = [
174 'description',
175 'rules',
176 ]
177
178 returnables = [
179 'description',
180 'rules',
181 ]
182
183 updatables = [
184 'description',
185 'rules',
186 ]
187
188
189 class ApiParameters(Parameters):
190 @property
191 def rules(self):
192 if self._values['rules'] is None:
193 return None
194 results = []
195 for rule in self._values['rules']:
196 result = dict()
197 result['name'] = rule['name']
198 if 'ipProtocol' in rule:
199 result['protocol'] = str(rule['ipProtocol'])
200 if 'timers' in rule:
201 result['idle_timeout'] = str(rule['timers'][0]['value'])
202 if 'destinationPorts' in rule:
203 ports = list(set([str(x['name']) for x in rule['destinationPorts']]))
204 ports.sort()
205 result['destination_ports'] = ports
206 results.append(result)
207 results = sorted(results, key=lambda k: k['name'])
208 return results
209
210
211 class ModuleParameters(Parameters):
212 @property
213 def rules(self):
214 if self._values['rules'] is None:
215 return None
216 if len(self._values['rules']) == 1 and self._values['rules'][0] == '':
217 return ''
218 results = []
219 for rule in self._values['rules']:
220 result = dict()
221 result['name'] = rule['name']
222 if 'protocol' in rule and rule['protocol']:
223 result['protocol'] = str(rule['protocol'])
224 else:
225 result['protocol'] = 'all-other'
226
227 if 'idle_timeout' in rule and rule['idle_timeout']:
228 result['idle_timeout'] = str(rule['idle_timeout'])
229 else:
230 result['idle_timeout'] = 'unspecified'
231
232 if 'destination_ports' in rule and rule['destination_ports']:
233 ports = list(set([str(x) for x in rule['destination_ports']]))
234 ports.sort()
235 ports = [str(self._validate_port_entries(x)) for x in ports]
236 result['destination_ports'] = ports
237 results.append(result)
238 results = sorted(results, key=lambda k: k['name'])
239 return results
240
241 def _validate_port_entries(self, port):
242 if port == 'all-other':
243 return 0
244 if '-' in port:
245 parts = port.split('-')
246 if len(parts) != 2:
247 raise F5ModuleError(
248 "The correct format for a port range is X-Y, where X is the start"
249 "port and Y is the end port."
250 )
251 try:
252 start = int(parts[0])
253 end = int(parts[1])
254 except ValueError:
255 raise F5ModuleError(
256 "The ports in a range must be numbers."
257 "You provided '{0}' and '{1}'.".format(parts[0], parts[1])
258 )
259 if start == end:
260 return start
261 if start > end:
262 return '{0}-{1}'.format(end, start)
263 else:
264 return port
265 else:
266 try:
267 return int(port)
268 except ValueError:
269 raise F5ModuleError(
270 "The specified destination port is not a number."
271 )
272
273
274 class Changes(Parameters):
275 def to_return(self):
276 result = {}
277 try:
278 for returnable in self.returnables:
279 result[returnable] = getattr(self, returnable)
280 result = self._filter_params(result)
281 except Exception:
282 raise
283 return result
284
285
286 class UsableChanges(Changes):
287 @property
288 def rules(self):
289 if self._values['rules'] is None:
290 return None
291 results = []
292 for rule in self._values['rules']:
293 result = dict()
294 result['name'] = rule['name']
295 if 'protocol' in rule:
296 result['ipProtocol'] = rule['protocol']
297
298 if 'destination_ports' in rule:
299 if rule['protocol'] not in ['tcp', 'udp', 'sctp']:
300 raise F5ModuleError(
301 "Only the 'tcp', 'udp', and 'sctp' protocols support 'destination_ports'."
302 )
303 ports = [dict(name=str(x)) for x in rule['destination_ports']]
304 result['destinationPorts'] = ports
305 else:
306 result['destinationPorts'] = []
307
308 if 'idle_timeout' in rule:
309 if rule['idle_timeout'] in ['indefinite', 'immediate', 'unspecified']:
310 timeout = rule['idle_timeout']
311 else:
312 try:
313 int(rule['idle_timeout'])
314 timeout = rule['idle_timeout']
315 except ValueError:
316 raise F5ModuleError(
317 "idle_timeout must be a number, or, one of 'indefinite', 'immediate', or 'unspecified'."
318 )
319 result['timers'] = [
320 dict(name='flow-idle-timeout', value=timeout)
321 ]
322 results.append(result)
323 results = sorted(results, key=lambda k: k['name'])
324 return results
325
326
327 class ReportableChanges(Changes):
328 pass
329
330
331 class Difference(object):
332 def __init__(self, want, have=None):
333 self.want = want
334 self.have = have
335
336 def compare(self, param):
337 try:
338 result = getattr(self, param)
339 return result
340 except AttributeError:
341 return self.__default(param)
342
343 def __default(self, param):
344 attr1 = getattr(self.want, param)
345 try:
346 attr2 = getattr(self.have, param)
347 if attr1 != attr2:
348 return attr1
349 except AttributeError:
350 return attr1
351
352 @property
353 def rules(self):
354 if self.want.rules is None:
355 return None
356 if self.have.rules is None and self.want.rules == '':
357 return None
358 if self.have.rules is not None and self.want.rules == '':
359 return []
360 if self.have.rules is None:
361 return self.want.rules
362
363 want = [tuple(x.pop('destination_ports')) for x in self.want.rules if 'destination_ports' in x]
364 have = [tuple(x.pop('destination_ports')) for x in self.have.rules if 'destination_ports' in x]
365 if set(want) != set(have):
366 return self.want.rules
367 if compare_complex_list(self.want.rules, self.have.rules):
368 return self.want.rules
369
370
371 class ModuleManager(object):
372 def __init__(self, *args, **kwargs):
373 self.module = kwargs.get('module', None)
374 self.client = F5RestClient(**self.module.params)
375 self.want = ModuleParameters(params=self.module.params)
376 self.have = ApiParameters()
377 self.changes = UsableChanges()
378
379 def _set_changed_options(self):
380 changed = {}
381 for key in Parameters.returnables:
382 if getattr(self.want, key) is not None:
383 changed[key] = getattr(self.want, key)
384 if changed:
385 self.changes = UsableChanges(params=changed)
386
387 def _update_changed_options(self):
388 diff = Difference(self.want, self.have)
389 updatables = Parameters.updatables
390 changed = dict()
391 for k in updatables:
392 change = diff.compare(k)
393 if change is None:
394 continue
395 else:
396 if isinstance(change, dict):
397 changed.update(change)
398 else:
399 changed[k] = change
400 if changed:
401 self.changes = UsableChanges(params=changed)
402 return True
403 return False
404
405 def should_update(self):
406 result = self._update_changed_options()
407 if result:
408 return True
409 return False
410
411 def exec_module(self):
412 start = datetime.now().isoformat()
413 version = tmos_version(self.client)
414 changed = False
415 result = dict()
416 state = self.want.state
417
418 if state == "present":
419 changed = self.present()
420 elif state == "absent":
421 changed = self.absent()
422
423 reportable = ReportableChanges(params=self.changes.to_return())
424 changes = reportable.to_return()
425 result.update(**changes)
426 result.update(dict(changed=changed))
427 self._announce_deprecations(result)
428 send_teem(start, self.client, self.module, version)
429 return result
430
431 def _announce_deprecations(self, result):
432 warnings = result.pop('__warnings', [])
433 for warning in warnings:
434 self.client.module.deprecate(
435 msg=warning['msg'],
436 version=warning['version']
437 )
438
439 def present(self):
440 if self.exists():
441 return self.update()
442 else:
443 return self.create()
444
445 def absent(self):
446 if self.exists():
447 return self.remove()
448 return False
449
450 def update(self):
451 self.have = self.read_current_from_device()
452 if not self.should_update():
453 return False
454 if self.module.check_mode:
455 return True
456 self.update_on_device()
457 return True
458
459 def remove(self):
460 if self.module.check_mode:
461 return True
462 self.remove_from_device()
463 if self.exists():
464 raise F5ModuleError("Failed to delete the resource.")
465 return True
466
467 def create(self):
468 self._set_changed_options()
469 if self.module.check_mode:
470 return True
471 self.create_on_device()
472 return True
473
474 def exists(self):
475 uri = "https://{0}:{1}/mgmt/tm/net/timer-policy/{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 create_on_device(self):
500 params = self.changes.api_params()
501 params['name'] = self.want.name
502 params['partition'] = self.want.partition
503 uri = "https://{0}:{1}/mgmt/tm/net/timer-policy/".format(
504 self.client.provider['server'],
505 self.client.provider['server_port'],
506 )
507 resp = self.client.api.post(uri, json=params)
508 try:
509 response = resp.json()
510 except ValueError as ex:
511 raise F5ModuleError(str(ex))
512
513 if 'code' in response and response['code'] in [400, 403]:
514 if 'message' in response:
515 raise F5ModuleError(response['message'])
516 else:
517 raise F5ModuleError(resp.content)
518 return response['selfLink']
519
520 def update_on_device(self):
521 params = self.changes.api_params()
522 uri = "https://{0}:{1}/mgmt/tm/net/timer-policy/{2}".format(
523 self.client.provider['server'],
524 self.client.provider['server_port'],
525 transform_name(self.want.partition, self.want.name),
526 )
527 resp = self.client.api.patch(uri, json=params)
528 try:
529 response = resp.json()
530 except ValueError as ex:
531 raise F5ModuleError(str(ex))
532
533 if 'code' in response and response['code'] == 400:
534 if 'message' in response:
535 raise F5ModuleError(response['message'])
536 else:
537 raise F5ModuleError(resp.content)
538
539 def remove_from_device(self):
540 uri = "https://{0}:{1}/mgmt/tm/net/timer-policy/{2}".format(
541 self.client.provider['server'],
542 self.client.provider['server_port'],
543 transform_name(self.want.partition, self.want.name),
544 )
545 response = self.client.api.delete(uri)
546 if response.status == 200:
547 return True
548 raise F5ModuleError(response.content)
549
550 def read_current_from_device(self):
551 uri = "https://{0}:{1}/mgmt/tm/net/timer-policy/{2}".format(
552 self.client.provider['server'],
553 self.client.provider['server_port'],
554 transform_name(self.want.partition, self.want.name),
555 )
556 resp = self.client.api.get(uri)
557 try:
558 response = resp.json()
559 except ValueError as ex:
560 raise F5ModuleError(str(ex))
561
562 if 'code' in response and response['code'] == 400:
563 if 'message' in response:
564 raise F5ModuleError(response['message'])
565 else:
566 raise F5ModuleError(resp.content)
567 return ApiParameters(params=response)
568
569
570 class ArgumentSpec(object):
571 def __init__(self):
572 self.supports_check_mode = True
573 argument_spec = dict(
574 name=dict(required=True),
575 description=dict(),
576 rules=dict(
577 type='list',
578 elements='dict',
579 options=dict(
580 name=dict(required=True),
581 protocol=dict(
582 default='all-other',
583 choices=[
584 'all-other',
585 'ah',
586 'bna',
587 'esp',
588 'etherip',
589 'gre',
590 'icmp',
591 'ipencap',
592 'ipv6',
593 'ipv6-auth',
594 'ipv6-crypt',
595 'ipv6-icmp',
596 'isp-ip',
597 'mux',
598 'ospf',
599 'sctp',
600 'tcp',
601 'udp',
602 'udplite',
603 ]
604 ),
605 idle_timeout=dict(default='unspecified'),
606 destination_ports=dict(
607 type='list',
608 elements='str',
609 )
610 )
611 ),
612 state=dict(
613 default='present',
614 choices=['present', 'absent']
615 ),
616 partition=dict(
617 default='Common',
618 fallback=(env_fallback, ['F5_PARTITION'])
619 )
620 )
621 self.argument_spec = {}
622 self.argument_spec.update(f5_argument_spec)
623 self.argument_spec.update(argument_spec)
624
625
626 def main():
627 spec = ArgumentSpec()
628
629 module = AnsibleModule(
630 argument_spec=spec.argument_spec,
631 supports_check_mode=spec.supports_check_mode
632 )
633
634 try:
635 mm = ModuleManager(module=module)
636 results = mm.exec_module()
637 module.exit_json(**results)
638 except F5ModuleError as ex:
639 module.fail_json(msg=str(ex))
640
641
642 if __name__ == '__main__':
643 main()