Debian Codegraph @

ansible_collections/purestorage/flashblade/plugins/modules/purefb_connect.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2020, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefb_connect
20 version_added: '1.0.0'
21 short_description: Manage replication connections between two FlashBlades
22 description:
23 - Manage replication connections to specified remote FlashBlade system
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 state:
28 description:
29 - Create or delete replication connection
30 default: present
31 type: str
32 choices: [ absent, present ]
33 encrypted:
34 description:
35 - Define if replication connection is encrypted
36 type: bool
37 default: false
38 target_url:
39 description:
40 - Management IP address of target FlashBlade system
41 type: str
42 required: true
43 target_api:
44 description:
45 - API token for target FlashBlade system
46 type: str
47 target_repl:
48 description:
49 - Replication IP address of target FlashBlade system
50 - If not set at time of connection creation, will default to
51 all the replication addresses available on the target array
52 at the time of connection creation.
53 type: list
54 elements: str
55 version_added: "1.9.0"
56 default_limit:
57 description:
58 - Default maximum bandwidth threshold for outbound traffic in bytes.
59 - B, K, M, or G units. See examples.
60 - Must be 0 or between 5MB and 28GB
61 - Once exceeded, bandwidth throttling occurs
62 type: str
63 version_added: "1.9.0"
64 window_limit:
65 description:
66 - Maximum bandwidth threshold for outbound traffic during the specified
67 time range in bytes.
68 - B, K, M, or G units. See examples.
69 - Must be 0 or between 5MB and 28GB
70 - Once exceeded, bandwidth throttling occurs
71 type: str
72 version_added: "1.9.0"
73 window_start:
74 description:
75 - The window start time.
76 - The time must be set to the hour.
77 type: str
78 version_added: "1.9.0"
79 window_end:
80 description:
81 - The window end time.
82 - The time must be set to the hour.
83 type: str
84 version_added: "1.9.0"
85 context:
86 description:
87 - Name of fleet member on which to perform the operation.
88 - This requires the array receiving the request is a member of a fleet
89 and the context name to be a member of the same fleet.
90 type: str
91 default: ""
92 version_added: "1.22.0"
93 extends_documentation_fragment:
94 - purestorage.flashblade.purestorage.fb
95 """
96
97 EXAMPLES = r"""
98 - name: Create a connection to remote FlashBlade system
99 purestorage.flashblade.purefb_connect:
100 target_url: 10.10.10.20
101 target_api: T-b3275b1c-8958-4190-9052-eb46b0bd09f8
102 fb_url: 10.10.10.2
103 api_token: T-91528421-fe42-47ee-bcb1-47eefb0a9220
104 - name: Create a connection to remote FlashBlade system with bandwidth limits
105 purestorage.flashblade.purefb_connect:
106 target_url: 10.10.10.20
107 target_api: T-b3275b1c-8958-4190-9052-eb46b0bd09f8
108 window_limit: 28G
109 window_start: 1AM
110 window_end: 7AM
111 default_limit: 5M
112 fb_url: 10.10.10.2
113 api_token: T-91528421-fe42-47ee-bcb1-47eefb0a9220
114 - name: Delete connection to target FlashBlade system
115 purestorage.flashblade.purefb_connect:
116 state: absent
117 target_url: 10.10.10.20
118 target_api: T-b3275b1c-8958-4190-9052-eb46b0bd09f8
119 fb_url: 10.10.10.2
120 api_token: T-91528421-fe42-47ee-bcb1-47eefb0a9220
121 """
122
123 RETURN = r"""
124 """
125
126 HAS_PYPURECLIENT = True
127 try:
128 from pypureclient.flashblade import (
129 Client,
130 ArrayConnectionPost,
131 TimeWindow,
132 Throttle,
133 )
134 except ImportError:
135 HAS_PYPURECLIENT = False
136
137 from ansible.module_utils.basic import AnsibleModule, human_to_bytes
138 from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
139 get_system,
140 purefb_argument_spec,
141 )
142
143
144 CONTEXT_API_VERSION = "2.17"
145 FAN_IN_MAXIMUM = 5
146 FAN_OUT_MAXIMUM = 5
147
148
149 def _convert_to_millisecs(hour_str: str) -> int:
150 """Convert a 12-hour formatted time string (e.g., '02AM', '12PM') to milliseconds since midnight."""
151 time_part = int(hour_str[:-2])
152 period = hour_str[-2:]
153
154 if period == "AM":
155 return 0 if time_part == 12 else time_part * 3600000
156 # PM
157 return 12 * 3600000 if time_part == 12 else (time_part + 12) * 3600000
158
159
160 def _check_connected(module, blade):
161 api_version = list(blade.get_versions().items)
162 if CONTEXT_API_VERSION in api_version:
163 connected_blades = list(
164 blade.get_array_connections(context_names=[module.params["context"]]).items
165 )
166 else:
167 connected_blades = list(blade.get_array_connections().items)
168 for target in range(len(connected_blades)):
169 if connected_blades[target].management_address is None:
170 remote_system = Client(
171 target=module.params["target_url"],
172 api_token=module.params["target_api"],
173 )
174 res = remote_system.get_arrays()
175 if res.status_code != 200:
176 module.fail_json(
177 msg="Failed to connect to remote array {0}.".format(
178 module.params["target_url"]
179 )
180 )
181 remote_array = list(res.items)[0].name
182 if connected_blades[target].remote.name == remote_array:
183 return connected_blades[target]
184 if connected_blades[target].management_address == module.params[
185 "target_url"
186 ] and connected_blades[target].status in [
187 "connected",
188 "connecting",
189 "partially_connected",
190 ]:
191 return connected_blades[target]
192 return None
193
194
195 def break_connection(module, blade, target_blade):
196 """Break connection between arrays"""
197 api_version = list(blade.get_versions().items)
198 changed = True
199 if not module.check_mode:
200 if CONTEXT_API_VERSION in api_version:
201 source_blade = (
202 blade.get_arrays(context_names=[module.params["context"]]).items[0].name
203 )
204 else:
205 source_blade = blade.get_arrays().items[0].name
206 if target_blade.management_address is None:
207 module.fail_json(
208 msg="Disconnect can only happen from the array that formed the connection"
209 )
210 if CONTEXT_API_VERSION in api_version:
211 res = blade.delete_array_connections(
212 remote_names=[target_blade.remote.name],
213 context_names=[module.params["context"]],
214 )
215 else:
216 res = blade.delete_array_connections(
217 remote_names=[target_blade.remote.name]
218 )
219 if res.status_code != 200:
220 module.fail_json(
221 msg="Failed to disconnect {0} from {1}. Error: {2}".format(
222 target_blade.remote.name, source_blade, res.errors[0].message
223 )
224 )
225 module.exit_json(changed=changed)
226
227
228 def create_connection(module, blade):
229 """Create connection between REST 2 capable arrays"""
230 api_version = list(blade.get_versions().items)
231 changed = True
232 if CONTEXT_API_VERSION in api_version:
233 res = blade.get_array_connections(context_names=[module.params["context"]])
234 else:
235 res = blade.get_array_connections()
236 if res.total_item_count >= FAN_OUT_MAXIMUM:
237 module.fail_json(
238 msg="FlashBlade fan-out maximum of {0} already reached".format(
239 FAN_OUT_MAXIMUM
240 )
241 )
242 try:
243 remote_system = Client(
244 target=module.params["target_url"], api_token=module.params["target_api"]
245 )
246 except Exception:
247 module.fail_json(
248 msg="Failed to connect to remote array {0}.".format(
249 module.params["target_url"]
250 )
251 )
252 remote_array = list(remote_system.get_arrays().items)[0].name
253 remote_conn_cnt = remote_system.get_array_connections().total_item_count
254 if remote_conn_cnt >= FAN_IN_MAXIMUM:
255 module.fail_json(
256 msg="Remote array {0} already connected to {1} other array. Fan-In not supported".format(
257 remote_array, remote_conn_cnt
258 )
259 )
260 connection_key = list(remote_system.post_array_connections_connection_key().items)[
261 0
262 ].connection_key
263
264 if module.params["default_limit"] or module.params["window_limit"]:
265 if module.params["window_limit"]:
266 if not module.params["window_start"]:
267 module.params["window_start"] = "12AM"
268 if not module.params["window_end"]:
269 module.params["window_end"] = "12AM"
270 window = TimeWindow(
271 start=_convert_to_millisecs(module.params["window_start"]),
272 end=_convert_to_millisecs(module.params["window_end"]),
273 )
274 if module.params["window_limit"] and module.params["default_limit"]:
275 throttle = Throttle(
276 default_limit=human_to_bytes(module.params["default_limit"]),
277 window_limit=human_to_bytes(module.params["window_limit"]),
278 window=window,
279 )
280 elif module.params["window_limit"] and not module.params["default_limit"]:
281 throttle = Throttle(
282 window_limit=human_to_bytes(module.params["window_limit"]),
283 window=window,
284 )
285 else:
286 throttle = Throttle(
287 default_limit=human_to_bytes(module.params["default_limit"]),
288 )
289 connection_info = ArrayConnectionPost(
290 management_address=module.params["target_url"],
291 replication_addresses=module.params["target_repl"],
292 encrypted=module.params["encrypted"],
293 connection_key=connection_key,
294 throttle=throttle,
295 )
296 else:
297 connection_info = ArrayConnectionPost(
298 management_address=module.params["target_url"],
299 replication_addresses=module.params["target_repl"],
300 encrypted=module.params["encrypted"],
301 connection_key=connection_key,
302 )
303 if not module.check_mode:
304 if CONTEXT_API_VERSION in api_version:
305 res = blade.post_array_connections(
306 array_connection=connection_info,
307 context_names=[module.params["context"]],
308 )
309 else:
310 res = blade.post_array_connections(array_connection=connection_info)
311 if res.status_code != 200:
312 module.fail_json(
313 msg="Failed to connect to remote array {0}. Error: {1}".format(
314 remote_array, res.errors[0].message
315 )
316 )
317 module.exit_json(changed=changed)
318
319
320 def update_connection(module, blade):
321 """Update REST 2 based array connection"""
322 changed = False
323 api_version = list(blade.get_versions().items)
324 remote_blade = Client(
325 target=module.params["target_url"], api_token=module.params["target_api"]
326 )
327 remote_name = list(remote_blade.get_arrays().items)[0].name
328 remote_connection = list(
329 blade.get_array_connections(filter="remote.name='" + remote_name + "'").items
330 )[0]
331 if remote_connection.management_address is None:
332 module.fail_json(
333 msg="Update can only happen from the array that formed the connection"
334 )
335 if module.params["encrypted"] != remote_connection.encrypted:
336 if CONTEXT_API_VERSION in api_version:
337 res = blade.get_file_system_replica_links(
338 context_names=[module.params["context"]]
339 )
340 else:
341 res = blade.get_file_system_replica_links()
342 if module.params["encrypted"] and res.total_item_count != 0:
343 module.fail_json(
344 msg="Cannot turn array connection encryption on if file system replica links exist"
345 )
346 current_connection = {
347 "encrypted": remote_connection.encrypted,
348 "replication_addresses": sorted(remote_connection.replication_addresses),
349 "throttle": [],
350 }
351 if (
352 not remote_connection.throttle.default_limit
353 and not remote_connection.throttle.window_limit
354 ):
355 if CONTEXT_API_VERSION in api_version:
356 blade.get_bucket_replica_links(context_names=[module.params["context"]])
357 else:
358 blade.get_bucket_replica_links()
359 if (
360 module.params["default_limit"] or module.params["window_limit"]
361 ) and res.total_item_count != 0:
362 module.fail_json(
363 msg="Cannot set throttle when bucket replica links already exist"
364 )
365 current_connection["throttle"] = {
366 "default_limit": remote_connection.throttle.default_limit,
367 "window_limit": remote_connection.throttle.window_limit,
368 "start": remote_connection.throttle.window.start,
369 "end": remote_connection.throttle.window.end,
370 }
371 if module.params["encrypted"]:
372 encryption = module.params["encrypted"]
373 else:
374 encryption = remote_connection.encrypted
375 if module.params["target_repl"]:
376 target_repl = sorted(module.params["target_repl"])
377 else:
378 target_repl = remote_connection.replication_addresses
379 if module.params["default_limit"]:
380 default_limit = human_to_bytes(module.params["default_limit"])
381 if default_limit == 0:
382 default_limit = None
383 else:
384 default_limit = remote_connection.throttle.default_limit
385 if module.params["window_limit"]:
386 window_limit = human_to_bytes(module.params["window_limit"])
387 else:
388 window_limit = remote_connection.throttle.window_limit
389 if module.params["window_start"]:
390 start = _convert_to_millisecs(module.params["window_start"])
391 else:
392 start = remote_connection.throttle.window.start
393 if module.params["window_end"]:
394 end = _convert_to_millisecs(module.params["window_end"])
395 else:
396 end = remote_connection.throttle.window.end
397
398 new_connection = {
399 "encrypted": encryption,
400 "replication_addresses": target_repl,
401 "throttle": [],
402 }
403 new_connection["throttle"] = {
404 "default_limit": default_limit,
405 "window_limit": window_limit,
406 "start": start,
407 "end": end,
408 }
409 if new_connection != current_connection:
410 changed = True
411 if not module.check_mode:
412 window = TimeWindow(
413 start=new_connection["throttle"]["start"],
414 end=new_connection["throttle"]["end"],
415 )
416 throttle = Throttle(
417 default_limit=new_connection["throttle"]["default_limit"],
418 window_limit=new_connection["throttle"]["window_limit"],
419 window=window,
420 )
421 connection_info = ArrayConnectionPost(
422 replication_addresses=new_connection["replication_addresses"],
423 encrypted=new_connection["encrypted"],
424 throttle=throttle,
425 )
426 if CONTEXT_API_VERSION in api_version:
427 res = blade.patch_array_connections(
428 remote_names=[remote_name],
429 array_connection=connection_info,
430 context_names=[module.params["context"]],
431 )
432 else:
433 res = blade.patch_array_connections(
434 remote_names=[remote_name], array_connection=connection_info
435 )
436 if res.status_code != 200:
437 module.fail_json(
438 msg="Failed to update connection to remote array {0}. Error: {1}".format(
439 remote_name, res.errors[0].message
440 )
441 )
442 module.exit_json(changed=changed)
443
444
445 def main():
446 argument_spec = purefb_argument_spec()
447 argument_spec.update(
448 dict(
449 state=dict(type="str", default="present", choices=["absent", "present"]),
450 encrypted=dict(type="bool", default=False),
451 target_url=dict(type="str", required=True),
452 target_api=dict(type="str", no_log=True),
453 target_repl=dict(type="list", elements="str"),
454 default_limit=dict(type="str"),
455 window_limit=dict(type="str"),
456 window_start=dict(type="str"),
457 window_end=dict(type="str"),
458 context=dict(type="str", default=""),
459 )
460 )
461
462 required_if = [("state", "present", ["target_api"])]
463
464 module = AnsibleModule(
465 argument_spec, required_if=required_if, supports_check_mode=True
466 )
467
468 if not HAS_PYPURECLIENT:
469 module.fail_json(msg="py-pure-client sdk is required for this module")
470
471 state = module.params["state"]
472 blade = get_system(module)
473
474 if module.params["default_limit"]:
475 if (
476 human_to_bytes(module.params["default_limit"]) != 0
477 and 5242880 >= human_to_bytes(module.params["default_limit"]) >= 30064771072
478 ):
479 module.fail_json(msg="Default Bandwidth must be between 5MB and 28GB")
480 if module.params["window_limit"]:
481 if (
482 human_to_bytes(module.params["window_limit"]) != 0
483 and 5242880 >= human_to_bytes(module.params["window_limit"]) >= 30064771072
484 ):
485 module.fail_json(msg="Window Bandwidth must be between 5MB and 28GB")
486
487 target_blade = _check_connected(module, blade)
488 if state == "present" and not target_blade:
489 create_connection(module, blade)
490 elif state == "present" and target_blade:
491 update_connection(module, blade)
492 elif state == "absent" and target_blade:
493 break_connection(module, blade, target_blade)
494
495 module.exit_json(changed=False)
496
497
498 if __name__ == "__main__":
499 main()