Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_monitoring_query.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: appliance_monitoring_query
12 short_description: Get monitoring data.
13 description: Get monitoring data.
14 options:
15 end_time:
16 description:
17 - End time in UTC This parameter is mandatory.
18 required: true
19 type: str
20 function:
21 choices:
22 - AVG
23 - COUNT
24 - MAX
25 - MIN
26 description:
27 - I(function_type) enumerated type Defines aggregation function This parameter
28 is mandatory.
29 required: true
30 type: str
31 interval:
32 choices:
33 - DAY1
34 - HOURS2
35 - HOURS6
36 - MINUTES30
37 - MINUTES5
38 description:
39 - I(interval_type) enumerated type Defines interval between the values in
40 hours and mins, for which aggregation will apply This parameter is mandatory.
41 required: true
42 type: str
43 names:
44 description:
45 - 'monitored item IDs Ex: CPU, MEMORY'
46 - When clients pass a value of this structure as a parameter, the field must
47 contain the id of resources returned by M(vmware.vmware_rest.appliance_monitoring_info).
48 elements: str
49 required: true
50 type: list
51 session_timeout:
52 description:
53 - 'Timeout settings for client session. '
54 - 'The maximal number of seconds for the whole operation including connection
55 establishment, request sending and response. '
56 - The default value is 300s.
57 type: float
58 version_added: 2.1.0
59 start_time:
60 description:
61 - Start time in UTC This parameter is mandatory.
62 required: true
63 type: str
64 vcenter_hostname:
65 description:
66 - The hostname or IP address of the vSphere vCenter
67 - If the value is not specified in the task, the value of environment variable
68 C(VMWARE_HOST) will be used instead.
69 required: true
70 type: str
71 vcenter_password:
72 description:
73 - The vSphere vCenter password
74 - If the value is not specified in the task, the value of environment variable
75 C(VMWARE_PASSWORD) will be used instead.
76 required: true
77 type: str
78 vcenter_rest_log_file:
79 description:
80 - 'You can use this optional parameter to set the location of a log file. '
81 - 'This file will be used to record the HTTP REST interaction. '
82 - 'The file will be stored on the host that runs the module. '
83 - 'If the value is not specified in the task, the value of '
84 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
85 type: str
86 vcenter_username:
87 description:
88 - The vSphere vCenter username
89 - If the value is not specified in the task, the value of environment variable
90 C(VMWARE_USER) will be used instead.
91 required: true
92 type: str
93 vcenter_validate_certs:
94 default: true
95 description:
96 - Allows connection when SSL certificates are not valid. Set to C(false) when
97 certificates are not trusted.
98 - If the value is not specified in the task, the value of environment variable
99 C(VMWARE_VALIDATE_CERTS) will be used instead.
100 type: bool
101 author:
102 - Ansible Cloud Team (@ansible-collections)
103 version_added: 2.0.0
104 requirements:
105 - vSphere 7.0.3 or greater
106 - python >= 3.6
107 - aiohttp
108 notes:
109 - Tested on vSphere 7.0.3
110 """
111
112 EXAMPLES = r"""
113 - name: Query the monitoring backend
114 vmware.vmware_rest.appliance_monitoring_query:
115 end_time: 2021-04-14 09:34:56+00:00
116 start_time: 2021-04-14 08:34:56+00:00
117 names:
118 - mem.total
119 interval: MINUTES5
120 function: AVG
121 register: result
122 """
123 RETURN = r"""
124 # content generated by the update_return_section callback# task: Query the monitoring backend
125 value:
126 description: Query the monitoring backend
127 returned: On success
128 sample:
129 - data:
130 - ''
131 - ''
132 - ''
133 - ''
134 - ''
135 - ''
136 - ''
137 - ''
138 - ''
139 - ''
140 - ''
141 - ''
142 - ''
143 end_time: '2021-04-14T09:34:56.000Z'
144 function: AVG
145 interval: MINUTES5
146 name: mem.total
147 start_time: '2021-04-14T08:34:56.000Z'
148 type: list
149 """
150
151
152 # This structure describes the format of the data expected by the end-points
153 PAYLOAD_FORMAT = {
154 "query": {
155 "query": {
156 "end_time": "end_time",
157 "function": "function",
158 "interval": "interval",
159 "names": "names",
160 "start_time": "start_time",
161 },
162 "body": {},
163 "path": {},
164 }
165 } # pylint: disable=line-too-long
166
167 from ansible.module_utils.basic import env_fallback
168 import os
169
170 if os.getenv("VMWARE_ENABLE_TURBO", False):
171 try:
172 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
173 AnsibleTurboModule as AnsibleModule,
174 )
175
176 AnsibleModule.collection_name = "vmware.vmware_rest"
177 except ImportError:
178 from ansible.module_utils.basic import AnsibleModule
179 else:
180 from ansible.module_utils.basic import AnsibleModule
181
182 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
183 exists,
184 gen_args,
185 get_subdevice_type,
186 open_session,
187 prepare_payload,
188 session_timeout,
189 update_changed_flag,
190 )
191
192
193 def prepare_argument_spec():
194 argument_spec = {
195 "vcenter_hostname": dict(
196 type="str",
197 required=True,
198 fallback=(env_fallback, ["VMWARE_HOST"]),
199 ),
200 "vcenter_username": dict(
201 type="str",
202 required=True,
203 fallback=(env_fallback, ["VMWARE_USER"]),
204 ),
205 "vcenter_password": dict(
206 type="str",
207 required=True,
208 no_log=True,
209 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
210 ),
211 "vcenter_validate_certs": dict(
212 type="bool",
213 required=False,
214 default=True,
215 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
216 ),
217 "vcenter_rest_log_file": dict(
218 type="str",
219 required=False,
220 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
221 ),
222 "session_timeout": dict(
223 type="float",
224 required=False,
225 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
226 ),
227 }
228
229 argument_spec["end_time"] = {"required": True, "type": "str"}
230 argument_spec["function"] = {
231 "required": True,
232 "type": "str",
233 "choices": ["AVG", "COUNT", "MAX", "MIN"],
234 }
235 argument_spec["interval"] = {
236 "required": True,
237 "type": "str",
238 "choices": ["DAY1", "HOURS2", "HOURS6", "MINUTES30", "MINUTES5"],
239 }
240 argument_spec["names"] = {"required": True, "type": "list", "elements": "str"}
241 argument_spec["start_time"] = {"required": True, "type": "str"}
242
243 return argument_spec
244
245
246 async def main():
247 required_if = list([])
248
249 module_args = prepare_argument_spec()
250 module = AnsibleModule(
251 argument_spec=module_args, required_if=required_if, supports_check_mode=False
252 )
253 if not module.params["vcenter_hostname"]:
254 module.fail_json("vcenter_hostname cannot be empty")
255 if not module.params["vcenter_username"]:
256 module.fail_json("vcenter_username cannot be empty")
257 if not module.params["vcenter_password"]:
258 module.fail_json("vcenter_password cannot be empty")
259 try:
260 session = await open_session(
261 vcenter_hostname=module.params["vcenter_hostname"],
262 vcenter_username=module.params["vcenter_username"],
263 vcenter_password=module.params["vcenter_password"],
264 validate_certs=module.params["vcenter_validate_certs"],
265 log_file=module.params["vcenter_rest_log_file"],
266 )
267 except Exception as err:
268 if hasattr(err, "get_message"):
269 module.fail_json(err.get_message())
270 else:
271 module.fail_json(str(err))
272 result = await entry_point(module, session)
273 module.exit_json(**result)
274
275
276 # template: default_module.j2
277 def build_url(params):
278 return ("https://{vcenter_hostname}" "/api/appliance/monitoring/query").format(
279 **params
280 )
281
282
283 async def entry_point(module, session):
284
285 func = globals()["_query"]
286
287 return await func(module.params, session)
288
289
290 async def _query(params, session):
291 _in_query_parameters = PAYLOAD_FORMAT["query"]["query"].keys()
292 payload = prepare_payload(params, PAYLOAD_FORMAT["query"])
293 subdevice_type = get_subdevice_type("/api/appliance/monitoring/query")
294 if subdevice_type and not params[subdevice_type]:
295 _json = await exists(params, session, build_url(params))
296 if _json:
297 params[subdevice_type] = _json["id"]
298 _url = (
299 "https://{vcenter_hostname}"
300 # aa
301 "/api/appliance/monitoring/query"
302 ).format(**params) + gen_args(params, _in_query_parameters)
303 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
304 try:
305 if resp.headers["Content-Type"] == "application/json":
306 _json = await resp.json()
307 except KeyError:
308 _json = {}
309 if "value" not in _json: # 7.0.2
310 _json = {"value": _json}
311
312 return await update_changed_flag(_json, resp.status, "query")
313
314
315 if __name__ == "__main__":
316 import asyncio
317
318 current_loop = asyncio.new_event_loop()
319 try:
320 asyncio.set_event_loop(current_loop)
321 current_loop.run_until_complete(main())
322 finally:
323 current_loop.close()