Repository navigation
Expand file tree
/
Copy pathpure_flasharray.py
More file actions
executable file
·557 lines (479 loc) · 19.2 KB
/
Copy pathpure_flasharray.py
File metadata and controls
executable file
·557 lines (479 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#!/usr/bin/env python3
"""Ansible dynamic inventory for a Pure Storage FlashArray, through REST API 1.19.
Lists the hosts defined on the array and the volumes (LUNs) mapped to them, so a
play can find a host's block devices by serial or multipath WWID.
--list every host, in purearray_<array> > purehostgroup_<host group>
--host one host's variables
Each host group's group carries pure_hgroup, pure_group, pure_array,
pure_luns_shared and pure_lun_count. Each host carries pure_array, pure_host,
pure_host_short, pure_hgroups, pure_groups, pure_luns_individual,
pure_lun_count, pure_iqns, pure_wwns, pure_nqns and pure_host_personality.
A set of LUNs is a dict of:
volumes_all every volume in one flat list, with its volume_group (or null)
volumes the volumes outside any volume group
volume_groups volume group name -> {"volumes": [...]}, each volume named
without the group prefix and with full_volume for the full name
and every volume has lun_id, serial, multipath_wwid, size_bytes and size_human.
The array comes from the environment: CREDENTIAL_PURE_<TAG>_BASE_URL, _USERNAME
and _PASSWORD as unified-api hands them over, or PURE_<TAG>_... as an Ansible
controller would. One array per source: run one source per array.
Settings, from the source's config (SOURCE_CONFIG, JSON; strings are fine):
resolve_fqdn true to name hosts by the fully qualified name DNS gives
domain with resolve_fqdn, the suffix for names DNS does not know
insecure true to skip TLS verification (self-signed arrays)
workers parallel requests, default 20
timeout_seconds per request, default 60
"""
import argparse
import http.cookiejar
import json
import os
import socket
import ssl
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import quote, urlparse
# --- begin shared helpers: copied from unified_connectors/inventory.py, keep identical ---
class ConnectorError(Exception):
"""A failure reported as one clean line on stderr, without a traceback."""
def settings(environ=None):
"""Read the settings unified-api hands a connector.
Args:
environ: The environment to read; os.environ by default.
Returns:
The SOURCE_CONFIG (or APPLICATION_CONFIG) JSON object, or an empty dict.
Raises:
ConnectorError: The variable is set but is not a JSON object.
"""
environ = os.environ if environ is None else environ
raw = environ.get("SOURCE_CONFIG") or environ.get("APPLICATION_CONFIG") or "{}"
try:
value = json.loads(raw)
except json.JSONDecodeError as e:
raise ConnectorError(f"SOURCE_CONFIG is not JSON: {e}") from None
if not isinstance(value, dict):
raise ConnectorError("SOURCE_CONFIG must be a JSON object")
return value
def as_list(value, default=()):
"""Read a list setting: a JSON list, or a comma-separated string.
unified-api passes every config value as a string, so "a, b" and ["a", "b"]
both give ["a", "b"].
"""
if value is None or value == "":
return list(default)
if isinstance(value, str):
return [item.strip() for item in value.split(",") if item.strip()]
return [str(item) for item in value]
def as_bool(value, default=False):
"""Read a flag setting: true, 1 and yes (any case) are true, anything else false."""
if value is None or value == "":
return default
if isinstance(value, str):
return value.strip().lower() in ("1", "true", "yes")
return bool(value)
def as_int(value, default):
"""Read a whole-number setting.
Raises:
ConnectorError: The value is not a whole number.
"""
if value is None or value == "":
return default
try:
return int(value)
except (TypeError, ValueError):
raise ConnectorError(f"not a whole number: {value!r}") from None
def credential_sets(prefix, required, optional=(), environ=None):
"""Find every complete set of credentials for one kind of system.
A set is PREFIX_<TAG>_<FIELD> variables sharing a TAG, which is any name.
unified-api hands them over as CREDENTIAL_PREFIX_<TAG>_<FIELD>; an Ansible
controller sets PREFIX_<TAG>_<FIELD>. The unified-api form wins, so a system
exposed both ways is used once.
Args:
prefix: The system's prefix, such as UCS.
required: Fields a set must have, the first of which marks a set.
optional: Fields read when present.
environ: The environment to read; os.environ by default.
Returns:
One dict per set, sorted by tag: "tag" plus each field in lowercase.
"""
environ = os.environ if environ is None else environ
marker = f"_{required[0]}"
found, seen = [], set()
for start in (f"CREDENTIAL_{prefix}_", f"{prefix}_"):
for key in sorted(environ):
if not (key.startswith(start) and key.endswith(marker)):
continue
tag = key[len(start) : -len(marker)]
if not tag or tag in seen:
continue
values = {
f.lower(): environ.get(f"{start}{tag}_{f}", "").strip()
for f in (*required, *optional)
}
if all(values[f.lower()] for f in required):
seen.add(tag)
found.append({"tag": tag, **values})
return found
# --- end shared helpers ---
API_VERSION = "1.19"
HGROUP_PREFIX = "purehostgroup_"
ARRAY_PREFIX = "purearray_"
DNS_WORKERS = 50
# Pure volume serials become multipath WWIDs behind this NAA prefix.
WWID_PREFIX = "3624a9370"
# What an array that is down, slow, refusing or answering nonsense raises:
# network errors and timeouts are OSError, a garbled answer a ValueError (JSON),
# a refused request a RuntimeError.
FAILURES = (OSError, ValueError, RuntimeError)
class NotFound(RuntimeError):
"""The array answered 404: the object has nothing mapped, or does not exist."""
class FlashArrayClient:
"""A signed-in session on one FlashArray."""
def __init__(self, base_url, username, password, insecure=False, timeout=60):
"""Sign in: trade the password for an API token, then the token for a session.
Args:
base_url: The array's address, such as https://array.example.com.
username: The account to sign in with.
password: Its password.
insecure: Skip TLS verification.
timeout: Seconds per request.
Raises:
RuntimeError: The array refused the sign-in.
"""
if "://" not in base_url:
base_url = f"https://{base_url}"
self.base_url = f"{base_url.rstrip('/')}/api/{API_VERSION}"
self.timeout = timeout
context = ssl.create_default_context()
if insecure:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
self.opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),
urllib.request.HTTPSHandler(context=context),
)
token = (
self._call(
"POST", "/auth/apitoken", {"username": username, "password": password}
)
or {}
).get("api_token")
if not token:
raise RuntimeError("sign-in answered without an API token")
self._call("POST", "/auth/session", {"api_token": token})
def get(self, path, missing_is_empty=False):
"""Return a list from the API; [] for a 404 when missing_is_empty."""
try:
result = self._call("GET", path)
except NotFound:
if missing_is_empty:
return []
raise
return result if isinstance(result, list) else []
def logout(self):
"""End the session; a failure here changes nothing for the inventory."""
try:
self._call("DELETE", "/auth/session")
except FAILURES:
return
def _call(self, method, path, body=None):
request = urllib.request.Request(
f"{self.base_url}{path}",
data=None if body is None else json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Accept": "application/json"},
method=method,
)
try:
with self.opener.open(request, timeout=self.timeout) as response:
raw = response.read()
except urllib.error.HTTPError as e:
error = NotFound if e.code == 404 else RuntimeError
raise error(f"HTTP {e.code} for {method} {path}") from None
return json.loads(raw) if raw else None
def human_size(size):
"""Format a byte count the way the array's own tools do, such as 1.00 TiB."""
if not size:
return "0 B"
for unit, divisor in (
("TiB", 2**40),
("GiB", 2**30),
("MiB", 2**20),
("KiB", 2**10),
):
if size >= divisor:
return f"{size / divisor:.2f} {unit}"
return f"{size} B"
def count_luns(luns):
"""Count the LUNs in a classified set."""
return len(luns.get("volumes", [])) + sum(
len(group.get("volumes", []))
for group in luns.get("volume_groups", {}).values()
)
def classify_luns(mapped, volumes, vgroup_of):
"""Turn a list of mapped volumes into the classified set of LUNs.
Membership of a volume group comes from the array's own list of groups,
never from the slash in a volume's name.
Args:
mapped: Entries from a host or host group volume list, each with vol and lun.
volumes: Volume name -> its catalogue entry (serial, size).
vgroup_of: Full volume name -> the volume group it belongs to.
Returns:
The dict of volumes_all, volumes and volume_groups.
"""
flat, standalone, groups = [], [], {}
for entry in mapped:
full = entry.get("vol", "")
info = volumes.get(full, {})
serial = info.get("serial", "")
size = info.get("size", 0) or 0
base = {
"lun_id": entry.get("lun"),
"serial": serial,
"multipath_wwid": f"{WWID_PREFIX}{serial.lower()}" if serial else "",
"size_bytes": size,
"size_human": human_size(size),
}
group = vgroup_of.get(full)
if group:
short = full.removeprefix(f"{group}/")
groups.setdefault(group, {"volumes": []})["volumes"].append(
{"volume": short, "full_volume": full, **base}
)
flat.append(
{"volume": short, "full_volume": full, "volume_group": group, **base}
)
else:
standalone.append({"volume": full, **base})
flat.append({"volume": full, "volume_group": None, **base})
return {"volumes_all": flat, "volumes": standalone, "volume_groups": groups}
def resolve_fqdn(short, domain):
"""Name a host by its fully qualified name.
A name with a dot is kept. Otherwise DNS is asked; when it has no longer
name, domain is appended, or the name is kept when there is no domain.
"""
if "." in short:
return short
try:
fqdn = socket.getfqdn(short)
except OSError:
fqdn = short
if fqdn and fqdn != short and "." in fqdn:
return fqdn
return f"{short}.{domain.lstrip('.')}" if domain else short
def _members(hgroup):
return [
h.get("name", str(h)) if isinstance(h, dict) else str(h)
for h in hgroup.get("hosts", [])
]
def _catalogue(client):
"""Return the volume catalogue and the volume-to-group map."""
volumes = {
v["name"]: {
"serial": v.get("serial", ""),
"size": v.get("size", 0),
"source": v.get("source", ""),
"created": v.get("created", ""),
}
for v in client.get("/volume")
if v.get("name")
}
vgroup_of = {
volume: group.get("name", "")
for group in client.get("/vgroup", missing_is_empty=True)
for volume in group.get("volumes", [])
if volume
}
return volumes, vgroup_of
def _host_vars(array, name, short, hgroups, luns, data):
return {
"pure_array": array,
"pure_host": name,
"pure_host_short": short,
"pure_hgroups": hgroups,
"pure_groups": [f"{HGROUP_PREFIX}{g}" for g in hgroups],
"pure_luns_individual": luns,
"pure_lun_count": count_luns(luns),
"pure_iqns": data.get("iqn", []),
"pure_wwns": data.get("wwn", []),
"pure_nqns": data.get("nqn", []),
"pure_host_personality": data.get("personality", ""),
}
def build_inventory(client, array, resolve=False, domain="", workers=20):
"""Read the array and build the inventory.
Args:
client: A signed-in FlashArrayClient, or anything answering get.
array: The array's host name, for pure_array and the group name.
resolve: Name hosts by their fully qualified name.
domain: With resolve, the suffix for names DNS does not know.
workers: Parallel requests.
Returns:
The inventory.
"""
with ThreadPoolExecutor(max_workers=4) as pool:
catalogue = pool.submit(_catalogue, client)
hgroups_future = pool.submit(client.get, "/hgroup")
hosts_future = pool.submit(client.get, "/host")
volumes, vgroup_of = catalogue.result()
hgroups, hosts = hgroups_future.result(), hosts_future.result()
members = {g.get("name", ""): _members(g) for g in hgroups}
names = [h["name"] for h in hosts if h.get("name")]
with ThreadPoolExecutor(max_workers=workers) as pool:
shared = dict(
zip(
members,
pool.map(
lambda g: classify_luns(
client.get(f"/hgroup/{quote(g)}/volume", missing_is_empty=True),
volumes,
vgroup_of,
),
members,
),
strict=True,
)
)
individual = dict(
zip(
names,
pool.map(
lambda h: classify_luns(
client.get(f"/host/{quote(h)}/volume", missing_is_empty=True),
volumes,
vgroup_of,
),
names,
),
strict=True,
)
)
every = set(names).union(*members.values()) if members else set(names)
if resolve:
with ThreadPoolExecutor(max_workers=DNS_WORKERS) as pool:
fqdn = dict(
zip(
every,
pool.map(lambda n: resolve_fqdn(n, domain), every),
strict=True,
)
)
else:
fqdn = {n: n for n in every}
array_group = f"{ARRAY_PREFIX}{array}"
inventory = {
"_meta": {"hostvars": {}},
"all": {"children": ["ungrouped", array_group]},
array_group: {"hosts": [], "vars": {"pure_array": array}, "children": []},
}
for group, hosts_in in members.items():
name = f"{HGROUP_PREFIX}{group}"
luns = shared.get(group, {"volumes": [], "volume_groups": {}})
inventory[name] = {
"hosts": [fqdn[h] for h in hosts_in],
"vars": {
"pure_hgroup": group,
"pure_group": name,
"pure_array": array,
"pure_luns_shared": luns,
"pure_lun_count": count_luns(luns),
},
}
inventory[array_group]["children"].append(name)
if name not in inventory["all"]["children"]:
inventory["all"]["children"].append(name)
data = {h.get("name", ""): h for h in hosts}
for short in names:
name = fqdn[short]
if name not in inventory[array_group]["hosts"]:
inventory[array_group]["hosts"].append(name)
groups = [g for g, m in members.items() if short in m]
inventory["_meta"]["hostvars"][name] = _host_vars(
array, name, short, groups, individual[short], data.get(short, {})
)
# Hosts that appear in a host group without a host object of their own.
for short in every - set(names):
name = fqdn[short]
if name not in inventory["_meta"]["hostvars"]:
groups = [g for g, m in members.items() if short in m]
inventory["_meta"]["hostvars"][name] = _host_vars(
array, name, short, groups, {"volumes": [], "volume_groups": {}}, {}
)
inventory["ungrouped"] = {"hosts": [], "vars": {}}
return inventory
def host_vars(client, array, host, resolve=False, domain=""):
"""Return one host's variables, found by its short or resolved name."""
try:
volumes, vgroup_of = _catalogue(client)
except FAILURES:
volumes, vgroup_of = {}, {}
def named(short):
return resolve_fqdn(short, domain) if resolve else short
data = next(
(
h
for h in client.get("/host")
if host in (h.get("name"), named(h.get("name", "")))
),
{},
)
short = data.get("name", host)
luns = classify_luns(
client.get(f"/host/{quote(short)}/volume", missing_is_empty=True),
volumes,
vgroup_of,
)
groups = [g.get("name", "") for g in client.get("/hgroup") if short in _members(g)]
return _host_vars(array, named(short), short, groups, luns, data)
def main(argv=None, environ=None, connect=FlashArrayClient):
"""Print the inventory, or one host's variables, as JSON."""
environ = os.environ if environ is None else environ
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--list", action="store_true", help="the whole inventory")
mode.add_argument("--host", help="one host's variables")
args = parser.parse_args(argv)
arrays = credential_sets(
"PURE", ("BASE_URL", "USERNAME", "PASSWORD"), environ=environ
)
if len(arrays) != 1:
print(
"need exactly one array: set CREDENTIAL_PURE_<TAG>_BASE_URL, _USERNAME and"
f" _PASSWORD for one TAG (found {len(arrays)})",
file=sys.stderr,
)
return 1
array = arrays[0]
name = urlparse(
array["base_url"]
if "://" in array["base_url"]
else f"https://{array['base_url']}"
).netloc
client = None
try:
config = settings(environ)
resolve = as_bool(config.get("resolve_fqdn"))
domain = config.get("domain") or ""
client = connect(
array["base_url"],
array["username"],
array["password"],
insecure=as_bool(config.get("insecure")),
timeout=as_int(config.get("timeout_seconds"), 60),
)
if args.list:
result = build_inventory(
client, name, resolve, domain, as_int(config.get("workers"), 20)
)
else:
result = host_vars(client, name, args.host, resolve, domain)
except (ConnectorError, *FAILURES) as e:
print(f"{name}: {e}", file=sys.stderr)
return 1
finally:
if client is not None:
client.logout()
print(json.dumps(result, indent=2, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())