Debian Codegraph @

ansible_collections/cisco/meraki/plugins/action/devices_camera_sense.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2021, Cisco Systems
5 # GNU General Public License v3.0+ (see LICENSE or
6 # https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10 from ansible.plugins.action import ActionBase
11 try:
12 from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import (
13 AnsibleArgSpecValidator, )
14 except ImportError:
15 ANSIBLE_UTILS_IS_INSTALLED = False
16 else:
17 ANSIBLE_UTILS_IS_INSTALLED = True
18 from ansible.errors import AnsibleActionFail
19 from ansible_collections.cisco.meraki.plugins.plugin_utils.meraki import (
20 MERAKI,
21 meraki_argument_spec,
22 meraki_compare_equality2,
23 get_dict_result,
24 )
25 from ansible_collections.cisco.meraki.plugins.plugin_utils.exceptions import (
26 InconsistentParameters,
27 )
28
29 # Get common arguments specification
30 argument_spec = meraki_argument_spec()
31 # Add arguments specific for this module
32 argument_spec.update(dict(
33 state=dict(type="str", default="present", choices=["present"]),
34 senseEnabled=dict(type="bool"),
35 mqttBrokerId=dict(type="str"),
36 audioDetection=dict(type="dict"),
37 detectionModelId=dict(type="str"),
38 serial=dict(type="str"),
39 ))
40
41 required_if = [
42 ("state", "present", ["serial"], True),
43 ]
44 required_one_of = []
45 mutually_exclusive = []
46 required_together = []
47
48
49 class DevicesCameraSense(object):
50 def __init__(self, params, meraki):
51 self.meraki = meraki
52 self.new_object = dict(
53 senseEnabled=params.get("senseEnabled"),
54 mqttBrokerId=params.get("mqttBrokerId"),
55 audioDetection=params.get("audioDetection"),
56 detectionModelId=params.get("detectionModelId"),
57 serial=params.get("serial"),
58 )
59
60 def get_all_params(self, name=None, id=None):
61 new_object_params = {}
62 if self.new_object.get('serial') is not None or self.new_object.get(
63 'serial') is not None:
64 new_object_params['serial'] = self.new_object.get('serial')
65 return new_object_params
66
67 def update_all_params(self):
68 new_object_params = {}
69 if self.new_object.get('senseEnabled') is not None or self.new_object.get(
70 'sense_enabled') is not None:
71 new_object_params['senseEnabled'] = self.new_object.get(
72 'senseEnabled')
73 if self.new_object.get('mqttBrokerId') is not None or self.new_object.get(
74 'mqtt_broker_id') is not None:
75 new_object_params['mqttBrokerId'] = self.new_object.get(
76 'mqttBrokerId') or self.new_object.get('mqtt_broker_id')
77 if self.new_object.get('audioDetection') is not None or self.new_object.get(
78 'audio_detection') is not None:
79 new_object_params['audioDetection'] = self.new_object.get(
80 'audioDetection') or self.new_object.get('audio_detection')
81 if self.new_object.get('detectionModelId') is not None or self.new_object.get(
82 'detection_model_id') is not None:
83 new_object_params['detectionModelId'] = self.new_object.get(
84 'detectionModelId') or self.new_object.get('detection_model_id')
85 if self.new_object.get('serial') is not None or self.new_object.get(
86 'serial') is not None:
87 new_object_params['serial'] = self.new_object.get('serial') or \
88 self.new_object.get('serial')
89 return new_object_params
90
91 def get_object_by_name(self, name):
92 result = None
93 # NOTE: Does not have a get by name method, using get all
94 try:
95 items = self.meraki.exec_meraki(
96 family="camera",
97 function="getDeviceCameraSense",
98 params=self.get_all_params(name=name),
99 )
100 if isinstance(items, dict):
101 if 'response' in items:
102 items = items.get('response')
103 result = get_dict_result(items, 'name', name)
104 if result is None:
105 result = items
106 except Exception as e:
107 print("Error: ", e)
108 result = None
109 return result
110
111 def get_object_by_id(self, id):
112 result = None
113 # NOTE: Does not have a get by id method or it is in another action
114 return result
115
116 def exists(self):
117 prev_obj = None
118 id_exists = False
119 name_exists = False
120 o_id = self.new_object.get("serial")
121 name = self.new_object.get("name")
122 if o_id:
123 prev_obj = self.get_object_by_name(o_id)
124 id_exists = prev_obj is not None and isinstance(prev_obj, dict)
125 if not id_exists and name:
126 prev_obj = self.get_object_by_name(name)
127 name_exists = prev_obj is not None and isinstance(prev_obj, dict)
128 if name_exists:
129 _id = prev_obj.get("id")
130 if id_exists and name_exists and o_id != _id:
131 raise InconsistentParameters(
132 "The 'id' and 'name' params don't refer to the same object")
133 if _id:
134 self.new_object.update(dict(id=_id))
135 it_exists = prev_obj is not None and isinstance(prev_obj, dict)
136 return (it_exists, prev_obj)
137
138 def requires_update(self, current_obj):
139 requested_obj = self.new_object
140
141 obj_params = [
142 ("senseEnabled", "senseEnabled"),
143 ("mqttBrokerId", "mqttBrokerId"),
144 ("audioDetection", "audioDetection"),
145 ("detectionModelId", "detectionModelId"),
146 ("serial", "serial"),
147 ]
148 # Method 1. Params present in request (Ansible) obj are the same as the current (ISE) params
149 # If any does not have eq params, it requires update
150 return any(
151 not meraki_compare_equality2(
152 current_obj.get(meraki_param),
153 requested_obj.get(ansible_param)) for (
154 meraki_param,
155 ansible_param) in obj_params)
156
157 def update(self):
158 id = self.new_object.get("id")
159 name = self.new_object.get("name")
160 result = None
161 result = self.meraki.exec_meraki(
162 family="camera",
163 function="updateDeviceCameraSense",
164 params=self.update_all_params(),
165 op_modifies=True,
166 )
167 return result
168
169
170 class ActionModule(ActionBase):
171 def __init__(self, *args, **kwargs):
172 if not ANSIBLE_UTILS_IS_INSTALLED:
173 raise AnsibleActionFail(
174 "ansible.utils is not installed. Execute 'ansible-galaxy collection install ansible.utils'")
175 super(ActionModule, self).__init__(*args, **kwargs)
176 self._supports_async = False
177 self._supports_check_mode = False
178 self._result = None
179
180 # Checks the supplied parameters against the argument spec for this module
181 def _check_argspec(self):
182 aav = AnsibleArgSpecValidator(
183 data=self._task.args,
184 schema=dict(argument_spec=argument_spec),
185 schema_format="argspec",
186 schema_conditionals=dict(
187 required_if=required_if,
188 required_one_of=required_one_of,
189 mutually_exclusive=mutually_exclusive,
190 required_together=required_together,
191 ),
192 name=self._task.action,
193 )
194 valid, errors, self._task.args = aav.validate()
195 if not valid:
196 raise AnsibleActionFail(errors)
197
198 def run(self, tmp=None, task_vars=None):
199 self._task.diff = False
200 self._result = super(ActionModule, self).run(tmp, task_vars)
201 self._result["changed"] = False
202 self._check_argspec()
203
204 meraki = MERAKI(self._task.args)
205 obj = DevicesCameraSense(self._task.args, meraki)
206
207 state = self._task.args.get("state")
208
209 response = None
210 if state == "present":
211 (obj_exists, prev_obj) = obj.exists()
212 if obj_exists:
213 if obj.requires_update(prev_obj):
214 response = obj.update()
215 meraki.object_updated()
216 else:
217 response = prev_obj
218 meraki.object_already_present()
219 else:
220 meraki.fail_json(
221 "Object does not exists, plugin only has update")
222
223 self._result.update(dict(meraki_response=response))
224 self._result.update(meraki.exit_json())
225 return self._result