Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_sip.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_profile_sip
13 short_description: Manage SIP profiles on a BIG-IP
14 description:
15 - Manage SIP profiles on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the SIP profile to manage.
21 type: str
22 required: True
23 parent:
24 description:
25 - Specifies the profile from which this profile inherits settings.
26 - When creating a new profile, if this parameter is not specified, the default
27 is the system-supplied C(sip) profile.
28 type: str
29 community:
30 description:
31 - When the C(dialog_aware) is C(true) and the configuration requires multiple SIP virtual server-profile pairings,
32 this string value indicates whether the pair belongs to the same SIP proxy functional group.
33 type: str
34 description:
35 description:
36 - Description of the profile.
37 - To remove the entry completely, set a value of C('').
38 type: str
39 dialog_aware:
40 description:
41 - When C(true), the system gathers SIP dialog information and automatically forwards SIP messages belonging to
42 the known SIP dialog.
43 type: bool
44 enable_sip_firewall:
45 description:
46 - Specifies whether the Advanced Firewall Manager (AFM) policy is enabled.
47 - When C(true), the SIP Security settings configured in the DoS Profile in AFM apply to the virtual servers that
48 use this profile.
49 type: bool
50 insert_record_route_header:
51 description:
52 - When C(true), inserts a Record-Route SIP header, which indicates the next hop for the following SIP request
53 messages.
54 type: bool
55 insert_via_header:
56 description:
57 - When C(true), inserts a Via header in the forwarded SIP request.
58 - Via headers indicate the path taken through proxy devices and transports used. The response message uses this
59 routing information.
60 type: bool
61 user_via_header:
62 description:
63 - When C(insert_via_header) is C(true), specifies the Via value the system inserts as the top Via header in a
64 SIP REQUEST message.
65 - "The valid value must include SIP protocol and sent_by settings, for example: C(SIP/2.0/UDP 10.10.10.10:5060)."
66 - To remove the entry completely, set a value of C('').
67 type: str
68 log_profile:
69 description:
70 - Specifies the logging settings the publisher uses to send log messages.
71 - The format of the name can be either be prepended by partition (C(/Common/foo)), or specified
72 just as an object name (C(foo)).
73 - To remove the entry. set a value of C(''), however the profile C(log_publisher)
74 must also be set as C('').
75 type: str
76 log_publisher:
77 description:
78 - Specifies the publisher defined to log messages.
79 - Format of the name can be either be prepended by partition (C(/Common/foo)), or specified
80 just as an object name (C(foo)).
81 - To remove the entry. set a value of C(''), however the profile C(log_profile)
82 must also be set as C('').
83 type: str
84 secure_via_header:
85 description:
86 - When checked (enabled), inserts a secure Via header in the forwarded SIP request.
87 - A secure Via header indicates where the message originated.
88 - This parameter causes the inserted Via header to specify Transport Layer Security. For this option to take
89 effect, C(insert_via_header) must be set to (true).
90 type: bool
91 security:
92 description:
93 - "When C(true), enables the use of enhanced Horizontal Security Layer (HSL) security checking."
94 type: bool
95 terminate_on_bye:
96 description:
97 - When C(true), closes a connection when a BYE transaction finishes.
98 - A BYE transaction is a message an application sends to another application when it is ready to close the
99 connection between the two.
100 type: bool
101 max_size:
102 description:
103 - Specifies the maximum SIP message size that the BIG-IP system accepts.
104 - The accepted value range is C(0 - 4294967295) bytes.
105 type: int
106 partition:
107 description:
108 - Device partition to manage resources on.
109 type: str
110 default: Common
111 state:
112 description:
113 - When C(present), ensures the profile exists.
114 - When C(absent), ensures the profile is removed.
115 type: str
116 choices:
117 - present
118 - absent
119 default: present
120 extends_documentation_fragment: f5networks.f5_modules.f5
121 author:
122 - Wojciech Wypior (@wojtek0806)
123 '''
124
125 EXAMPLES = r'''
126 - name: Create a SIP profile
127 bigip_profile_sip:
128 name: foo
129 parent: sip
130 log_profile: alg_log
131 log_publisher: foo-publisher
132 description: this is a new profile
133 security: true
134 provider:
135 password: secret
136 server: lb.mydomain.com
137 user: admin
138 delegate_to: localhost
139
140 - name: Update SIP profile
141 bigip_profile_sip:
142 name: foo
143 insert_record_route_header: true
144 enable_sip_firewall: true
145 insert_via_header: true
146 user_via_header: "SIP/2.0/UDP 10.10.10.10:5060"
147 provider:
148 password: secret
149 server: lb.mydomain.com
150 user: admin
151 delegate_to: localhost
152
153 - name: Delete a SIP profile
154 bigip_profile_sip:
155 name: foo
156 state: absent
157 provider:
158 password: secret
159 server: lb.mydomain.com
160 user: admin
161 delegate_to: localhost
162 '''
163
164 RETURN = r'''
165 description:
166 description: Description of the profile.
167 returned: changed
168 type: str
169 sample: "custom description"
170 community:
171 description: Indicates whether the pair belongs to the same SIP proxy functional group.
172 returned: changed
173 type: str
174 sample: foo_community
175 parent:
176 description: Specifies the profile from which this profile inherits settings.
177 returned: changed
178 type: str
179 sample: /Common/sip
180 dialog_aware:
181 description: Specifies if the system gathers SIP dialog information.
182 returned: changed
183 type: bool
184 sample: false
185 enable_sip_firewall:
186 description: Specifies whether the Advanced Firewall Manager policy is enabled.
187 returned: changed
188 type: bool
189 sample: true
190 insert_record_route_header:
191 description: Specifies if the system will insert a Record-Route SIP header.
192 returned: changed
193 type: bool
194 sample: true
195 insert_via_header:
196 description: Specifies if the system will insert a Via header in the forwarded SIP request.
197 returned: changed
198 type: bool
199 sample: true
200 user_via_header:
201 description: The value the system inserts as the top Via header in a SIP REQUEST message.
202 returned: changed
203 type: str
204 sample: "SIP/2.0/UDP 10.10.10.10:5060"
205 log_profile:
206 description: The logging settings the publisher uses to send log messages.
207 returned: changed
208 type: str
209 sample: "/Common/alg_profile"
210 log_publisher:
211 description: The publisher defined to log messages.
212 returned: changed
213 type: str
214 sample: "/Common/foo_publisher"
215 secure_via_header:
216 description: Specifies if the system will insert a secure Via header in the forwarded SIP request.
217 returned: changed
218 type: bool
219 sample: false
220 security:
221 description: Enables the use of enhanced Horizontal Security Layer security checking.
222 returned: changed
223 type: bool
224 sample: true
225 terminate_on_bye:
226 description: Specifies if the system will close a connection when a BYE transaction finishes.
227 returned: changed
228 type: bool
229 sample: false
230 max_size:
231 description: Specifies if the system will close a connection when a BYE transaction finishes.
232 returned: changed
233 type: bool
234 sample: false
235 '''
236 from datetime import datetime
237
238 from ansible.module_utils.basic import (
239 AnsibleModule, env_fallback
240 )
241
242 from ..module_utils.bigip import F5RestClient
243 from ..module_utils.common import (
244 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
245 )
246 from ..module_utils.icontrol import tmos_version
247 from ..module_utils.teem import send_teem
248
249
250 class Parameters(AnsibleF5Parameters):
251 api_map = {
252 'defaultsFrom': 'parent',
253 'dialogAware': 'dialog_aware',
254 'enableSipFirewall': 'enable_sip_firewall',
255 'insertRecordRouteHeader': 'insert_record_route_header',
256 'insertViaHeader': 'insert_via_header',
257 'userViaHeader': 'user_via_header',
258 'logProfile': 'log_profile',
259 'logPublisher': 'log_publisher',
260 'secureViaHeader': 'secure_via_header',
261 'terminateOnBye': 'terminate_on_bye',
262 'maxSize': 'max_size',
263 }
264
265 api_attributes = [
266 'community',
267 'description',
268 'defaultsFrom',
269 'dialogAware',
270 'enableSipFirewall',
271 'insertRecordRouteHeader',
272 'insertViaHeader',
273 'logProfile',
274 'logPublisher',
275 'secureViaHeader',
276 'security',
277 'terminateOnBye',
278 'userViaHeader',
279 'maxSize',
280
281 ]
282
283 returnables = [
284 'description',
285 'community',
286 'parent',
287 'dialog_aware',
288 'enable_sip_firewall',
289 'insert_record_route_header',
290 'insert_via_header',
291 'user_via_header',
292 'log_profile',
293 'log_publisher',
294 'secure_via_header',
295 'security',
296 'terminate_on_bye',
297 'max_size',
298 ]
299
300 updatables = [
301 'description',
302 'community',
303 'parent',
304 'dialog_aware',
305 'enable_sip_firewall',
306 'insert_record_route_header',
307 'insert_via_header',
308 'user_via_header',
309 'log_profile',
310 'log_publisher',
311 'secure_via_header',
312 'security',
313 'terminate_on_bye',
314 'max_size',
315 ]
316
317
318 class ApiParameters(Parameters):
319 pass
320
321
322 class ModuleParameters(Parameters):
323 @property
324 def parent(self):
325 if self._values['parent'] is None:
326 return None
327 result = fq_name(self.partition, self._values['parent'])
328 return result
329
330 @property
331 def security(self):
332 if self._values['security'] is None:
333 return None
334 result = flatten_boolean(self._values['security'])
335 if result == 'yes':
336 return 'enabled'
337 if result == 'no':
338 return 'disabled'
339
340 @property
341 def dialog_aware(self):
342 if self._values['dialog_aware'] is None:
343 return None
344 result = flatten_boolean(self._values['dialog_aware'])
345 if result == 'yes':
346 return 'enabled'
347 if result == 'no':
348 return 'disabled'
349
350 @property
351 def enable_sip_firewall(self):
352 if self._values['enable_sip_firewall'] is None:
353 return None
354 result = flatten_boolean(self._values['enable_sip_firewall'])
355 return result
356
357 @property
358 def insert_via_header(self):
359 if self._values['insert_via_header'] is None:
360 return None
361 result = flatten_boolean(self._values['insert_via_header'])
362 if result == 'yes':
363 return 'enabled'
364 if result == 'no':
365 return 'disabled'
366
367 @property
368 def secure_via_header(self):
369 if self._values['secure_via_header'] is None:
370 return None
371 result = flatten_boolean(self._values['secure_via_header'])
372 if result == 'yes':
373 return 'enabled'
374 if result == 'no':
375 return 'disabled'
376
377 @property
378 def terminate_on_bye(self):
379 if self._values['terminate_on_bye'] is None:
380 return None
381 result = flatten_boolean(self._values['terminate_on_bye'])
382 if result == 'yes':
383 return 'enabled'
384 if result == 'no':
385 return 'disabled'
386
387 @property
388 def insert_record_route_header(self):
389 if self._values['insert_record_route_header'] is None:
390 return None
391 result = flatten_boolean(self._values['insert_record_route_header'])
392 if result == 'yes':
393 return 'enabled'
394 if result == 'no':
395 return 'disabled'
396
397 @property
398 def max_size(self):
399 if self._values['max_size'] is None:
400 return None
401 if 0 <= self._values['max_size'] <= 4294967295:
402 return self._values['max_size']
403 raise F5ModuleError(
404 "Valid 'max_size' must be in range 0 - 4294967295 bytes."
405 )
406
407 @property
408 def log_profile(self):
409 if self._values['log_profile'] in [None, '']:
410 return self._values['log_profile']
411 result = fq_name(self.partition, self._values['log_profile'])
412 return result
413
414 @property
415 def log_publisher(self):
416 if self._values['log_publisher'] in [None, '']:
417 return self._values['log_publisher']
418 result = fq_name(self.partition, self._values['log_publisher'])
419 return result
420
421
422 class Changes(Parameters):
423 def to_return(self):
424 result = {}
425 try:
426 for returnable in self.returnables:
427 result[returnable] = getattr(self, returnable)
428 result = self._filter_params(result)
429 except Exception:
430 pass
431 return result
432
433
434 class UsableChanges(Changes):
435 pass
436
437
438 class ReportableChanges(Changes):
439 @property
440 def security(self):
441 result = flatten_boolean(self._values['security'])
442 return result
443
444 @property
445 def dialog_aware(self):
446 result = flatten_boolean(self._values['dialog_aware'])
447 return result
448
449 @property
450 def enable_sip_firewall(self):
451 result = flatten_boolean(self._values['enable_sip_firewall'])
452 return result
453
454 @property
455 def insert_via_header(self):
456 result = flatten_boolean(self._values['insert_via_header'])
457 return result
458
459 @property
460 def terminate_on_bye(self):
461 result = flatten_boolean(self._values['terminate_on_bye'])
462 return result
463
464 @property
465 def insert_record_route_header(self):
466 result = flatten_boolean(self._values['insert_record_route_header'])
467 return result
468
469 @property
470 def secure_via_header(self):
471 result = flatten_boolean(self._values['secure_via_header'])
472 return result
473
474
475 class Difference(object):
476 def __init__(self, want, have=None):
477 self.want = want
478 self.have = have
479
480 def compare(self, param):
481 try:
482 result = getattr(self, param)
483 return result
484 except AttributeError:
485 return self.__default(param)
486
487 def __default(self, param):
488 attr1 = getattr(self.want, param)
489 try:
490 attr2 = getattr(self.have, param)
491 if attr1 != attr2:
492 return attr1
493 except AttributeError:
494 return attr1
495
496 @property
497 def description(self):
498 if self.want.description is None:
499 return None
500 if self.want.description == '':
501 if self.have.description in [None, "none"]:
502 return None
503 if self.want.description != self.have.description:
504 return self.want.description
505
506 @property
507 def user_via_header(self):
508 if self.want.user_via_header is None:
509 return None
510 if self.want.user_via_header == '':
511 if self.have.user_via_header in [None, "none"]:
512 return None
513 if self.want.user_via_header != self.have.user_via_header:
514 return self.want.user_via_header
515
516 @property
517 def log_profile(self):
518 if self.want.log_profile is None:
519 return None
520 if self.want.log_profile == '':
521 if self.have.log_profile in [None, "none"]:
522 return None
523 if self.want.log_profile != self.have.log_profile:
524 return self.want.log_profile
525
526 @property
527 def log_publisher(self):
528 if self.want.log_publisher is None:
529 return None
530 if self.want.log_publisher == '':
531 if self.have.log_publisher in [None, "none"]:
532 return None
533 if self.want.log_publisher != self.have.log_publisher:
534 return self.want.log_publisher
535
536
537 class ModuleManager(object):
538 def __init__(self, *args, **kwargs):
539 self.module = kwargs.get('module', None)
540 self.client = F5RestClient(**self.module.params)
541 self.want = ModuleParameters(params=self.module.params)
542 self.have = ApiParameters()
543 self.changes = UsableChanges()
544
545 def _set_changed_options(self):
546 changed = {}
547 for key in Parameters.returnables:
548 if getattr(self.want, key) is not None:
549 changed[key] = getattr(self.want, key)
550 if changed:
551 self.changes = UsableChanges(params=changed)
552
553 def _update_changed_options(self):
554 diff = Difference(self.want, self.have)
555 updatables = Parameters.updatables
556 changed = dict()
557 for k in updatables:
558 change = diff.compare(k)
559 if change is None:
560 continue
561 else:
562 if isinstance(change, dict):
563 changed.update(change)
564 else:
565 changed[k] = change
566 if changed:
567 self.changes = UsableChanges(params=changed)
568 return True
569 return False
570
571 def _announce_deprecations(self, result):
572 warnings = result.pop('__warnings', [])
573 for warning in warnings:
574 self.client.module.deprecate(
575 msg=warning['msg'],
576 version=warning['version']
577 )
578
579 def exec_module(self):
580 start = datetime.now().isoformat()
581 version = tmos_version(self.client)
582 changed = False
583 result = dict()
584 state = self.want.state
585
586 if state == "present":
587 changed = self.present()
588 elif state == "absent":
589 changed = self.absent()
590
591 reportable = ReportableChanges(params=self.changes.to_return())
592 changes = reportable.to_return()
593 result.update(**changes)
594 result.update(dict(changed=changed))
595 self._announce_deprecations(result)
596 send_teem(start, self.client, self.module, version)
597 return result
598
599 def present(self):
600 if self.exists():
601 return self.update()
602 else:
603 return self.create()
604
605 def absent(self):
606 if self.exists():
607 return self.remove()
608 return False
609
610 def should_update(self):
611 result = self._update_changed_options()
612 if result:
613 return True
614 return False
615
616 def update(self):
617 self.have = self.read_current_from_device()
618 if not self.should_update():
619 return False
620 if self.module.check_mode:
621 return True
622 self.update_on_device()
623 return True
624
625 def remove(self):
626 if self.module.check_mode:
627 return True
628 self.remove_from_device()
629 if self.exists():
630 raise F5ModuleError("Failed to delete the resource.")
631 return True
632
633 def create(self):
634 self._set_changed_options()
635 if self.module.check_mode:
636 return True
637 self.create_on_device()
638 return True
639
640 def exists(self):
641 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/{2}".format(
642 self.client.provider['server'],
643 self.client.provider['server_port'],
644 transform_name(self.want.partition, self.want.name)
645 )
646 resp = self.client.api.get(uri)
647 try:
648 response = resp.json()
649 except ValueError as ex:
650 raise F5ModuleError(str(ex))
651
652 if resp.status == 404 or 'code' in response and response['code'] == 404:
653 return False
654 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
655 return True
656
657 errors = [401, 403, 409, 500, 501, 502, 503, 504]
658
659 if resp.status in errors or 'code' in response and response['code'] in errors:
660 if 'message' in response:
661 raise F5ModuleError(response['message'])
662 else:
663 raise F5ModuleError(resp.content)
664
665 def create_on_device(self):
666 params = self.changes.api_params()
667 params['name'] = self.want.name
668 params['partition'] = self.want.partition
669 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/".format(
670 self.client.provider['server'],
671 self.client.provider['server_port'],
672 )
673 resp = self.client.api.post(uri, json=params)
674 try:
675 response = resp.json()
676 except ValueError as ex:
677 raise F5ModuleError(str(ex))
678
679 if 'code' in response and response['code'] in [400, 409]:
680 if 'message' in response:
681 raise F5ModuleError(response['message'])
682 else:
683 raise F5ModuleError(resp.content)
684 return True
685
686 def update_on_device(self):
687 params = self.changes.api_params()
688 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/{2}".format(
689 self.client.provider['server'],
690 self.client.provider['server_port'],
691 transform_name(self.want.partition, self.want.name)
692 )
693 resp = self.client.api.patch(uri, json=params)
694 try:
695 response = resp.json()
696 except ValueError as ex:
697 raise F5ModuleError(str(ex))
698
699 if 'code' in response and response['code'] == 400:
700 if 'message' in response:
701 raise F5ModuleError(response['message'])
702 else:
703 raise F5ModuleError(resp.content)
704
705 def remove_from_device(self):
706 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/{2}".format(
707 self.client.provider['server'],
708 self.client.provider['server_port'],
709 transform_name(self.want.partition, self.want.name)
710 )
711 response = self.client.api.delete(uri)
712 if response.status == 200:
713 return True
714 raise F5ModuleError(response.content)
715
716 def read_current_from_device(self):
717 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/sip/{2}".format(
718 self.client.provider['server'],
719 self.client.provider['server_port'],
720 transform_name(self.want.partition, self.want.name)
721 )
722 resp = self.client.api.get(uri)
723 try:
724 response = resp.json()
725 except ValueError as ex:
726 raise F5ModuleError(str(ex))
727
728 if 'code' in response and response['code'] == 400:
729 if 'message' in response:
730 raise F5ModuleError(response['message'])
731 else:
732 raise F5ModuleError(resp.content)
733 return ApiParameters(params=response)
734
735
736 class ArgumentSpec(object):
737 def __init__(self):
738 self.supports_check_mode = True
739 argument_spec = dict(
740 name=dict(required=True),
741 parent=dict(),
742 security=dict(type='bool'),
743 description=dict(),
744 community=dict(),
745 dialog_aware=dict(type='bool'),
746 enable_sip_firewall=dict(type='bool'),
747 insert_via_header=dict(type='bool'),
748 user_via_header=dict(),
749 secure_via_header=dict(type='bool'),
750 terminate_on_bye=dict(type='bool'),
751 max_size=dict(type='int'),
752 log_profile=dict(),
753 log_publisher=dict(),
754 insert_record_route_header=dict(type='bool'),
755 state=dict(
756 default='present',
757 choices=['present', 'absent']
758 ),
759 partition=dict(
760 default='Common',
761 fallback=(env_fallback, ['F5_PARTITION'])
762 )
763 )
764 self.argument_spec = {}
765 self.argument_spec.update(f5_argument_spec)
766 self.argument_spec.update(argument_spec)
767
768
769 def main():
770 spec = ArgumentSpec()
771
772 module = AnsibleModule(
773 argument_spec=spec.argument_spec,
774 supports_check_mode=spec.supports_check_mode,
775 )
776
777 try:
778 mm = ModuleManager(module=module)
779 results = mm.exec_module()
780 module.exit_json(**results)
781 except F5ModuleError as ex:
782 module.fail_json(msg=str(ex))
783
784
785 if __name__ == '__main__':
786 main()