Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_analytics.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_analytics
13 short_description: Manage HTTP analytics profiles on a BIG-IP
14 description:
15 - Manage HTTP analytics profiles on a BIG-IP device.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the profile.
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(analytics) profile.
28 type: str
29 description:
30 description:
31 - Description of the profile.
32 type: str
33 collect_geo:
34 description:
35 - Enables or disables the collection of the names of the countries
36 from where the traffic was sent.
37 type: bool
38 collect_ip:
39 description:
40 - Enables or disables the collection of client IPs statistics.
41 type: bool
42 collect_max_tps_and_throughput:
43 description:
44 - Enables or disables the collection of maximum TPS and throughput
45 for all collected entities.
46 type: bool
47 collect_page_load_time:
48 description:
49 - Enables or disables the collection of the page load time
50 statistics.
51 type: bool
52 collect_url:
53 description:
54 - Enables or disables the collection of requested URL statistics.
55 type: bool
56 collect_user_agent:
57 description:
58 - Enables or disables the collection of user agents.
59 type: bool
60 collect_user_sessions:
61 description:
62 - Enables or disables the collection of the unique user sessions.
63 type: bool
64 collected_stats_external_logging:
65 description:
66 - Enables or disables the external logging of the collected
67 statistics.
68 type: bool
69 collected_stats_internal_logging:
70 description:
71 - Enables or disables the internal logging of the collected
72 statistics.
73 type: bool
74 external_logging_publisher:
75 description:
76 - Specifies the external logging publisher used to send statistical
77 data to one or more destinations.
78 type: str
79 notification_by_syslog:
80 description:
81 - Enables or disables logging of the analytics alerts into the
82 Syslog.
83 type: bool
84 notification_by_email:
85 description:
86 - Enables or disables sending the analytics alerts by email.
87 type: bool
88 notification_email_addresses:
89 description:
90 - Specifies which email addresses receive alerts by email when
91 C(notification_by_email) is enabled.
92 type: list
93 elements: str
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 profile exists.
102 - When C(absent), ensures the profile is removed.
103 type: str
104 choices:
105 - present
106 - absent
107 default: present
108 extends_documentation_fragment: f5networks.f5_modules.f5
109 author:
110 - Tim Rupp (@caphrim007)
111 '''
112
113 EXAMPLES = r'''
114 - name: Create a profile
115 bigip_profile_analytics:
116 name: profile1
117 provider:
118 password: secret
119 server: lb.mydomain.com
120 user: admin
121 delegate_to: localhost
122 '''
123
124 RETURN = r'''
125 param1:
126 description: The new param1 value of the resource.
127 returned: changed
128 type: bool
129 sample: true
130 param2:
131 description: The new param2 value of the resource.
132 returned: changed
133 type: str
134 sample: Foo is bar
135 '''
136 from datetime import datetime
137
138 from ansible.module_utils.basic import (
139 AnsibleModule, env_fallback
140 )
141
142 from ..module_utils.bigip import F5RestClient
143 from ..module_utils.common import (
144 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
145 )
146 from ..module_utils.compare import cmp_simple_list
147 from ..module_utils.icontrol import tmos_version
148 from ..module_utils.teem import send_teem
149
150
151 class Parameters(AnsibleF5Parameters):
152 api_map = {
153 'defaultsFrom': 'parent',
154 'collectGeo': 'collect_geo',
155 'collectIp': 'collect_ip',
156 'collectMaxTpsAndThroughput': 'collect_max_tps_and_throughput',
157 'collectPageLoadTime': 'collect_page_load_time',
158 'collectUrl': 'collect_url',
159 'collectUserAgent': 'collect_user_agent',
160 'collectUserSessions': 'collect_user_sessions',
161 'collectedStatsExternalLogging': 'collected_stats_external_logging',
162 'collectedStatsInternalLogging': 'collected_stats_internal_logging',
163 'externalLoggingPublisher': 'external_logging_publisher',
164 'notificationBySyslog': 'notification_by_syslog',
165 'notificationByEmail': 'notification_by_email',
166 'notificationEmailAddresses': 'notification_email_addresses'
167 }
168
169 api_attributes = [
170 'description',
171 'defaultsFrom',
172 'collectGeo',
173 'collectIp',
174 'collectMaxTpsAndThroughput',
175 'collectPageLoadTime',
176 'collectUrl',
177 'collectUserAgent',
178 'collectUserSessions',
179 'collectedStatsExternalLogging',
180 'collectedStatsInternalLogging',
181 'externalLoggingPublisher',
182 'notificationBySyslog',
183 'notificationByEmail',
184 'notificationEmailAddresses',
185 ]
186
187 returnables = [
188 'collect_geo',
189 'collect_ip',
190 'collect_max_tps_and_throughput',
191 'collect_page_load_time',
192 'collect_url',
193 'collect_user_agent',
194 'collect_user_sessions',
195 'collected_stats_external_logging',
196 'collected_stats_internal_logging',
197 'description',
198 'external_logging_publisher',
199 'notification_by_syslog',
200 'notification_by_email',
201 'notification_email_addresses',
202 'parent',
203 ]
204
205 updatables = [
206 'collect_geo',
207 'collect_ip',
208 'collect_max_tps_and_throughput',
209 'collect_page_load_time',
210 'collect_url',
211 'collect_user_agent',
212 'collect_user_sessions',
213 'collected_stats_external_logging',
214 'collected_stats_internal_logging',
215 'description',
216 'external_logging_publisher',
217 'notification_by_syslog',
218 'notification_by_email',
219 'notification_email_addresses',
220 'parent',
221 ]
222
223 @property
224 def external_logging_publisher(self):
225 if self._values['external_logging_publisher'] is None:
226 return None
227 if self._values['external_logging_publisher'] in ['none', '']:
228 return ''
229 result = fq_name(self.partition, self._values['external_logging_publisher'])
230 return result
231
232 @property
233 def collect_geo(self):
234 return flatten_boolean(self._values['collect_geo'])
235
236 @property
237 def collect_ip(self):
238 return flatten_boolean(self._values['collect_ip'])
239
240 @property
241 def collect_max_tps_and_throughput(self):
242 return flatten_boolean(self._values['collect_max_tps_and_throughput'])
243
244 @property
245 def collect_page_load_time(self):
246 return flatten_boolean(self._values['collect_page_load_time'])
247
248 @property
249 def collect_url(self):
250 return flatten_boolean(self._values['collect_url'])
251
252 @property
253 def collect_user_agent(self):
254 return flatten_boolean(self._values['collect_user_agent'])
255
256 @property
257 def collect_user_sessions(self):
258 return flatten_boolean(self._values['collect_user_sessions'])
259
260 @property
261 def collected_stats_external_logging(self):
262 return flatten_boolean(self._values['collected_stats_external_logging'])
263
264 @property
265 def collected_stats_internal_logging(self):
266 return flatten_boolean(self._values['collected_stats_internal_logging'])
267
268 @property
269 def notification_by_syslog(self):
270 return flatten_boolean(self._values['notification_by_syslog'])
271
272 @property
273 def notification_by_email(self):
274 return flatten_boolean(self._values['notification_by_email'])
275
276
277 class ApiParameters(Parameters):
278 @property
279 def description(self):
280 if self._values['description'] in [None, 'none']:
281 return None
282 return self._values['description']
283
284
285 class ModuleParameters(Parameters):
286 @property
287 def description(self):
288 if self._values['description'] is None:
289 return None
290 elif self._values['description'] in ['none', '']:
291 return ''
292 return self._values['description']
293
294 @property
295 def parent(self):
296 if self._values['parent'] is None:
297 return None
298 result = fq_name(self.partition, self._values['parent'])
299 return result
300
301 @property
302 def notification_email_addresses(self):
303 if self._values['notification_email_addresses'] is None:
304 return None
305 elif (len(self._values['notification_email_addresses']) == 1 and
306 self._values['notification_email_addresses'][0] in ['', 'none']):
307 return []
308 return self._values['notification_email_addresses']
309
310
311 class Changes(Parameters):
312 def to_return(self):
313 result = {}
314 try:
315 for returnable in self.returnables:
316 result[returnable] = getattr(self, returnable)
317 result = self._filter_params(result)
318 except Exception:
319 pass
320 return result
321
322
323 class UsableChanges(Changes):
324 @property
325 def collect_geo(self):
326 if self._values['collect_geo'] is None:
327 return None
328 elif self._values['collect_geo'] == 'yes':
329 return 'enabled'
330 return 'disabled'
331
332 @property
333 def collect_ip(self):
334 if self._values['collect_ip'] is None:
335 return None
336 elif self._values['collect_ip'] == 'yes':
337 return 'enabled'
338 return 'disabled'
339
340 @property
341 def collect_max_tps_and_throughput(self):
342 if self._values['collect_max_tps_and_throughput'] is None:
343 return None
344 elif self._values['collect_max_tps_and_throughput'] == 'yes':
345 return 'enabled'
346 return 'disabled'
347
348 @property
349 def collect_page_load_time(self):
350 if self._values['collect_page_load_time'] is None:
351 return None
352 elif self._values['collect_page_load_time'] == 'yes':
353 return 'enabled'
354 return 'disabled'
355
356 @property
357 def collect_url(self):
358 if self._values['collect_url'] is None:
359 return None
360 elif self._values['collect_url'] == 'yes':
361 return 'enabled'
362 return 'disabled'
363
364 @property
365 def collect_user_agent(self):
366 if self._values['collect_user_agent'] is None:
367 return None
368 elif self._values['collect_user_agent'] == 'yes':
369 return 'enabled'
370 return 'disabled'
371
372 @property
373 def collect_user_sessions(self):
374 if self._values['collect_user_sessions'] is None:
375 return None
376 elif self._values['collect_user_sessions'] == 'yes':
377 return 'enabled'
378 return 'disabled'
379
380 @property
381 def collected_stats_external_logging(self):
382 if self._values['collected_stats_external_logging'] is None:
383 return None
384 elif self._values['collected_stats_external_logging'] == 'yes':
385 return 'enabled'
386 return 'disabled'
387
388 @property
389 def collected_stats_internal_logging(self):
390 if self._values['collected_stats_internal_logging'] is None:
391 return None
392 elif self._values['collected_stats_internal_logging'] == 'yes':
393 return 'enabled'
394 return 'disabled'
395
396 @property
397 def notification_by_syslog(self):
398 if self._values['notification_by_syslog'] is None:
399 return None
400 elif self._values['notification_by_syslog'] == 'yes':
401 return 'enabled'
402 return 'disabled'
403
404 @property
405 def notification_by_email(self):
406 if self._values['notification_by_email'] is None:
407 return None
408 elif self._values['notification_by_email'] == 'yes':
409 return 'enabled'
410 return 'disabled'
411
412
413 class ReportableChanges(Changes):
414 @property
415 def collect_geo(self):
416 return flatten_boolean(self._values['collect_geo'])
417
418 @property
419 def collect_ip(self):
420 return flatten_boolean(self._values['collect_ip'])
421
422 @property
423 def collect_max_tps_and_throughput(self):
424 return flatten_boolean(self._values['collect_max_tps_and_throughput'])
425
426 @property
427 def collect_page_load_time(self):
428 return flatten_boolean(self._values['collect_page_load_time'])
429
430 @property
431 def collect_url(self):
432 return flatten_boolean(self._values['collect_url'])
433
434 @property
435 def collect_user_agent(self):
436 return flatten_boolean(self._values['collect_user_agent'])
437
438 @property
439 def collect_user_sessions(self):
440 return flatten_boolean(self._values['collect_user_sessions'])
441
442 @property
443 def collected_stats_external_logging(self):
444 return flatten_boolean(self._values['collected_stats_external_logging'])
445
446 @property
447 def collected_stats_internal_logging(self):
448 return flatten_boolean(self._values['collected_stats_internal_logging'])
449
450 @property
451 def notification_by_syslog(self):
452 return flatten_boolean(self._values['notification_by_syslog'])
453
454 @property
455 def notification_by_email(self):
456 return flatten_boolean(self._values['notification_by_email'])
457
458
459 class Difference(object):
460 def __init__(self, want, have=None):
461 self.want = want
462 self.have = have
463
464 def compare(self, param):
465 try:
466 result = getattr(self, param)
467 return result
468 except AttributeError:
469 return self.__default(param)
470
471 def __default(self, param):
472 attr1 = getattr(self.want, param)
473 try:
474 attr2 = getattr(self.have, param)
475 if attr1 != attr2:
476 return attr1
477 except AttributeError:
478 return attr1
479
480 @property
481 def description(self):
482 if self.want.description is None:
483 return None
484 if self.have.description is None and self.want.description == '':
485 return None
486 if self.want.description != self.have.description:
487 return self.want.description
488
489 @property
490 def notification_email_addresses(self):
491 return cmp_simple_list(self.want.notification_email_addresses, self.have.notification_email_addresses)
492
493 @property
494 def external_logging_publisher(self):
495 if self.want.external_logging_publisher is None:
496 return None
497 if self.have.external_logging_publisher is None and self.want.external_logging_publisher == '':
498 return None
499 if self.want.external_logging_publisher != self.have.external_logging_publisher:
500 return self.want.external_logging_publisher
501
502
503 class ModuleManager(object):
504 def __init__(self, *args, **kwargs):
505 self.module = kwargs.get('module', None)
506 self.client = F5RestClient(**self.module.params)
507 self.want = ModuleParameters(params=self.module.params)
508 self.have = ApiParameters()
509 self.changes = UsableChanges()
510
511 def _set_changed_options(self):
512 changed = {}
513 for key in Parameters.returnables:
514 if getattr(self.want, key) is not None:
515 changed[key] = getattr(self.want, key)
516 if changed:
517 self.changes = UsableChanges(params=changed)
518
519 def _update_changed_options(self):
520 diff = Difference(self.want, self.have)
521 updatables = Parameters.updatables
522 changed = dict()
523 for k in updatables:
524 change = diff.compare(k)
525 if change is None:
526 continue
527 else:
528 if isinstance(change, dict):
529 changed.update(change)
530 else:
531 changed[k] = change
532 if changed:
533 self.changes = UsableChanges(params=changed)
534 return True
535 return False
536
537 def _announce_deprecations(self, result):
538 warnings = result.pop('__warnings', [])
539 for warning in warnings:
540 self.client.module.deprecate(
541 msg=warning['msg'],
542 version=warning['version']
543 )
544
545 def exec_module(self):
546 start = datetime.now().isoformat()
547 version = tmos_version(self.client)
548 changed = False
549 result = dict()
550 state = self.want.state
551
552 if state == "present":
553 changed = self.present()
554 elif state == "absent":
555 changed = self.absent()
556
557 reportable = ReportableChanges(params=self.changes.to_return())
558 changes = reportable.to_return()
559 result.update(**changes)
560 result.update(dict(changed=changed))
561 self._announce_deprecations(result)
562 send_teem(start, self.client, self.module, version)
563 return result
564
565 def present(self):
566 if self.exists():
567 return self.update()
568 else:
569 return self.create()
570
571 def absent(self):
572 if self.exists():
573 return self.remove()
574 return False
575
576 def should_update(self):
577 result = self._update_changed_options()
578 if result:
579 return True
580 return False
581
582 def update(self):
583 self.have = self.read_current_from_device()
584 if not self.should_update():
585 return False
586 if self.module.check_mode:
587 return True
588 self.update_on_device()
589 return True
590
591 def remove(self):
592 if self.module.check_mode:
593 return True
594 self.remove_from_device()
595 if self.exists():
596 raise F5ModuleError("Failed to delete the resource.")
597 return True
598
599 def create(self):
600 self._set_changed_options()
601 if self.module.check_mode:
602 return True
603 self.create_on_device()
604 return True
605
606 def exists(self):
607 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/analytics/{2}".format(
608 self.client.provider['server'],
609 self.client.provider['server_port'],
610 transform_name(self.want.partition, self.want.name)
611 )
612 resp = self.client.api.get(uri)
613 try:
614 response = resp.json()
615 except ValueError as ex:
616 raise F5ModuleError(str(ex))
617
618 if resp.status == 404 or 'code' in response and response['code'] == 404:
619 return False
620 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
621 return True
622
623 errors = [401, 403, 409, 500, 501, 502, 503, 504]
624
625 if resp.status in errors or 'code' in response and response['code'] in errors:
626 if 'message' in response:
627 raise F5ModuleError(response['message'])
628 else:
629 raise F5ModuleError(resp.content)
630
631 def create_on_device(self):
632 params = self.changes.api_params()
633 params['name'] = self.want.name
634 params['partition'] = self.want.partition
635 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/analytics/".format(
636 self.client.provider['server'],
637 self.client.provider['server_port'],
638 )
639 resp = self.client.api.post(uri, json=params)
640 try:
641 response = resp.json()
642 except ValueError as ex:
643 raise F5ModuleError(str(ex))
644
645 if 'code' in response and response['code'] in [400, 409, 404]:
646 if 'message' in response:
647 raise F5ModuleError(response['message'])
648 else:
649 raise F5ModuleError(resp.content)
650 return True
651
652 def update_on_device(self):
653 params = self.changes.api_params()
654 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/analytics/{2}".format(
655 self.client.provider['server'],
656 self.client.provider['server_port'],
657 transform_name(self.want.partition, self.want.name)
658 )
659 resp = self.client.api.patch(uri, json=params)
660 try:
661 response = resp.json()
662 except ValueError as ex:
663 raise F5ModuleError(str(ex))
664
665 if 'code' in response and response['code'] in [400, 404]:
666 if 'message' in response:
667 raise F5ModuleError(response['message'])
668 else:
669 raise F5ModuleError(resp.content)
670
671 def remove_from_device(self):
672 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/analytics/{2}".format(
673 self.client.provider['server'],
674 self.client.provider['server_port'],
675 transform_name(self.want.partition, self.want.name)
676 )
677 response = self.client.api.delete(uri)
678 if response.status == 200:
679 return True
680 raise F5ModuleError(response.content)
681
682 def read_current_from_device(self):
683 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/analytics/{2}".format(
684 self.client.provider['server'],
685 self.client.provider['server_port'],
686 transform_name(self.want.partition, self.want.name)
687 )
688 resp = self.client.api.get(uri)
689 try:
690 response = resp.json()
691 except ValueError as ex:
692 raise F5ModuleError(str(ex))
693
694 if 'code' in response and response['code'] == 400:
695 if 'message' in response:
696 raise F5ModuleError(response['message'])
697 else:
698 raise F5ModuleError(resp.content)
699 return ApiParameters(params=response)
700
701
702 class ArgumentSpec(object):
703 def __init__(self):
704 self.supports_check_mode = True
705 argument_spec = dict(
706 name=dict(required=True),
707 parent=dict(),
708 description=dict(),
709 collect_geo=dict(type='bool'),
710 collect_ip=dict(type='bool'),
711 collect_max_tps_and_throughput=dict(type='bool'),
712 collect_page_load_time=dict(type='bool'),
713 collect_url=dict(type='bool'),
714 collect_user_agent=dict(type='bool'),
715 collect_user_sessions=dict(type='bool'),
716 collected_stats_external_logging=dict(type='bool'),
717 collected_stats_internal_logging=dict(type='bool'),
718 external_logging_publisher=dict(),
719 notification_by_syslog=dict(type='bool'),
720 notification_by_email=dict(type='bool'),
721 notification_email_addresses=dict(
722 type='list',
723 elements='str',
724 ),
725 state=dict(
726 default='present',
727 choices=['present', 'absent']
728 ),
729 partition=dict(
730 default='Common',
731 fallback=(env_fallback, ['F5_PARTITION'])
732 )
733 )
734 self.argument_spec = {}
735 self.argument_spec.update(f5_argument_spec)
736 self.argument_spec.update(argument_spec)
737
738
739 def main():
740 spec = ArgumentSpec()
741
742 module = AnsibleModule(
743 argument_spec=spec.argument_spec,
744 supports_check_mode=spec.supports_check_mode,
745 )
746
747 try:
748 mm = ModuleManager(module=module)
749 results = mm.exec_module()
750 module.exit_json(**results)
751 except F5ModuleError as ex:
752 module.fail_json(msg=str(ex))
753
754
755 if __name__ == '__main__':
756 main()