Repository navigation
Expand file tree
/
Copy pathworkbench.py
More file actions
577 lines (519 loc) · 24 KB
/
Copy pathworkbench.py
File metadata and controls
577 lines (519 loc) · 24 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#!/usr/bin/env python3
"""Agent-friendly command-line entry point for MSP Workbench."""
from __future__ import annotations
import argparse
import csv
from dataclasses import asdict
from difflib import get_close_matches
from io import StringIO
import json
import logging
import os
from pathlib import Path
import sys
from typing import Any
from msp_workbench.adapter import AdapterError, AuthenticationRequiredError
from msp_workbench.demo_adapter import DemoAdapter
from msp_workbench.engine import OnboardingEngine
from msp_workbench.monitor import (
export_fieldnames,
export_rows,
find_monitored_tenant,
overview as monitor_overview,
parse_include,
tenant_detail,
)
from msp_workbench.models import strip_subscription_ids
from msp_workbench.parser import ParseError, parse_yaml_manifest
from msp_workbench.pycentral_adapter import PycentralAdapter
from msp_workbench.burndown_snapshot import BurndownUsageError, load_snapshot
from msp_workbench.burndown_projection import (
HORIZON_MONTHS,
export_csv as burndown_csv,
listing as list_burndown,
project as project_burndown,
public as public_burndown,
resolve_scope as resolve_burndown_scope,
validate_filters as validate_burndown_filters,
)
from msp_workbench.store import MemoryStore
JSON_OPTIONS = {"sort_keys": True, "separators": (",", ":")}
MONITOR_SECTIONS = ("sites", "monitored_devices", "clients", "alerts")
class CliError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
hint: str | None = None,
*,
errors: list[dict] | None = None,
):
self.status = status
self.code = code
self.message = message
self.hint = hint
self.errors = errors
super().__init__(message)
class JsonArgumentParser(argparse.ArgumentParser):
def error(self, message: str) -> None:
raise CliError(2, "usage_error", message, f"Run '{self.prog} --help'.")
def _command(commands, name: str, description: str, output: str, example: str):
return commands.add_parser(
name,
formatter_class=argparse.RawDescriptionHelpFormatter,
description=f"{description}\n\nOutput keys: {output}",
epilog=f"Example:\n {example}",
)
def _parser() -> argparse.ArgumentParser:
parser = JsonArgumentParser(
description="MSP Workbench CLI. Reads token.yaml from the current directory unless --demo is used.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--demo", action="store_true", help="Use deterministic demo data")
parser.add_argument("--verbose", action="store_true", help="Show pycentral INFO logs on stderr")
parser.add_argument("--format", choices=("json", "table"), default="json")
parser.add_argument("--fields", help="Comma-separated dotted paths within each list item, e.g. workspace_name,address.city")
parser.add_argument(
"--limit",
action="append",
default=[],
metavar="N|SECTION=N",
help="Cap every list or one named list section; repeatable",
)
parser.add_argument("--out", help="Write output to this path and print a receipt")
commands = parser.add_subparsers(dest="command", required=True)
list_parser = _command(
commands, "list", "Reads one discovery collection from GLP.",
"the selected collection", "workbench.py --demo list tenants",
)
list_parser.add_argument(
"selector", choices=("tenants", "services", "devices", "subscriptions")
)
plan_parser = _command(
commands, "plan", "Reads and validates a YAML manifest without writing to GLP.",
"job_id, manifest_hash, plan_hash, mode, tenant_groups, devices, errors, created_at",
"workbench.py --demo plan samples/new_tenant.yaml",
)
plan_parser.add_argument("manifest")
run_parser = _command(
commands, "run", "Reads a YAML manifest, plans it, and executes the confirmed job.",
"activity, created_at, devices, ended_at, id, last_error, manifest_hash, mode, plan, plan_hash, started_at, status, steps, stop_requested, tenant_groups, updated_at",
"workbench.py --demo run samples/new_tenant.yaml --yes",
)
run_parser.add_argument("manifest")
run_parser.add_argument("--yes", action="store_true", help="Confirm execution")
monitor_parser = _command(
commands, "monitor", "Reads the merged read-only tenant monitoring backend.",
"depends on the monitor subcommand", "workbench.py --demo monitor overview",
)
monitor_commands = monitor_parser.add_subparsers(dest="monitor_command", required=True)
_command(
monitor_commands, "overview", "Reads the monitored tenant overview.",
"tenants, totals, fetched_at", "workbench.py --demo monitor overview",
)
tenant_parser = _command(
monitor_commands, "tenant",
"Reads live monitoring detail for an exact tenant name or workspace ID.",
"workspace_id, workspace_name, sites, monitored_devices, clients, alerts",
"workbench.py --demo monitor tenant 'Acme Corp' --sites --alerts",
)
tenant_parser.add_argument("tenant")
for flag in MONITOR_SECTIONS:
tenant_parser.add_argument(f"--{flag.replace('_', '-')}", action="store_true")
export_parser = _command(
monitor_commands, "export",
"Freshly reads the monitored tenant overview for JSON or CSV export.",
"JSON: tenants, totals, fetched_at; CSV: tenant, sites, degraded_sites, total_devices, critical_alerts",
"workbench.py --demo monitor export --format csv --out tenants.csv",
)
export_parser.add_argument("--format", choices=("csv", "json"), dest="export_format")
export_parser.add_argument("--out", dest="export_out")
subscriptions = _command(
commands, "subscriptions", "Reads subscription coverage and utilization.",
"data and snapshot/call metadata", "workbench.py --demo subscriptions burndown",
)
subscription_commands = subscriptions.add_subparsers(dest="subscriptions_command", required=True)
burndown_parser = _command(
subscription_commands, "burndown", "Reads a single source snapshot and projects burndown scope.",
"horizon_months, months, kpis, tenant_options, fetched_at", "workbench.py --demo subscriptions burndown --scope msp",
)
burndown_parser.add_argument("--scope", choices=("msp", "tenant", "tenants", "all"))
burndown_parser.add_argument("--tenant", action="append", default=[])
burndown_parser.add_argument("--months", type=int, choices=HORIZON_MONTHS, default=12)
burndown_parser.add_argument("--view", choices=("losing_cover", "unused", "evaluations"), default="losing_cover")
burndown_parser.add_argument("--lifecycle", choices=("current", "expired", "all"), default="current")
burndown_parser.add_argument("--search", default="")
burndown_parser.add_argument("--month")
burndown_parser.add_argument("--format", choices=("json", "csv"), dest="burndown_format", default="json")
burndown_parser.add_argument("--out", dest="burndown_out")
return parser
def _configure_logging(verbose: bool) -> None:
# NOTE: pycentral installs its own stderr handlers with explicit levels, so global disable is the only reliable switch; revisit if the CLI ever wants its own logging.
logging.disable(logging.NOTSET if verbose else logging.WARNING)
def _adapter(demo: bool):
if demo:
return DemoAdapter()
if not os.path.isfile("token.yaml"):
raise CliError(
1,
"token_not_found",
"Live mode requires token.yaml in the current directory",
"Create token.yaml (see msp-workbench/token.yaml.example) or pass --demo.",
)
return PycentralAdapter("token.yaml")
def _list(adapter, selector: str) -> list[dict]:
if selector == "tenants":
values = adapter.list_tenants()
elif selector == "services":
values = adapter.list_eligible_services(None)
elif selector == "devices":
values = adapter.list_available_devices()
else:
values = adapter.list_subscriptions()
return [asdict(item) for item in values]
def _limits(values: list[str], sections: set[str]) -> tuple[int | None, dict[str, int]]:
default = None
overrides = {}
for value in values:
section, separator, raw_limit = value.partition("=")
if not separator:
raw_limit, section = section, ""
try:
limit = int(raw_limit)
except ValueError:
raise CliError(2, "invalid_limit", f"Invalid limit: {value}", "Use N or section=N.")
if limit < 0:
raise CliError(2, "invalid_limit", "Limits cannot be negative", "Use zero or a positive integer.")
if section and section not in sections:
raise CliError(
2, "invalid_limit", f"Unknown list section: {section}",
"Valid sections: " + ", ".join(sorted(sections)),
)
if section:
overrides[section] = limit
else:
default = limit
return default, overrides
def _cap_lists(
data: dict[str, Any], values: list[str], required: tuple[str, ...] = (),
) -> tuple[dict[str, Any], dict[str, dict[str, int | bool]]]:
sections = {key for key, value in data.items() if isinstance(value, list)} | set(required)
default, overrides = _limits(values, sections)
meta = {}
for section in sections:
rows = data.get(section)
total = len(rows) if isinstance(rows, list) else 0
limit = overrides.get(section, default)
returned = total if limit is None else min(total, limit)
if isinstance(rows, list) and limit is not None:
data[section] = rows[:limit]
meta[section] = {"total": total, "returned": returned, "truncated": returned < total}
return data, meta
def _flatten(value: Any, prefix: str = "") -> dict[str, Any]:
if not isinstance(value, dict):
return {prefix: value}
flattened = {}
for key, child in value.items():
path = f"{prefix}.{key}" if prefix else key
if isinstance(child, dict):
flattened.update(_flatten(child, path))
else:
flattened[path] = child
return flattened
def _lookup(value: dict[str, Any], path: str) -> tuple[bool, Any]:
current: Any = value
for part in path.split("."):
if not isinstance(current, dict) or part not in current:
return False, None
current = current[part]
return True, current
def _assign(target: dict[str, Any], path: str, value: Any) -> None:
parts = path.split(".")
for part in parts[:-1]:
target = target.setdefault(part, {})
target[parts[-1]] = value
def _project(value: dict[str, Any], paths: list[str]) -> dict[str, Any]:
result = {}
for path in paths:
found, selected = _lookup(value, path)
if found:
_assign(result, path, selected)
return result
def _fields(data: dict[str, Any], raw: str | None) -> dict[str, Any]:
if not raw:
return data
paths = [path.strip() for path in raw.split(",") if path.strip()]
valid = set(data)
for key, value in data.items():
if isinstance(value, dict):
valid.update(_flatten(value, key))
elif isinstance(value, list) and value and isinstance(value[0], dict):
valid.update(_flatten(value[0]))
unknown = [path for path in paths if path not in valid]
if unknown:
raise CliError(
2, "unknown_field", "Unknown field path: " + ", ".join(unknown),
"Valid keys: " + ", ".join(sorted(valid)),
)
result = _project(data, paths)
for section, rows in data.items():
if not isinstance(rows, list):
continue
if section in paths:
result[section] = rows
continue
row_paths = [
path for path in paths
if any(_lookup(row, path)[0] for row in rows if isinstance(row, dict))
]
if row_paths:
result[section] = [
_project(row, row_paths) if isinstance(row, dict) else row for row in rows
]
return result
def _cell(value: Any) -> str:
if isinstance(value, (dict, list)):
return json.dumps(value, **JSON_OPTIONS)
if value is None:
return ""
if isinstance(value, bool):
return str(value).lower()
return str(value)
def _table(data: dict[str, Any]) -> str:
blocks = []
scalars = {key: value for key, value in data.items() if not isinstance(value, list)}
if scalars:
pairs = list(_flatten(scalars).items())
width = max(len(key) for key, _ in pairs)
blocks.append("\n".join(f"{key:<{width}} {_cell(value)}" for key, value in pairs))
for section, rows in data.items():
if not isinstance(rows, list):
continue
flat_rows = [_flatten(row) if isinstance(row, dict) else {"value": row} for row in rows]
headers = list(dict.fromkeys(key for row in flat_rows for key in row))
lines = [f"[{section}]"]
if headers:
widths = [
max(len(header), *[len(_cell(row.get(header))) for row in flat_rows])
for header in headers
]
lines.append(" ".join(f"{header:<{width}}" for header, width in zip(headers, widths)))
lines.extend(
" ".join(
f"{_cell(row.get(header)):<{width}}"
for header, width in zip(headers, widths)
)
for row in flat_rows
)
blocks.append("\n".join(lines))
return "\n\n".join(blocks)
def _json(value: Any) -> str:
return json.dumps(value, **JSON_OPTIONS)
def _write(document: str, path: str, rows: int) -> None:
content = document + ("" if document.endswith("\n") else "\n")
try:
Path(path).write_text(content, encoding="utf-8")
except OSError as exc:
raise CliError(
1,
"output_not_writable",
f"Cannot write {path}: {exc.strerror or exc}",
"Check the parent directory exists and is writable.",
)
print(_json({"bytes": len(content.encode()), "path": path, "rows": rows}))
def _render(data: dict[str, Any], meta: dict[str, Any], args) -> None:
rows = sum(len(value) for value in data.values() if isinstance(value, list))
if (args.format or "json") == "json":
document = _json({"data": data, "meta": meta})
else:
document = _table(data)
if args.out:
_write(document, args.out, rows)
else:
print(document)
if args.format == "table":
print(_json(meta), file=sys.stderr)
def _error(exc: Exception) -> tuple[int, dict[str, Any]]:
if isinstance(exc, CliError):
error = {"code": exc.code, "message": exc.message, "hint": exc.hint}
if exc.errors is not None:
error["errors"] = exc.errors
return exc.status, error
if isinstance(exc, ParseError):
return 1, {
"code": "manifest_invalid",
"message": str(exc),
"hint": "See samples/*.yaml for the schema-v2 manifest shape.",
"errors": [asdict(error) for error in exc.errors],
}
if isinstance(exc, AdapterError):
hint = "Check token.yaml and MSP credentials." if isinstance(exc, AuthenticationRequiredError) else None
return 4, {"code": exc.code, "message": exc.message, "hint": hint}
if isinstance(exc, LookupError):
return 3, {"code": "not_found", "message": str(exc), "hint": "Check the exact GLP tenant name or ID."}
if isinstance(exc, BurndownUsageError):
return 2, {"code": "usage_error", "message": str(exc), "hint": "Check subscriptions burndown flags."}
return 1, {"code": exc.__class__.__name__.lower(), "message": str(exc), "hint": None}
def _manifest(engine: OnboardingEngine, path: str):
try:
with open(path, encoding="utf-8") as manifest_file:
content = manifest_file.read()
except (FileNotFoundError, IsADirectoryError):
raise CliError(
1,
"manifest_not_found",
f"Manifest not found: {path}",
"Pass the path to a version 2 YAML manifest; see samples/.",
)
except OSError as exc:
raise CliError(
1,
"manifest_not_readable",
f"Cannot read manifest {path}: {exc.strerror or exc}",
"Check the file permissions.",
)
return engine.plan(parse_yaml_manifest(content))
def _infer_burndown_scope(snapshot, tenants: list[str]) -> str:
"""Pick a burndown scope from the ownership of the requested tenants."""
if not tenants:
return "msp"
# Resolving under "all" accepts any ownership and keeps the not-found error.
selected, _, _ = resolve_burndown_scope(snapshot, "all", tenants)
ownerships = {tenant.ownership for tenant in selected}
if ownerships == {"CUSTOMER_OWNED_INVENTORY"}:
return "tenant" if len(selected) == 1 else "tenants"
if ownerships == {"MSP_OWNED_INVENTORY"}:
return "msp"
return "all"
def _confirm(plan, yes: bool) -> None:
if yes:
return
print(f"Run onboarding job {plan.job_id}? [y/N] ", end="", file=sys.stderr, flush=True)
if input().lower() not in ("y", "yes"):
print(file=sys.stderr)
raise CliError(2, "confirmation_refused", "Run was not confirmed.", "Pass --yes to confirm execution.")
def main(argv: list[str] | None = None) -> int:
try:
args = _parser().parse_args(argv)
_configure_logging(args.verbose)
if args.command == "run" and not args.yes and not sys.stdin.isatty():
raise CliError(
2, "confirmation_required", "Run requires confirmation.",
"Pass --yes to confirm execution.",
)
adapter = _adapter(args.demo)
fetched_at = adapter.now().isoformat()
command_meta: dict[str, Any] = {}
if args.command == "subscriptions":
validate_burndown_filters(view=args.view, lifecycle_value=args.lifecycle, month=args.month, q=args.search)
snapshot = load_snapshot(adapter, 1)
scope = args.scope or _infer_burndown_scope(snapshot, args.tenant)
current = project_burndown(snapshot, scope=scope, tenants=args.tenant, months=args.months, cache="miss")
fetched_at = current["fetched_at"]
command_meta = dict(current["meta"])
if args.burndown_format == "csv":
args.out = args.burndown_out or args.out
raw_document = burndown_csv(current, args.view, month=args.month, lifecycle_value=args.lifecycle, q=args.search)
reader = csv.DictReader(StringIO(raw_document))
csv_rows, sections = _cap_lists({"rows": list(reader)}, args.limit)
fieldnames = list(reader.fieldnames or [])
if args.fields:
requested = [field.strip().removeprefix("rows.") for field in args.fields.split(",") if field.strip()]
unknown = [field for field in requested if field not in fieldnames]
if unknown:
raise CliError(2, "unknown_field", "Unknown CSV field: " + ", ".join(unknown), "Valid fields: " + ", ".join(fieldnames))
fieldnames = requested
output = StringIO()
writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction="ignore", lineterminator="\n")
writer.writeheader()
writer.writerows(csv_rows["rows"])
document = output.getvalue()
rows = len(csv_rows["rows"])
if args.out: _write(document, args.out, rows)
else: print(document, end="")
print(_json({"demo": args.demo, **command_meta, **sections}), file=sys.stderr)
return 0
if args.view == "losing_cover":
data = public_burndown(current)
data.pop("meta", None)
else: data = list_burndown(current, args.view, args.lifecycle, args.search, full=True)
if args.view != "losing_cover":
command_meta = dict(data.pop("meta"))
data, sections = _cap_lists(data, args.limit)
if args.view != "losing_cover" and "rows" in sections:
command_meta.update(sections["rows"])
args.out = args.burndown_out or args.out
elif args.command == "list":
data, sections = _cap_lists(
strip_subscription_ids({args.selector: _list(adapter, args.selector)}),
args.limit,
)
elif args.command == "monitor" and args.monitor_command == "overview":
current = monitor_overview(adapter)
fetched_at = current.fetched_at
data, sections = _cap_lists(asdict(current), args.limit)
elif args.command == "monitor" and args.monitor_command == "tenant":
current = monitor_overview(adapter)
tenant = find_monitored_tenant(current, args.tenant, by_name=True)
if tenant is None:
names = [row.workspace_name for row in current.tenants]
suggestions = get_close_matches(args.tenant, names) or names
raise CliError(
3, "tenant_not_found", f"Monitored tenant not found: {args.tenant}",
"Try: " + ", ".join(suggestions),
)
selected = [section for section in MONITOR_SECTIONS if getattr(args, section)]
include = parse_include(",".join(selected))
data = asdict(tenant_detail(adapter, tenant.workspace_id, include))
data.update(workspace_id=tenant.workspace_id, workspace_name=tenant.workspace_name)
data, sections = _cap_lists(data, args.limit, MONITOR_SECTIONS)
elif args.command == "monitor" and args.monitor_command == "export":
current = monitor_overview(adapter, fresh=True)
fetched_at = current.fetched_at
export_format = args.export_format or "json"
args.out = args.export_out or args.out
if export_format == "csv":
csv_data, sections = _cap_lists({"tenants": export_rows(current)}, args.limit)
csv_data = _fields(csv_data, args.fields)
fieldnames = export_fieldnames
if args.fields:
requested = {field.strip() for field in args.fields.split(",")}
if "tenants" not in requested:
fieldnames = tuple(field for field in export_fieldnames if field in requested)
output = StringIO()
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(csv_data["tenants"])
meta = {"demo": args.demo, "fetched_at": fetched_at, **command_meta, **sections}
document = output.getvalue()
if args.out:
_write(document, args.out, sections["tenants"]["returned"])
else:
print(document, end="")
print(_json(meta), file=sys.stderr)
return 0
args.format = "json"
data, sections = _cap_lists(asdict(current), args.limit)
else:
with MemoryStore() as store:
engine = OnboardingEngine(adapter, store)
plan = _manifest(engine, args.manifest)
if args.command == "run":
_confirm(plan, args.yes)
engine.start(plan.job_id)
engine.drain()
data = engine.get(plan.job_id)
else:
data = plan.to_dict()
data, sections = _cap_lists(strip_subscription_ids(data), args.limit)
data = _fields(data, args.fields)
meta = {"demo": args.demo, "fetched_at": fetched_at, **command_meta, **sections}
_render(data, meta, args)
return 0
except Exception as exc:
status, error = _error(exc)
print(_json(error), file=sys.stderr)
return status
if __name__ == "__main__":
raise SystemExit(main())