Debian Codegraph @

ansible_collections/netapp/storagegrid/plugins/module_utils/netapp.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) 2020, NetApp Ansible Team <[email protected]>
8 # All rights reserved.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 from __future__ import absolute_import, division, print_function
30
31 __metaclass__ = type
32
33 from ansible.module_utils.basic import missing_required_lib
34
35 COLLECTION_VERSION = "21.16.0"
36
37 try:
38 import requests
39
40 HAS_REQUESTS = True
41 except ImportError:
42 HAS_REQUESTS = False
43
44
45 POW2_BYTE_MAP = dict(
46 # Here, 1 kb = 1024
47 bytes=1,
48 b=1,
49 kb=1024,
50 mb=1024**2,
51 gb=1024**3,
52 tb=1024**4,
53 pb=1024**5,
54 eb=1024**6,
55 zb=1024**7,
56 yb=1024**8,
57 )
58
59
60 def na_storagegrid_host_argument_spec():
61 return dict(
62 api_url=dict(required=True, type="str"),
63 validate_certs=dict(required=False, type="bool", default=True),
64 auth_token=dict(required=True, type="str", no_log=True),
65 )
66
67
68 class SGRestAPI(object):
69 def __init__(self, module, timeout=60):
70 self.module = module
71 self.auth_token = self.module.params["auth_token"]
72 self.api_url = self.module.params["api_url"]
73 self.verify = self.module.params["validate_certs"]
74 self.timeout = timeout
75 self.check_required_library()
76 self.sg_version = dict(major=-1, minor=-1, full="", valid=False)
77
78 def check_required_library(self):
79 if not HAS_REQUESTS:
80 self.module.fail_json(msg=missing_required_lib("requests"))
81
82 def send_request(self, method, api, params=None, json=None, files=None):
83 """send http request and process reponse, including error conditions"""
84 url = "%s/%s" % (self.api_url, api)
85 status_code = None
86 content = None
87 json_dict = None
88 json_error = None
89 error_details = None
90 headers = {
91 "Authorization": "Bearer {}".format(self.auth_token),
92 "Cache-Control": "no-cache",
93 }
94
95 def get_json(response):
96 """extract json, and error message if present"""
97 try:
98 json = response.json()
99
100 except ValueError:
101 return None, None
102 success_code = [200, 201, 202, 204]
103 if response.status_code not in success_code:
104 error = json.get("message")
105 if json.get("errors"):
106 error.update({"errors": json.get("errors")})
107 else:
108 error = None
109 return json, error
110
111 try:
112 if files:
113 headers["Content-Type"] = "multipart/form-data"
114 response = requests.request(
115 method,
116 url,
117 headers=headers,
118 timeout=self.timeout,
119 json=json,
120 files=files,
121 verify=self.verify,
122 params=params,
123 )
124 else:
125 headers["Content-Type"] = "application/json"
126 response = requests.request(
127 method,
128 url,
129 headers=headers,
130 timeout=self.timeout,
131 json=json,
132 verify=self.verify,
133 params=params,
134 )
135
136 # check if response is binary file
137 content_type = response.headers.get("content-type", "").lower()
138 if "application/zip" in content_type or "octet-stream" in content_type:
139 return response, None
140
141 # If the response was successful, no Exception will be raised
142 # Add status_code to the json_dict
143 json_dict, json_error = get_json(response)
144 if json_dict is None:
145 json_dict = {}
146 json_dict["status_code"] = response.status_code
147 except requests.exceptions.HTTPError as err:
148 __, json_error = get_json(response)
149 if json_error is None:
150 error_details = str(err)
151 except requests.exceptions.ConnectionError as err:
152 error_details = str(err)
153 except Exception as err:
154 error_details = str(err)
155 if json_error is not None:
156 error_details = json_error
157
158 return json_dict, error_details
159
160 # If an error was reported in the json payload, it is handled below
161 def get(self, api, params=None):
162 method = "GET"
163 return self.send_request(method, api, params)
164
165 def post(self, api, data=None, params=None, files=None):
166 method = "POST"
167 return self.send_request(method, api, params, json=data, files=files)
168
169 def patch(self, api, data, params=None):
170 method = "PATCH"
171 return self.send_request(method, api, params, json=data)
172
173 def put(self, api, data, params=None):
174 method = "PUT"
175 return self.send_request(method, api, params, json=data)
176
177 def delete(self, api, data, params=None):
178 method = "DELETE"
179 return self.send_request(method, api, params, json=data)
180
181 def get_sg_product_version(self, api_root="grid"):
182 method = "GET"
183 api = "api/v3/%s/config/product-version" % api_root
184 message, error = self.send_request(method, api, params={})
185 if error:
186 self.module.fail_json(msg=error)
187 self.set_version(message)
188
189 def set_version(self, message):
190 try:
191 product_version = message.get("data", "not found").get("productVersion", "not_found")
192 except AttributeError:
193 self.sg_version["valid"] = False
194 return
195
196 self.sg_version["major"], self.sg_version["minor"] = list(map(int, product_version.split(".")[0:2]))
197 self.sg_version["full"] = product_version
198 self.sg_version["valid"] = True
199
200 def get_sg_version(self):
201 if self.sg_version["valid"]:
202 return self.sg_version["major"], self.sg_version["minor"]
203 return -1, -1
204
205 def get_api_version(self):
206 """ Return 'v3' if SG version is less than 11.8, else return 'v4' """
207 if self.get_sg_version() < (11, 8):
208 return 'v3'
209 else:
210 return 'v4'
211
212 def meets_sg_minimum_version(self, minimum_major, minimum_minor):
213 return self.get_sg_version() >= (minimum_major, minimum_minor)
214
215 def requires_sg_version(self, module_or_option, version):
216 return "%s requires StorageGRID %s or later." % (module_or_option, version)
217
218 def fail_if_not_sg_minimum_version(self, module_or_option, minimum_major, minimum_minor):
219 version = self.get_sg_version()
220 if version < (minimum_major, minimum_minor):
221 msg = "Error: " + self.requires_sg_version(module_or_option, "%d.%d" % (minimum_major, minimum_minor))
222 msg += " Found: %s.%s." % version
223 self.module.fail_json(msg=msg)
224
225
226 def na_storagegrid_pge_argument_spec():
227 """Argument spec for PGE modules"""
228 return dict(
229 api_url=dict(required=True, type="str"),
230 validate_certs=dict(required=False, type="bool", default=True),
231 )
232
233
234 class PgeRestAPI(SGRestAPI):
235 """
236 StorageGRID PGE API wrapper class
237 """
238 def __init__(self, module, timeout=60):
239 self.module = module
240 self.api_url = self.module.params["api_url"]
241 self.verify = self.module.params["validate_certs"]
242 self.timeout = timeout
243 self.check_required_library()
244
245 def send_request(self, method, api, params=None, json=None, files=None):
246 """send http request for PGE endpoints without Authorization header"""
247 url = "%s/%s" % (self.api_url, api)
248 status_code = None
249 content = None
250 json_dict = None
251 json_error = None
252 error_details = None
253 headers = {
254 "Content-type": "application/json",
255 "Cache-Control": "no-cache",
256 }
257
258 def get_json(response):
259 """extract json, and error message if present"""
260 try:
261 json = response.json()
262
263 except ValueError:
264 return None, None
265 success_code = [200, 201, 202, 204]
266 if response.status_code not in success_code:
267 error = json.get("message")
268 else:
269 error = None
270 return json, error
271
272 try:
273 response = requests.request(
274 method,
275 url,
276 headers=headers,
277 timeout=self.timeout,
278 json=json,
279 verify=self.verify,
280 params=params,
281 )
282 status_code = response.status_code
283 # If the response was successful, no Exception will be raised
284 json_dict, json_error = get_json(response)
285 except requests.exceptions.HTTPError as err:
286 __, json_error = get_json(response)
287 if json_error is None:
288 error_details = str(err)
289 except requests.exceptions.ConnectionError as err:
290 error_details = str(err)
291 except Exception as err:
292 error_details = str(err)
293 if json_error is not None:
294 error_details = json_error
295
296 return json_dict, error_details
297
298
299 class SGAuthGenRestAPI(SGRestAPI):
300 """
301 StorageGRID API wrapper class
302 """
303 def __init__(self, module, timeout=60):
304 self.module = module
305 self.hostname = self.module.params["hostname"]
306 self.username = self.module.params["username"]
307 self.password = self.module.params["password"]
308 self.verify = self.module.params["validate_certs"]
309 self.timeout = timeout
310 self.check_required_library()
311
312 def send_request(self, method, api, params=None, json=None, files=None):
313 """send http request for SG endpoints without Authorization header"""
314 if not self.hostname.startswith("https://"):
315 self.hostname = "https://" + self.hostname
316 url = "%s/%s" % (self.hostname, api)
317 status_code = None
318 content = None
319 json_dict = None
320 json_error = None
321 error_details = None
322 headers = {
323 "Content-type": "application/json",
324 "Cache-Control": "no-cache",
325 }
326
327 def get_json(response):
328 """extract json, and error message if present"""
329 try:
330 json = response.json()
331
332 except ValueError:
333 return None, None
334 success_code = [200, 201, 202, 204]
335 if response.status_code not in success_code:
336 error = json.get("message")
337 else:
338 error = None
339 return json, error
340
341 try:
342 response = requests.request(
343 method,
344 url,
345 headers=headers,
346 timeout=self.timeout,
347 json=json,
348 verify=self.verify,
349 params=params,
350 )
351 status_code = response.status_code
352 # If the response was successful, no Exception will be raised
353 json_dict, json_error = get_json(response)
354 except requests.exceptions.HTTPError as err:
355 __, json_error = get_json(response)
356 if json_error is None:
357 error_details = str(err)
358 except requests.exceptions.ConnectionError as err:
359 error_details = str(err)
360 except Exception as err:
361 error_details = str(err)
362 if json_error is not None:
363 error_details = json_error
364
365 return json_dict, error_details