Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/na_santricity_discover.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # (c) 2024, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 DOCUMENTATION = """
10 ---
11 module: na_santricity_discover
12 short_description: NetApp E-Series discover E-Series storage systems
13 description: Module searches a subnet range and returns any available E-Series storage systems.
14 author:
15 - Nathan Swartz (@swartzn)
16 - Vu Tran (@VuTran007)
17 options:
18 subnet_mask:
19 description:
20 - This is the IPv4 search range for discovering E-Series storage arrays.
21 - IPv4 subnet mask specified in CIDR form. Example 192.168.1.0/24 would search the range 192.168.1.0 to 192.168.1.255.
22 - Be sure to include all management paths in the search range.
23 type: str
24 required: true
25 ports:
26 description:
27 - This option specifies which ports to be tested during the discovery process.
28 - The first usable port will be used in the returned API url.
29 type: list
30 elements: int
31 default: [8443]
32 required: false
33 proxy_url:
34 description:
35 - Web Services Proxy REST API URL. Example https://192.168.1.100:8443/devmgr/v2/
36 type: str
37 required: false
38 proxy_username:
39 description:
40 - Web Service Proxy username
41 type: str
42 required: false
43 proxy_password:
44 description:
45 - Web Service Proxy user password
46 type: str
47 required: false
48 proxy_validate_certs:
49 description:
50 - Whether to validate Web Service Proxy SSL certificate
51 type: bool
52 default: true
53 required: false
54 prefer_embedded:
55 description:
56 - Give preference to Web Services Embedded when an option exists for both Web Services Proxy and Embedded.
57 - Web Services Proxy will be utilized when available by default.
58 type: bool
59 default: false
60 required: false
61 notes:
62 - Only available for platforms E2800 or later (SANtricity Web Services Embedded REST API must be available).
63 - All E-Series storage systems with SANtricity version 11.62 or later will be discovered.
64 - Only E-Series storage systems without a set admin password running SANtricity versions prior to 11.62 will be discovered.
65 - Use SANtricity Web Services Proxy to discover all systems regardless of SANricity version or password.
66 requirements:
67 - ipaddress
68 """
69
70 EXAMPLES = """
71 - name: Discover all E-Series storage systems on the network.
72 na_santricity_discover:
73 subnet_mask: 192.168.1.0/24
74 """
75
76 RETURN = """
77 systems_found:
78 description: Success message
79 returned: on success
80 type: dict
81 sample: '{"012341234123": {
82 "addresses": ["192.168.1.184", "192.168.1.185"],
83 "api_urls": ["https://192.168.1.184:8443/devmgr/v2/", "https://192.168.1.185:8443/devmgr/v2/"],
84 "label": "ExampleArray01",
85 "proxy_ssid: "",
86 "proxy_required": false},
87 "012341234567": {
88 "addresses": ["192.168.1.23", "192.168.1.24"],
89 "api_urls": ["https://192.168.1.100:8443/devmgr/v2/"],
90 "label": "ExampleArray02",
91 "proxy_ssid": "array_ssid",
92 "proxy_required": true}}'
93 """
94
95 import json
96 import multiprocessing
97 import threading
98 from time import sleep
99
100 from ansible.module_utils.basic import AnsibleModule
101 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import request
102 from ansible.module_utils._text import to_native
103
104 try:
105 import ipaddress
106 except ImportError:
107 HAS_IPADDRESS = False
108 else:
109 HAS_IPADDRESS = True
110
111 try:
112 import urlparse
113 except ImportError:
114 import urllib.parse as urlparse
115
116
117 class NetAppESeriesDiscover:
118 """Discover E-Series storage systems."""
119 MAX_THREAD_POOL_SIZE = 256
120 CPU_THREAD_MULTIPLE = 32
121 SEARCH_TIMEOUT = 30
122 DEFAULT_CONNECTION_TIMEOUT_SEC = 30
123 DEFAULT_DISCOVERY_TIMEOUT_SEC = 300
124
125 def __init__(self):
126 ansible_options = dict(subnet_mask=dict(type="str", required=True),
127 ports=dict(type="list", elements="int", required=False, default=[8443]),
128 proxy_url=dict(type="str", required=False),
129 proxy_username=dict(type="str", required=False),
130 proxy_password=dict(type="str", required=False, no_log=True),
131 proxy_validate_certs=dict(type="bool", default=True, required=False),
132 prefer_embedded=dict(type="bool", default=False, required=False))
133
134 required_together = [["proxy_url", "proxy_username", "proxy_password"]]
135 self.module = AnsibleModule(argument_spec=ansible_options, required_together=required_together)
136 args = self.module.params
137
138 self.subnet_mask = args["subnet_mask"]
139 self.prefer_embedded = args["prefer_embedded"]
140 self.ports = []
141 self.proxy_url = args["proxy_url"]
142 if args["proxy_url"]:
143 parsed_url = list(urlparse.urlparse(args["proxy_url"]))
144 parsed_url[2] = "/devmgr/utils/about"
145 self.proxy_about_url = urlparse.urlunparse(parsed_url)
146 parsed_url[2] = "/devmgr/v2/"
147 self.proxy_url = urlparse.urlunparse(parsed_url)
148 self.proxy_username = args["proxy_username"]
149 self.proxy_password = args["proxy_password"]
150 self.proxy_validate_certs = args["proxy_validate_certs"]
151
152 for port in args["ports"]:
153 try:
154 port_int = int(port)
155 if 0 < port_int < 2 ** 16:
156 self.ports.append(str(port_int))
157 else:
158 self.module.fail_json(msg="Invalid port! Ports must be positive numbers between 0 and 65536.")
159 except (ValueError, TypeError):
160 self.module.fail_json(msg="Invalid port! Ports must be positive numbers between 0 and 65536.")
161
162 self.systems_found = {}
163
164 def check_ip_address(self, systems_found, address):
165 """Determine where an E-Series storage system is available at a specific ip address."""
166 for port in self.ports:
167 if port == "8080":
168 url = "http://%s:%s/" % (address, port)
169 else:
170 url = "https://%s:%s/" % (address, port)
171
172 try:
173 rc, about = request(url + "devmgr/v2/storage-systems/1/about", validate_certs=False, force_basic_auth=False, ignore_errors=True)
174 if about["serialNumber"] in systems_found:
175 systems_found[about["serialNumber"]]["api_urls"].append(url)
176 else:
177 systems_found.update({about["serialNumber"]: {"api_urls": [url], "label": about["name"],
178 "addresses": [], "proxy_ssid": "", "proxy_required": False}})
179 break
180 except Exception as error:
181 try:
182 rc, sa_data = request(url + "devmgr/v2/storage-systems/1/symbol/getSAData", validate_certs=False, force_basic_auth=False,
183 ignore_errors=True)
184 if rc == 401: # Unauthorized
185 self.module.warn(
186 "Fail over and discover any storage system without a set admin password. This will discover systems without a set password"
187 " such as newly deployed storage systems. Address [%s]." % address)
188 # Fail over and discover any storage system without a set admin password. This will cover newly deployed systems.
189 rc, graph = request(url + "graph", validate_certs=False, url_username="admin", url_password="", timeout=self.SEARCH_TIMEOUT)
190 sa_data = graph["sa"]["saData"]
191
192 if sa_data["chassisSerialNumber"] in systems_found:
193 systems_found[sa_data["chassisSerialNumber"]]["api_urls"].append(url)
194 else:
195 systems_found.update({sa_data["chassisSerialNumber"]: {"api_urls": [url], "label": sa_data["storageArrayLabel"],
196 "addresses": [], "proxy_ssid": "", "proxy_required": False}})
197 break
198 except Exception as error:
199 pass
200
201 def no_proxy_discover(self):
202 """Discover E-Series storage systems using embedded web services."""
203 thread_pool_size = min(multiprocessing.cpu_count() * self.CPU_THREAD_MULTIPLE, self.MAX_THREAD_POOL_SIZE)
204 subnet = list(ipaddress.ip_network(u"%s" % self.subnet_mask))
205
206 thread_pool = []
207 search_count = len(subnet)
208 for start in range(0, search_count, thread_pool_size):
209 end = search_count if (search_count - start) < thread_pool_size else start + thread_pool_size
210
211 for address in subnet[start:end]:
212 thread = threading.Thread(target=self.check_ip_address, args=(self.systems_found, address))
213 thread_pool.append(thread)
214 thread.start()
215 for thread in thread_pool:
216 thread.join()
217
218 def verify_proxy_service(self):
219 """Verify proxy url points to a web services proxy."""
220 try:
221 rc, about = request(self.proxy_about_url, validate_certs=self.proxy_validate_certs)
222 if not about["runningAsProxy"]:
223 self.module.fail_json(msg="Web Services is not running as a proxy!")
224 except Exception as error:
225 self.module.fail_json(msg="Proxy is not available! Check proxy_url. Error [%s]." % to_native(error))
226
227 def test_systems_found(self, systems_found, serial, label, addresses):
228 """Verify and build api urls."""
229 api_urls = []
230 for address in addresses:
231 for port in self.ports:
232 if port == "8080":
233 url = "http://%s:%s/devmgr/" % (address, port)
234 else:
235 url = "https://%s:%s/devmgr/" % (address, port)
236
237 try:
238 rc, response = request(url + "utils/about", validate_certs=False, timeout=self.SEARCH_TIMEOUT)
239 api_urls.append(url + "v2/")
240 break
241 except Exception as error:
242 pass
243 systems_found.update({serial: {"api_urls": api_urls,
244 "label": label,
245 "addresses": addresses,
246 "proxy_ssid": "",
247 "proxy_required": False}})
248
249 def proxy_discover(self):
250 """Search for array using it's chassis serial from web services proxy."""
251 self.verify_proxy_service()
252 subnet = ipaddress.ip_network(u"%s" % self.subnet_mask)
253
254 try:
255 rc, request_id = request(self.proxy_url + "discovery", method="POST", validate_certs=self.proxy_validate_certs,
256 force_basic_auth=True, url_username=self.proxy_username, url_password=self.proxy_password,
257 data=json.dumps({"startIP": str(subnet[0]), "endIP": str(subnet[-1]),
258 "connectionTimeout": self.DEFAULT_CONNECTION_TIMEOUT_SEC}))
259
260 # Wait for discover to complete
261 try:
262 for iteration in range(self.DEFAULT_DISCOVERY_TIMEOUT_SEC):
263 rc, discovered_systems = request(self.proxy_url + "discovery?requestId=%s" % request_id["requestId"],
264 validate_certs=self.proxy_validate_certs,
265 force_basic_auth=True, url_username=self.proxy_username, url_password=self.proxy_password)
266 if not discovered_systems["discoverProcessRunning"]:
267 thread_pool = []
268 for discovered_system in discovered_systems["storageSystems"]:
269 addresses = []
270 for controller in discovered_system["controllers"]:
271 addresses.extend(controller["ipAddresses"])
272
273 # Storage systems with embedded web services.
274 if "https" in discovered_system["supportedManagementPorts"] and self.prefer_embedded:
275
276 thread = threading.Thread(target=self.test_systems_found,
277 args=(self.systems_found, discovered_system["serialNumber"], discovered_system["label"], addresses))
278 thread_pool.append(thread)
279 thread.start()
280
281 # Storage systems without embedded web services.
282 else:
283 self.systems_found.update({discovered_system["serialNumber"]: {"api_urls": [self.proxy_url],
284 "label": discovered_system["label"],
285 "addresses": addresses,
286 "proxy_ssid": "",
287 "proxy_required": True}})
288 for thread in thread_pool:
289 thread.join()
290 break
291 sleep(1)
292 else:
293 self.module.fail_json(msg="Timeout waiting for array discovery process. Subnet [%s]" % self.subnet_mask)
294 except Exception as error:
295 self.module.fail_json(msg="Failed to get the discovery results. Error [%s]." % to_native(error))
296 except Exception as error:
297 self.module.fail_json(msg="Failed to initiate array discovery. Error [%s]." % to_native(error))
298
299 def update_proxy_with_proxy_ssid(self):
300 """Determine the current proxy ssid for all discovered-proxy_required storage systems."""
301 # Discover all added storage systems to the proxy.
302 systems = []
303 try:
304 rc, systems = request(self.proxy_url + "storage-systems", validate_certs=self.proxy_validate_certs,
305 force_basic_auth=True, url_username=self.proxy_username, url_password=self.proxy_password)
306 except Exception as error:
307 self.module.fail_json(msg="Failed to ascertain storage systems added to Web Services Proxy.")
308
309 for system_key, system_info in self.systems_found.items():
310 if system_info["proxy_required"]:
311 for system in systems:
312 if system_key == system["chassisSerialNumber"]:
313 system_info["proxy_ssid"] = system["id"]
314
315 def discover(self):
316 """Discover E-Series storage systems."""
317 missing_packages = []
318 if not HAS_IPADDRESS:
319 missing_packages.append("ipaddress")
320
321 if missing_packages:
322 self.module.fail_json(msg="Python packages are missing! Packages [%s]." % ", ".join(missing_packages))
323
324 if self.proxy_url:
325 self.proxy_discover()
326 self.update_proxy_with_proxy_ssid()
327 else:
328 self.no_proxy_discover()
329
330 self.module.exit_json(msg="Discover process complete.", systems_found=self.systems_found, changed=False)
331
332
333 def main():
334 discover = NetAppESeriesDiscover()
335 discover.discover()
336
337
338 if __name__ == "__main__":
339 main()