1#!/usr/bin/python
2# This file is part of Ansible
3#
4# Ansible is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# Ansible is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
16
17from __future__ import absolute_import, division, print_function
18__metaclass__ = type
19
20ANSIBLE_METADATA = {'metadata_version': '1.1',
21                    'status': ['preview'],
22                    'supported_by': 'community'}
23
24DOCUMENTATION = '''
25---
26module: oneandone_monitoring_policy
27short_description: Configure 1&1 monitoring policy.
28description:
29     - Create, remove, update monitoring policies
30       (and add/remove ports, processes, and servers).
31       This module has a dependency on 1and1 >= 1.0
32version_added: "2.5"
33options:
34  state:
35    description:
36      - Define a monitoring policy's state to create, remove, update.
37    required: false
38    default: present
39    choices: [ "present", "absent", "update" ]
40  auth_token:
41    description:
42      - Authenticating API token provided by 1&1.
43    required: true
44  api_url:
45    description:
46      - Custom API URL. Overrides the
47        ONEANDONE_API_URL environement variable.
48    required: false
49  name:
50    description:
51      - Monitoring policy name used with present state. Used as identifier (id or name) when used with absent state. maxLength=128
52    required: true
53  monitoring_policy:
54    description:
55      - The identifier (id or name) of the monitoring policy used with update state.
56    required: true
57  agent:
58    description:
59      - Set true for using agent.
60    required: true
61  email:
62    description:
63      - User's email. maxLength=128
64    required: true
65  description:
66    description:
67      - Monitoring policy description. maxLength=256
68    required: false
69  thresholds:
70    description:
71      - Monitoring policy thresholds. Each of the suboptions have warning and critical,
72        which both have alert and value suboptions. Warning is used to set limits for
73        warning alerts, critical is used to set critical alerts. alert enables alert,
74        and value is used to advise when the value is exceeded.
75    required: true
76    suboptions:
77      cpu:
78        description:
79          - Consumption limits of CPU.
80        required: true
81      ram:
82        description:
83          - Consumption limits of RAM.
84        required: true
85      disk:
86        description:
87          - Consumption limits of hard disk.
88        required: true
89      internal_ping:
90        description:
91          - Response limits of internal ping.
92        required: true
93      transfer:
94        description:
95          - Consumption limits for transfer.
96        required: true
97  ports:
98    description:
99      - Array of ports that will be monitoring.
100    required: true
101    suboptions:
102      protocol:
103        description:
104          - Internet protocol.
105        choices: [ "TCP", "UDP" ]
106        required: true
107      port:
108        description:
109          - Port number. minimum=1, maximum=65535
110        required: true
111      alert_if:
112        description:
113          - Case of alert.
114        choices: [ "RESPONDING", "NOT_RESPONDING" ]
115        required: true
116      email_notification:
117        description:
118          - Set true for sending e-mail notifications.
119        required: true
120  processes:
121    description:
122      - Array of processes that will be monitoring.
123    required: true
124    suboptions:
125      process:
126        description:
127          - Name of the process. maxLength=50
128        required: true
129      alert_if:
130        description:
131          - Case of alert.
132        choices: [ "RUNNING", "NOT_RUNNING" ]
133        required: true
134  add_ports:
135    description:
136      - Ports to add to the monitoring policy.
137    required: false
138  add_processes:
139    description:
140      - Processes to add to the monitoring policy.
141    required: false
142  add_servers:
143    description:
144      - Servers to add to the monitoring policy.
145    required: false
146  remove_ports:
147    description:
148      - Ports to remove from the monitoring policy.
149    required: false
150  remove_processes:
151    description:
152      - Processes to remove from the monitoring policy.
153    required: false
154  remove_servers:
155    description:
156      - Servers to remove from the monitoring policy.
157    required: false
158  update_ports:
159    description:
160      - Ports to be updated on the monitoring policy.
161    required: false
162  update_processes:
163    description:
164      - Processes to be updated on the monitoring policy.
165    required: false
166  wait:
167    description:
168      - wait for the instance to be in state 'running' before returning
169    required: false
170    default: "yes"
171    type: bool
172  wait_timeout:
173    description:
174      - how long before wait gives up, in seconds
175    default: 600
176  wait_interval:
177    description:
178      - Defines the number of seconds to wait when using the _wait_for methods
179    default: 5
180
181requirements:
182  - "1and1"
183  - "python >= 2.6"
184
185author:
186  -  "Amel Ajdinovic (@aajdinov)"
187  -  "Ethan Devenport (@edevenport)"
188'''
189
190EXAMPLES = '''
191
192# Provisioning example. Create and destroy a monitoring policy.
193
194- oneandone_moitoring_policy:
195    auth_token: oneandone_private_api_key
196    name: ansible monitoring policy
197    description: Testing creation of a monitoring policy with ansible
198    email: your@emailaddress.com
199    agent: true
200    thresholds:
201     -
202       cpu:
203         warning:
204           value: 80
205           alert: false
206         critical:
207           value: 92
208           alert: false
209     -
210       ram:
211         warning:
212           value: 80
213           alert: false
214         critical:
215           value: 90
216           alert: false
217     -
218       disk:
219         warning:
220           value: 80
221           alert: false
222         critical:
223           value: 90
224           alert: false
225     -
226       internal_ping:
227         warning:
228           value: 50
229           alert: false
230         critical:
231           value: 100
232           alert: false
233     -
234       transfer:
235         warning:
236           value: 1000
237           alert: false
238         critical:
239           value: 2000
240           alert: false
241    ports:
242     -
243       protocol: TCP
244       port: 22
245       alert_if: RESPONDING
246       email_notification: false
247    processes:
248     -
249       process: test
250       alert_if: NOT_RUNNING
251       email_notification: false
252    wait: true
253
254- oneandone_moitoring_policy:
255    auth_token: oneandone_private_api_key
256    state: absent
257    name: ansible monitoring policy
258
259# Update a monitoring policy.
260
261- oneandone_moitoring_policy:
262    auth_token: oneandone_private_api_key
263    monitoring_policy: ansible monitoring policy
264    name: ansible monitoring policy updated
265    description: Testing creation of a monitoring policy with ansible updated
266    email: another@emailaddress.com
267    thresholds:
268     -
269       cpu:
270         warning:
271           value: 70
272           alert: false
273         critical:
274           value: 90
275           alert: false
276     -
277       ram:
278         warning:
279           value: 70
280           alert: false
281         critical:
282           value: 80
283           alert: false
284     -
285       disk:
286         warning:
287           value: 70
288           alert: false
289         critical:
290           value: 80
291           alert: false
292     -
293       internal_ping:
294         warning:
295           value: 60
296           alert: false
297         critical:
298           value: 90
299           alert: false
300     -
301       transfer:
302         warning:
303           value: 900
304           alert: false
305         critical:
306           value: 1900
307           alert: false
308    wait: true
309    state: update
310
311# Add a port to a monitoring policy.
312
313- oneandone_moitoring_policy:
314    auth_token: oneandone_private_api_key
315    monitoring_policy: ansible monitoring policy updated
316    add_ports:
317     -
318       protocol: TCP
319       port: 33
320       alert_if: RESPONDING
321       email_notification: false
322    wait: true
323    state: update
324
325# Update existing ports of a monitoring policy.
326
327- oneandone_moitoring_policy:
328    auth_token: oneandone_private_api_key
329    monitoring_policy: ansible monitoring policy updated
330    update_ports:
331     -
332       id: existing_port_id
333       protocol: TCP
334       port: 34
335       alert_if: RESPONDING
336       email_notification: false
337     -
338       id: existing_port_id
339       protocol: TCP
340       port: 23
341       alert_if: RESPONDING
342       email_notification: false
343    wait: true
344    state: update
345
346# Remove a port from a monitoring policy.
347
348- oneandone_moitoring_policy:
349    auth_token: oneandone_private_api_key
350    monitoring_policy: ansible monitoring policy updated
351    remove_ports:
352     - port_id
353    state: update
354
355# Add a process to a monitoring policy.
356
357- oneandone_moitoring_policy:
358    auth_token: oneandone_private_api_key
359    monitoring_policy: ansible monitoring policy updated
360    add_processes:
361     -
362       process: test_2
363       alert_if: NOT_RUNNING
364       email_notification: false
365    wait: true
366    state: update
367
368# Update existing processes of a monitoring policy.
369
370- oneandone_moitoring_policy:
371    auth_token: oneandone_private_api_key
372    monitoring_policy: ansible monitoring policy updated
373    update_processes:
374     -
375       id: process_id
376       process: test_1
377       alert_if: NOT_RUNNING
378       email_notification: false
379     -
380       id: process_id
381       process: test_3
382       alert_if: NOT_RUNNING
383       email_notification: false
384    wait: true
385    state: update
386
387# Remove a process from a monitoring policy.
388
389- oneandone_moitoring_policy:
390    auth_token: oneandone_private_api_key
391    monitoring_policy: ansible monitoring policy updated
392    remove_processes:
393     - process_id
394    wait: true
395    state: update
396
397# Add server to a monitoring policy.
398
399- oneandone_moitoring_policy:
400    auth_token: oneandone_private_api_key
401    monitoring_policy: ansible monitoring policy updated
402    add_servers:
403     - server id or name
404    wait: true
405    state: update
406
407# Remove server from a monitoring policy.
408
409- oneandone_moitoring_policy:
410    auth_token: oneandone_private_api_key
411    monitoring_policy: ansible monitoring policy updated
412    remove_servers:
413     - server01
414    wait: true
415    state: update
416'''
417
418RETURN = '''
419monitoring_policy:
420    description: Information about the monitoring policy that was processed
421    type: dict
422    sample: '{"id": "92B74394A397ECC3359825C1656D67A6", "name": "Default Policy"}'
423    returned: always
424'''
425
426import os
427from ansible.module_utils.basic import AnsibleModule
428from ansible.module_utils.oneandone import (
429    get_monitoring_policy,
430    get_server,
431    OneAndOneResources,
432    wait_for_resource_creation_completion
433)
434
435HAS_ONEANDONE_SDK = True
436
437try:
438    import oneandone.client
439except ImportError:
440    HAS_ONEANDONE_SDK = False
441
442
443def _check_mode(module, result):
444    if module.check_mode:
445        module.exit_json(
446            changed=result
447        )
448
449
450def _add_ports(module, oneandone_conn, monitoring_policy_id, ports):
451    """
452    Adds new ports to a monitoring policy.
453    """
454    try:
455        monitoring_policy_ports = []
456
457        for _port in ports:
458            monitoring_policy_port = oneandone.client.Port(
459                protocol=_port['protocol'],
460                port=_port['port'],
461                alert_if=_port['alert_if'],
462                email_notification=_port['email_notification']
463            )
464            monitoring_policy_ports.append(monitoring_policy_port)
465
466        if module.check_mode:
467            if monitoring_policy_ports:
468                return True
469            return False
470
471        monitoring_policy = oneandone_conn.add_port(
472            monitoring_policy_id=monitoring_policy_id,
473            ports=monitoring_policy_ports)
474        return monitoring_policy
475    except Exception as ex:
476        module.fail_json(msg=str(ex))
477
478
479def _delete_monitoring_policy_port(module, oneandone_conn, monitoring_policy_id, port_id):
480    """
481    Removes a port from a monitoring policy.
482    """
483    try:
484        if module.check_mode:
485            monitoring_policy = oneandone_conn.delete_monitoring_policy_port(
486                monitoring_policy_id=monitoring_policy_id,
487                port_id=port_id)
488            if monitoring_policy:
489                return True
490            return False
491
492        monitoring_policy = oneandone_conn.delete_monitoring_policy_port(
493            monitoring_policy_id=monitoring_policy_id,
494            port_id=port_id)
495        return monitoring_policy
496    except Exception as ex:
497        module.fail_json(msg=str(ex))
498
499
500def _modify_port(module, oneandone_conn, monitoring_policy_id, port_id, port):
501    """
502    Modifies a monitoring policy port.
503    """
504    try:
505        if module.check_mode:
506            cm_port = oneandone_conn.get_monitoring_policy_port(
507                monitoring_policy_id=monitoring_policy_id,
508                port_id=port_id)
509            if cm_port:
510                return True
511            return False
512
513        monitoring_policy_port = oneandone.client.Port(
514            protocol=port['protocol'],
515            port=port['port'],
516            alert_if=port['alert_if'],
517            email_notification=port['email_notification']
518        )
519
520        monitoring_policy = oneandone_conn.modify_port(
521            monitoring_policy_id=monitoring_policy_id,
522            port_id=port_id,
523            port=monitoring_policy_port)
524        return monitoring_policy
525    except Exception as ex:
526        module.fail_json(msg=str(ex))
527
528
529def _add_processes(module, oneandone_conn, monitoring_policy_id, processes):
530    """
531    Adds new processes to a monitoring policy.
532    """
533    try:
534        monitoring_policy_processes = []
535
536        for _process in processes:
537            monitoring_policy_process = oneandone.client.Process(
538                process=_process['process'],
539                alert_if=_process['alert_if'],
540                email_notification=_process['email_notification']
541            )
542            monitoring_policy_processes.append(monitoring_policy_process)
543
544        if module.check_mode:
545            mp_id = get_monitoring_policy(oneandone_conn, monitoring_policy_id)
546            if (monitoring_policy_processes and mp_id):
547                return True
548            return False
549
550        monitoring_policy = oneandone_conn.add_process(
551            monitoring_policy_id=monitoring_policy_id,
552            processes=monitoring_policy_processes)
553        return monitoring_policy
554    except Exception as ex:
555        module.fail_json(msg=str(ex))
556
557
558def _delete_monitoring_policy_process(module, oneandone_conn, monitoring_policy_id, process_id):
559    """
560    Removes a process from a monitoring policy.
561    """
562    try:
563        if module.check_mode:
564            process = oneandone_conn.get_monitoring_policy_process(
565                monitoring_policy_id=monitoring_policy_id,
566                process_id=process_id
567            )
568            if process:
569                return True
570            return False
571
572        monitoring_policy = oneandone_conn.delete_monitoring_policy_process(
573            monitoring_policy_id=monitoring_policy_id,
574            process_id=process_id)
575        return monitoring_policy
576    except Exception as ex:
577        module.fail_json(msg=str(ex))
578
579
580def _modify_process(module, oneandone_conn, monitoring_policy_id, process_id, process):
581    """
582    Modifies a monitoring policy process.
583    """
584    try:
585        if module.check_mode:
586            cm_process = oneandone_conn.get_monitoring_policy_process(
587                monitoring_policy_id=monitoring_policy_id,
588                process_id=process_id)
589            if cm_process:
590                return True
591            return False
592
593        monitoring_policy_process = oneandone.client.Process(
594            process=process['process'],
595            alert_if=process['alert_if'],
596            email_notification=process['email_notification']
597        )
598
599        monitoring_policy = oneandone_conn.modify_process(
600            monitoring_policy_id=monitoring_policy_id,
601            process_id=process_id,
602            process=monitoring_policy_process)
603        return monitoring_policy
604    except Exception as ex:
605        module.fail_json(msg=str(ex))
606
607
608def _attach_monitoring_policy_server(module, oneandone_conn, monitoring_policy_id, servers):
609    """
610    Attaches servers to a monitoring policy.
611    """
612    try:
613        attach_servers = []
614
615        for _server_id in servers:
616            server_id = get_server(oneandone_conn, _server_id)
617            attach_server = oneandone.client.AttachServer(
618                server_id=server_id
619            )
620            attach_servers.append(attach_server)
621
622        if module.check_mode:
623            if attach_servers:
624                return True
625            return False
626
627        monitoring_policy = oneandone_conn.attach_monitoring_policy_server(
628            monitoring_policy_id=monitoring_policy_id,
629            servers=attach_servers)
630        return monitoring_policy
631    except Exception as ex:
632        module.fail_json(msg=str(ex))
633
634
635def _detach_monitoring_policy_server(module, oneandone_conn, monitoring_policy_id, server_id):
636    """
637    Detaches a server from a monitoring policy.
638    """
639    try:
640        if module.check_mode:
641            mp_server = oneandone_conn.get_monitoring_policy_server(
642                monitoring_policy_id=monitoring_policy_id,
643                server_id=server_id)
644            if mp_server:
645                return True
646            return False
647
648        monitoring_policy = oneandone_conn.detach_monitoring_policy_server(
649            monitoring_policy_id=monitoring_policy_id,
650            server_id=server_id)
651        return monitoring_policy
652    except Exception as ex:
653        module.fail_json(msg=str(ex))
654
655
656def update_monitoring_policy(module, oneandone_conn):
657    """
658    Updates a monitoring_policy based on input arguments.
659    Monitoring policy ports, processes and servers can be added/removed to/from
660    a monitoring policy. Monitoring policy name, description, email,
661    thresholds for cpu, ram, disk, transfer and internal_ping
662    can be updated as well.
663
664    module : AnsibleModule object
665    oneandone_conn: authenticated oneandone object
666    """
667    try:
668        monitoring_policy_id = module.params.get('monitoring_policy')
669        name = module.params.get('name')
670        description = module.params.get('description')
671        email = module.params.get('email')
672        thresholds = module.params.get('thresholds')
673        add_ports = module.params.get('add_ports')
674        update_ports = module.params.get('update_ports')
675        remove_ports = module.params.get('remove_ports')
676        add_processes = module.params.get('add_processes')
677        update_processes = module.params.get('update_processes')
678        remove_processes = module.params.get('remove_processes')
679        add_servers = module.params.get('add_servers')
680        remove_servers = module.params.get('remove_servers')
681
682        changed = False
683
684        monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy_id, True)
685        if monitoring_policy is None:
686            _check_mode(module, False)
687
688        _monitoring_policy = oneandone.client.MonitoringPolicy(
689            name=name,
690            description=description,
691            email=email
692        )
693
694        _thresholds = None
695
696        if thresholds:
697            threshold_entities = ['cpu', 'ram', 'disk', 'internal_ping', 'transfer']
698
699            _thresholds = []
700            for treshold in thresholds:
701                key = treshold.keys()[0]
702                if key in threshold_entities:
703                    _threshold = oneandone.client.Threshold(
704                        entity=key,
705                        warning_value=treshold[key]['warning']['value'],
706                        warning_alert=str(treshold[key]['warning']['alert']).lower(),
707                        critical_value=treshold[key]['critical']['value'],
708                        critical_alert=str(treshold[key]['critical']['alert']).lower())
709                    _thresholds.append(_threshold)
710
711        if name or description or email or thresholds:
712            _check_mode(module, True)
713            monitoring_policy = oneandone_conn.modify_monitoring_policy(
714                monitoring_policy_id=monitoring_policy['id'],
715                monitoring_policy=_monitoring_policy,
716                thresholds=_thresholds)
717            changed = True
718
719        if add_ports:
720            if module.check_mode:
721                _check_mode(module, _add_ports(module,
722                                               oneandone_conn,
723                                               monitoring_policy['id'],
724                                               add_ports))
725
726            monitoring_policy = _add_ports(module, oneandone_conn, monitoring_policy['id'], add_ports)
727            changed = True
728
729        if update_ports:
730            chk_changed = False
731            for update_port in update_ports:
732                if module.check_mode:
733                    chk_changed |= _modify_port(module,
734                                                oneandone_conn,
735                                                monitoring_policy['id'],
736                                                update_port['id'],
737                                                update_port)
738
739                _modify_port(module,
740                             oneandone_conn,
741                             monitoring_policy['id'],
742                             update_port['id'],
743                             update_port)
744            monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy['id'], True)
745            changed = True
746
747        if remove_ports:
748            chk_changed = False
749            for port_id in remove_ports:
750                if module.check_mode:
751                    chk_changed |= _delete_monitoring_policy_port(module,
752                                                                  oneandone_conn,
753                                                                  monitoring_policy['id'],
754                                                                  port_id)
755
756                _delete_monitoring_policy_port(module,
757                                               oneandone_conn,
758                                               monitoring_policy['id'],
759                                               port_id)
760            _check_mode(module, chk_changed)
761            monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy['id'], True)
762            changed = True
763
764        if add_processes:
765            monitoring_policy = _add_processes(module,
766                                               oneandone_conn,
767                                               monitoring_policy['id'],
768                                               add_processes)
769            _check_mode(module, monitoring_policy)
770            changed = True
771
772        if update_processes:
773            chk_changed = False
774            for update_process in update_processes:
775                if module.check_mode:
776                    chk_changed |= _modify_process(module,
777                                                   oneandone_conn,
778                                                   monitoring_policy['id'],
779                                                   update_process['id'],
780                                                   update_process)
781
782                _modify_process(module,
783                                oneandone_conn,
784                                monitoring_policy['id'],
785                                update_process['id'],
786                                update_process)
787            _check_mode(module, chk_changed)
788            monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy['id'], True)
789            changed = True
790
791        if remove_processes:
792            chk_changed = False
793            for process_id in remove_processes:
794                if module.check_mode:
795                    chk_changed |= _delete_monitoring_policy_process(module,
796                                                                     oneandone_conn,
797                                                                     monitoring_policy['id'],
798                                                                     process_id)
799
800                _delete_monitoring_policy_process(module,
801                                                  oneandone_conn,
802                                                  monitoring_policy['id'],
803                                                  process_id)
804            _check_mode(module, chk_changed)
805            monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy['id'], True)
806            changed = True
807
808        if add_servers:
809            monitoring_policy = _attach_monitoring_policy_server(module,
810                                                                 oneandone_conn,
811                                                                 monitoring_policy['id'],
812                                                                 add_servers)
813            _check_mode(module, monitoring_policy)
814            changed = True
815
816        if remove_servers:
817            chk_changed = False
818            for _server_id in remove_servers:
819                server_id = get_server(oneandone_conn, _server_id)
820
821                if module.check_mode:
822                    chk_changed |= _detach_monitoring_policy_server(module,
823                                                                    oneandone_conn,
824                                                                    monitoring_policy['id'],
825                                                                    server_id)
826
827                _detach_monitoring_policy_server(module,
828                                                 oneandone_conn,
829                                                 monitoring_policy['id'],
830                                                 server_id)
831            _check_mode(module, chk_changed)
832            monitoring_policy = get_monitoring_policy(oneandone_conn, monitoring_policy['id'], True)
833            changed = True
834
835        return (changed, monitoring_policy)
836    except Exception as ex:
837        module.fail_json(msg=str(ex))
838
839
840def create_monitoring_policy(module, oneandone_conn):
841    """
842    Creates a new monitoring policy.
843
844    module : AnsibleModule object
845    oneandone_conn: authenticated oneandone object
846    """
847    try:
848        name = module.params.get('name')
849        description = module.params.get('description')
850        email = module.params.get('email')
851        agent = module.params.get('agent')
852        thresholds = module.params.get('thresholds')
853        ports = module.params.get('ports')
854        processes = module.params.get('processes')
855        wait = module.params.get('wait')
856        wait_timeout = module.params.get('wait_timeout')
857        wait_interval = module.params.get('wait_interval')
858
859        _monitoring_policy = oneandone.client.MonitoringPolicy(name,
860                                                               description,
861                                                               email,
862                                                               agent, )
863
864        _monitoring_policy.specs['agent'] = str(_monitoring_policy.specs['agent']).lower()
865
866        threshold_entities = ['cpu', 'ram', 'disk', 'internal_ping', 'transfer']
867
868        _thresholds = []
869        for treshold in thresholds:
870            key = treshold.keys()[0]
871            if key in threshold_entities:
872                _threshold = oneandone.client.Threshold(
873                    entity=key,
874                    warning_value=treshold[key]['warning']['value'],
875                    warning_alert=str(treshold[key]['warning']['alert']).lower(),
876                    critical_value=treshold[key]['critical']['value'],
877                    critical_alert=str(treshold[key]['critical']['alert']).lower())
878                _thresholds.append(_threshold)
879
880        _ports = []
881        for port in ports:
882            _port = oneandone.client.Port(
883                protocol=port['protocol'],
884                port=port['port'],
885                alert_if=port['alert_if'],
886                email_notification=str(port['email_notification']).lower())
887            _ports.append(_port)
888
889        _processes = []
890        for process in processes:
891            _process = oneandone.client.Process(
892                process=process['process'],
893                alert_if=process['alert_if'],
894                email_notification=str(process['email_notification']).lower())
895            _processes.append(_process)
896
897        _check_mode(module, True)
898        monitoring_policy = oneandone_conn.create_monitoring_policy(
899            monitoring_policy=_monitoring_policy,
900            thresholds=_thresholds,
901            ports=_ports,
902            processes=_processes
903        )
904
905        if wait:
906            wait_for_resource_creation_completion(
907                oneandone_conn,
908                OneAndOneResources.monitoring_policy,
909                monitoring_policy['id'],
910                wait_timeout,
911                wait_interval)
912
913        changed = True if monitoring_policy else False
914
915        _check_mode(module, False)
916
917        return (changed, monitoring_policy)
918    except Exception as ex:
919        module.fail_json(msg=str(ex))
920
921
922def remove_monitoring_policy(module, oneandone_conn):
923    """
924    Removes a monitoring policy.
925
926    module : AnsibleModule object
927    oneandone_conn: authenticated oneandone object
928    """
929    try:
930        mp_id = module.params.get('name')
931        monitoring_policy_id = get_monitoring_policy(oneandone_conn, mp_id)
932        if module.check_mode:
933            if monitoring_policy_id is None:
934                _check_mode(module, False)
935            _check_mode(module, True)
936        monitoring_policy = oneandone_conn.delete_monitoring_policy(monitoring_policy_id)
937
938        changed = True if monitoring_policy else False
939
940        return (changed, {
941            'id': monitoring_policy['id'],
942            'name': monitoring_policy['name']
943        })
944    except Exception as ex:
945        module.fail_json(msg=str(ex))
946
947
948def main():
949    module = AnsibleModule(
950        argument_spec=dict(
951            auth_token=dict(
952                type='str',
953                default=os.environ.get('ONEANDONE_AUTH_TOKEN'),
954                no_log=True),
955            api_url=dict(
956                type='str',
957                default=os.environ.get('ONEANDONE_API_URL')),
958            name=dict(type='str'),
959            monitoring_policy=dict(type='str'),
960            agent=dict(type='str'),
961            email=dict(type='str'),
962            description=dict(type='str'),
963            thresholds=dict(type='list', default=[]),
964            ports=dict(type='list', default=[]),
965            processes=dict(type='list', default=[]),
966            add_ports=dict(type='list', default=[]),
967            update_ports=dict(type='list', default=[]),
968            remove_ports=dict(type='list', default=[]),
969            add_processes=dict(type='list', default=[]),
970            update_processes=dict(type='list', default=[]),
971            remove_processes=dict(type='list', default=[]),
972            add_servers=dict(type='list', default=[]),
973            remove_servers=dict(type='list', default=[]),
974            wait=dict(type='bool', default=True),
975            wait_timeout=dict(type='int', default=600),
976            wait_interval=dict(type='int', default=5),
977            state=dict(type='str', default='present', choices=['present', 'absent', 'update']),
978        ),
979        supports_check_mode=True
980    )
981
982    if not HAS_ONEANDONE_SDK:
983        module.fail_json(msg='1and1 required for this module')
984
985    if not module.params.get('auth_token'):
986        module.fail_json(
987            msg='auth_token parameter is required.')
988
989    if not module.params.get('api_url'):
990        oneandone_conn = oneandone.client.OneAndOneService(
991            api_token=module.params.get('auth_token'))
992    else:
993        oneandone_conn = oneandone.client.OneAndOneService(
994            api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
995
996    state = module.params.get('state')
997
998    if state == 'absent':
999        if not module.params.get('name'):
1000            module.fail_json(
1001                msg="'name' parameter is required to delete a monitoring policy.")
1002        try:
1003            (changed, monitoring_policy) = remove_monitoring_policy(module, oneandone_conn)
1004        except Exception as ex:
1005            module.fail_json(msg=str(ex))
1006    elif state == 'update':
1007        if not module.params.get('monitoring_policy'):
1008            module.fail_json(
1009                msg="'monitoring_policy' parameter is required to update a monitoring policy.")
1010        try:
1011            (changed, monitoring_policy) = update_monitoring_policy(module, oneandone_conn)
1012        except Exception as ex:
1013            module.fail_json(msg=str(ex))
1014
1015    elif state == 'present':
1016        for param in ('name', 'agent', 'email', 'thresholds', 'ports', 'processes'):
1017            if not module.params.get(param):
1018                module.fail_json(
1019                    msg="%s parameter is required for a new monitoring policy." % param)
1020        try:
1021            (changed, monitoring_policy) = create_monitoring_policy(module, oneandone_conn)
1022        except Exception as ex:
1023            module.fail_json(msg=str(ex))
1024
1025    module.exit_json(changed=changed, monitoring_policy=monitoring_policy)
1026
1027
1028if __name__ == '__main__':
1029    main()
1030