slurm-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
slurm_cli/py.typed ADDED
File without changes
@@ -0,0 +1 @@
1
+ """Utility modules for Slurm CLI."""
@@ -0,0 +1,544 @@
1
+ """Utilities for managing accounts."""
2
+
3
+ import json
4
+ import subprocess
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ from rich.box import SIMPLE_HEAVY
8
+ from rich.table import Table
9
+
10
+ from .base_resource import BaseSlurmResource
11
+ from .profiles import (
12
+ format_with_template,
13
+ get_profile_config,
14
+ sort_data,
15
+ sort_hierarchical_data,
16
+ )
17
+ from .utils import console
18
+
19
+ # Account configuration options (sacctmgr field names)
20
+ # Note: Flags is read-only (shows status like "Deleted"), not settable
21
+ ACCOUNT_OPTIONS: List[str] = [
22
+ "Cluster",
23
+ # "DefaultQOS",
24
+ "Description",
25
+ "Name",
26
+ # "Fairshare",
27
+ # "GrpJobs",
28
+ # "GrpJobsAccrue",
29
+ # "GrpSubmit",
30
+ # "GrpSubmitJobs",
31
+ # "GrpTRES",
32
+ # "GrpTRESMins",
33
+ # "GrpTRESRunMins",
34
+ # "GrpWall",
35
+ # "MaxJobs",
36
+ # "MaxJobsAccrue",
37
+ # "MaxSubmit",
38
+ # "MaxSubmitJobs",
39
+ # "MaxTRES",
40
+ # "MaxTRESMins",
41
+ # "MaxWall",
42
+ "Organization",
43
+ "Parent",
44
+ "RawUsage",
45
+ ]
46
+
47
+
48
+ class Account(BaseSlurmResource):
49
+ def __init__(self, name: str, **kwargs: Any):
50
+ self.name = name
51
+ self.kwargs = kwargs
52
+
53
+ @classmethod
54
+ def get_profile_fields(cls) -> dict:
55
+ """Return field names and descriptions for profile templates."""
56
+ return {
57
+ "name": "Account name",
58
+ "description": "Account description",
59
+ "organization": "Organization name",
60
+ "coordinators": "List of coordinator usernames",
61
+ }
62
+
63
+ @classmethod
64
+ def generate_autocomplete_options(cls) -> str:
65
+ """Generate bash autocomplete script for account options."""
66
+ valid_keys = [opt.lower() for opt in ACCOUNT_OPTIONS]
67
+ filter_opts = " ".join(f"{k}=" for k in valid_keys)
68
+
69
+ script = f"""
70
+ _slurm_cli_accounts_autocomplete() {{
71
+ local cmd="$1"
72
+ local pos="$2"
73
+
74
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
75
+ local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
76
+ local name="${{COMP_WORDS[$pos]}}"
77
+
78
+ local cached_accounts="$(_slurm_cache_accounts)"
79
+ local filter_options="{filter_opts}"
80
+ local update_options="$filter_options set"
81
+
82
+ # First argument after 'accounts' (not completing a value)
83
+ if [[ $name == accounts && $prev == accounts && $cur != *=* ]]; then
84
+ case "$cmd" in
85
+ show|delete) _slurm_complete "$filter_options $cached_accounts" "$cur" ;;
86
+ update) _slurm_complete "$update_options $cached_accounts" "$cur" ;;
87
+ esac
88
+ return
89
+ fi
90
+
91
+ # Handle key=value completion
92
+ if _slurm_parse_keyval "$cur" "$prev"; then
93
+ case "$_key" in
94
+ defaultqos)
95
+ _slurm_complete_value "$(_slurm_cache_qos)" "$_key" "$_val" "$cur" ;;
96
+ parent|organization|name)
97
+ _slurm_complete_value "$cached_accounts" "$_key" "$_val" "$cur" ;;
98
+ esac
99
+ return
100
+ fi
101
+
102
+ # Complete option names
103
+ case "$cmd" in
104
+ show|delete) _slurm_complete "$filter_options" "$cur" ;;
105
+ create|update) _slurm_complete "$update_options" "$cur" ;;
106
+ esac
107
+ }}
108
+ """ # noqa: E501
109
+ return script
110
+
111
+ @classmethod
112
+ def create(
113
+ cls, name: str, verbose: bool = False, **kwargs: Any
114
+ ) -> None:
115
+ """Create a new account."""
116
+ console.print(f"Creating account: {name}")
117
+ args = ["sacctmgr", "create", "account", f"name={name}"]
118
+ for key, value in kwargs.items():
119
+ args.append(f"{key}={value}")
120
+
121
+ try:
122
+ result = subprocess.run(
123
+ args,
124
+ check=True,
125
+ capture_output=True,
126
+ text=True,
127
+ )
128
+ console.print(
129
+ f"[green]Account '{name}' created successfully.[/green]"
130
+ )
131
+ if result.stdout:
132
+ console.print(result.stdout)
133
+ except subprocess.CalledProcessError as e:
134
+ error_msg = e.stderr or e
135
+ console.print(
136
+ f"[red]Failed to create account '{name}':[/red] {error_msg}"
137
+ )
138
+
139
+ @classmethod
140
+ def update(
141
+ cls,
142
+ name: str,
143
+ verbose: bool = False,
144
+ dry_run: bool = False,
145
+ where_conditions: Optional[List[str]] = None,
146
+ set_values: Optional[List[str]] = None,
147
+ **kwargs: Any,
148
+ ) -> None:
149
+ """Update an account.
150
+
151
+ Two calling modes:
152
+ 1. Simple: update(name, key=value, ...) - updates account by name
153
+ 2. Where: update(name, where_conditions=[...], set_values=[...])
154
+ - uses WHERE/SET syntax for bulk updates
155
+
156
+ Args:
157
+ name: Account name (simple mode) or ignored (where mode)
158
+ verbose: Enable verbose output
159
+ dry_run: If True, print command without executing
160
+ where_conditions: List of WHERE conditions (e.g., ["cluster=test"])
161
+ set_values: List of SET values (e.g., ["description=foo"])
162
+ **kwargs: Additional SET values (simple mode only)
163
+ """
164
+ # Build sacctmgr command
165
+ args = ["sacctmgr", "-i", "modify", "account"]
166
+
167
+ if where_conditions is not None:
168
+ # WHERE/SET mode
169
+ args.append("where")
170
+ args.extend(where_conditions)
171
+ args.append("set")
172
+ if set_values:
173
+ args.extend(set_values)
174
+ where_str = " ".join(where_conditions)
175
+ set_str = " ".join(set_values) if set_values else ""
176
+ if not dry_run:
177
+ console.print(
178
+ f"Updating accounts where {where_str} set {set_str}"
179
+ )
180
+ else:
181
+ # Simple mode - update by name
182
+ args.append("where")
183
+ args.append(f"name={name}")
184
+ args.append("set")
185
+ for key, value in kwargs.items():
186
+ if value is not None:
187
+ args.append(f"{key}={value}")
188
+ else:
189
+ args.append(key)
190
+ if not dry_run:
191
+ console.print(f"Updating account: {name}")
192
+
193
+ if dry_run:
194
+ console.print(f"[yellow]DRY RUN:[/yellow] {' '.join(args)}")
195
+ return
196
+
197
+ try:
198
+ result = subprocess.run(
199
+ args,
200
+ check=True,
201
+ capture_output=True,
202
+ text=True,
203
+ )
204
+ if result.stdout:
205
+ console.print(result.stdout)
206
+ if verbose:
207
+ console.print(
208
+ "[green]Account updated successfully.[/green]"
209
+ )
210
+ except subprocess.CalledProcessError as e:
211
+ console.print(
212
+ f"[red]Failed to update account:[/red] {e.stderr or e}"
213
+ )
214
+
215
+ @classmethod
216
+ def delete(cls, name: str) -> None:
217
+ """Delete an account."""
218
+ # TODO: Implement actual account deletion using sacctmgr delete account
219
+ console.print(f"Deleting account: {name}")
220
+
221
+ # Default column configuration for accounts
222
+ DEFAULT_COLUMNS = [
223
+ "name",
224
+ "description",
225
+ "organization",
226
+ "coordinators",
227
+ "flags",
228
+ "associations",
229
+ ]
230
+ DEFAULT_STYLES = {
231
+ "name": "cyan",
232
+ "description": "white",
233
+ "organization": "green",
234
+ "coordinators": "yellow",
235
+ "flags": "magenta",
236
+ "associations": "blue",
237
+ }
238
+
239
+ @classmethod
240
+ def _get_column_config(
241
+ cls,
242
+ profile: str = "default",
243
+ profile_str: Optional[str] = None,
244
+ ) -> tuple:
245
+ """Get column configuration from profile.
246
+
247
+ Returns:
248
+ Tuple of (columns, styles, template, sort_field, sort_asc)
249
+ """
250
+ (
251
+ columns,
252
+ styles,
253
+ template,
254
+ sort_field,
255
+ sort_asc,
256
+ ) = get_profile_config(profile, "accounts", profile_str)
257
+
258
+ # Use default columns if profile specifies "*" or no columns
259
+ if columns == "*" or columns is None:
260
+ columns = cls.DEFAULT_COLUMNS
261
+
262
+ # Merge with default styles
263
+ merged_styles = dict(cls.DEFAULT_STYLES)
264
+ merged_styles.update(styles)
265
+
266
+ return columns, merged_styles, template, sort_field, sort_asc
267
+
268
+ @classmethod
269
+ def _format_value(cls, account: Dict[str, Any], column: str) -> str:
270
+ """Format a value for display."""
271
+ value = account.get(column, "")
272
+ # Handle array fields
273
+ if column in ("coordinators", "flags", "associations"):
274
+ if isinstance(value, list):
275
+ return (
276
+ ", ".join(str(v) for v in value) if value else "-"
277
+ )
278
+ if value is None or value == "":
279
+ return "-"
280
+ return str(value)
281
+
282
+ @classmethod
283
+ def _parse_filter(cls, filter_str: str) -> Optional[tuple]:
284
+ """Parse a filter string like 'organization=nvidia'.
285
+
286
+ Returns:
287
+ Tuple of (key, value) if valid filter, None otherwise.
288
+ """
289
+ if "=" in filter_str:
290
+ key, value = filter_str.split("=", 1)
291
+ return (key.lower(), value)
292
+ return None
293
+
294
+ @classmethod
295
+ def _apply_filters(
296
+ cls, accounts: List[Dict[str, Any]], filters: List[tuple]
297
+ ) -> List[Dict[str, Any]]:
298
+ """Apply filters to account list.
299
+
300
+ Args:
301
+ accounts: List of account dictionaries
302
+ filters: List of (key, value) tuples to filter by
303
+
304
+ Returns:
305
+ Filtered list of accounts
306
+ """
307
+ for key, value in filters:
308
+ accounts = [
309
+ acc
310
+ for acc in accounts
311
+ if str(acc.get(key, "")).lower() == value.lower()
312
+ ]
313
+ return accounts
314
+
315
+ @classmethod
316
+ def _sort_hierarchically(
317
+ cls,
318
+ accounts: List[Dict[str, Any]],
319
+ indent: str = " ",
320
+ ) -> List[Dict[str, Any]]:
321
+ """Sort accounts hierarchically and add depth/indent info.
322
+
323
+ Args:
324
+ accounts: List of account dictionaries
325
+ indent: Indentation string per level (default: two spaces)
326
+
327
+ Returns:
328
+ Sorted list with '_depth' and '_indent' keys added
329
+ """
330
+ # Build parent-child relationships
331
+ account_map = {} # name -> account_data
332
+ children_map: Dict[
333
+ str, List[str]
334
+ ] = {} # parent_name -> [child_names]
335
+
336
+ for acc in accounts:
337
+ name = acc.get("name", "")
338
+ parent = acc.get("parent", "") or acc.get(
339
+ "parent_account", ""
340
+ )
341
+ account_map[name] = acc
342
+
343
+ if parent not in children_map:
344
+ children_map[parent] = []
345
+ children_map[parent].append(name)
346
+
347
+ # Find root accounts (no parent or parent not in map)
348
+ root_accounts = []
349
+ for name, acc in account_map.items():
350
+ parent = acc.get("parent", "") or acc.get(
351
+ "parent_account", ""
352
+ )
353
+ if not parent or parent not in account_map:
354
+ root_accounts.append(name)
355
+
356
+ root_accounts.sort()
357
+
358
+ # Build sorted list with depth
359
+ result: List[Dict[str, Any]] = []
360
+
361
+ def add_account(account_name: str, depth: int):
362
+ acc = account_map.get(account_name, {})
363
+ acc_copy = acc.copy()
364
+ acc_copy["_depth"] = depth
365
+ acc_copy["_indent"] = indent * depth
366
+ acc_copy["_is_account"] = True
367
+ result.append(acc_copy)
368
+
369
+ # Add children (sorted)
370
+ children = sorted(children_map.get(account_name, []))
371
+ for child in children:
372
+ add_account(child, depth + 1)
373
+
374
+ for root in root_accounts:
375
+ add_account(root, 0)
376
+
377
+ return result
378
+
379
+ @classmethod
380
+ def show(
381
+ cls,
382
+ field: Union[str, None] = None,
383
+ style: str = "pretty",
384
+ force_cache_update: bool = False,
385
+ delimiter: str = ";",
386
+ zebra: bool = False,
387
+ profile: str = "default",
388
+ profile_str: Optional[str] = None,
389
+ tree: bool = False,
390
+ ) -> None:
391
+ """Show account information.
392
+
393
+ Args:
394
+ field: Optional account name or filter (e.g., organization=nvidia)
395
+ style: Output style ("pretty", "json", or "csv")
396
+ force_cache_update: Whether to force cache update (unused)
397
+ delimiter: Delimiter for CSV output (default: ";")
398
+ zebra: Use zebra striping for table rows (default: False)
399
+ profile: Profile name to use for output formatting
400
+ profile_str: Inline profile string (overrides profile)
401
+ tree: Show accounts in hierarchical tree format
402
+ """
403
+ try:
404
+ # Always get JSON output from sacctmgr
405
+ result = subprocess.run(
406
+ ["sacctmgr", "show", "accounts", "--json"],
407
+ check=True,
408
+ capture_output=True,
409
+ text=True,
410
+ )
411
+
412
+ if not result.stdout:
413
+ console.print("[yellow]No accounts found.[/yellow]")
414
+ return
415
+
416
+ # Parse JSON data
417
+ data = json.loads(result.stdout)
418
+ accounts = data.get("accounts", [])
419
+
420
+ # Filter by field if specified
421
+ if field:
422
+ # Check if field is a filter (contains '=') or a name
423
+ parsed_filter = cls._parse_filter(field)
424
+ if parsed_filter:
425
+ # It's a filter like organization=nvidia
426
+ accounts = cls._apply_filters(
427
+ accounts, [parsed_filter]
428
+ )
429
+ if not accounts:
430
+ console.print(
431
+ f"[yellow]No accounts match filter "
432
+ f"'{field}'.[/yellow]"
433
+ )
434
+ return
435
+ else:
436
+ # It's an account name
437
+ accounts = [
438
+ acc
439
+ for acc in accounts
440
+ if acc.get("name") == field
441
+ ]
442
+ if not accounts:
443
+ console.print(
444
+ f"[yellow]Account '{field}' not found.[/yellow]"
445
+ )
446
+ return
447
+
448
+ # Get column configuration from profile (once)
449
+ (
450
+ columns,
451
+ styles,
452
+ template,
453
+ sort_field,
454
+ sort_asc,
455
+ ) = cls._get_column_config(profile, profile_str)
456
+
457
+ # Tree mode or flat sorting
458
+ if tree and style == "pretty":
459
+ # Hierarchical mode - add depth/indent info
460
+ accounts = cls._sort_hierarchically(accounts)
461
+ # Apply hierarchical sorting if specified
462
+ if sort_field:
463
+ accounts = sort_hierarchical_data(
464
+ accounts,
465
+ sort_field,
466
+ sort_asc,
467
+ depth_key="_depth",
468
+ parent_key="parent",
469
+ id_key="name",
470
+ )
471
+ elif sort_field:
472
+ # Flat mode sorting
473
+ accounts = sort_data(accounts, sort_field, sort_asc)
474
+
475
+ if style == "json":
476
+ # Print filtered JSON
477
+ filtered_data = {"accounts": accounts}
478
+ console.print_json(json.dumps(filtered_data, indent=2))
479
+ elif style == "csv":
480
+ # Header
481
+ headers = [col.title() for col in columns]
482
+ print(delimiter.join(headers))
483
+
484
+ # Data rows
485
+ for account in accounts:
486
+ row = [
487
+ cls._format_value(account, col)
488
+ for col in columns
489
+ ]
490
+ # Replace "-" with empty for CSV
491
+ row = ["" if v == "-" else v for v in row]
492
+ print(delimiter.join(row))
493
+ else: # pretty style
494
+ # If template is specified, use template-based output
495
+ if template:
496
+ for account in accounts:
497
+ output = format_with_template(
498
+ template, account, resource="accounts"
499
+ )
500
+ console.print(output)
501
+ else:
502
+ # Create a rich table
503
+ row_styles = (
504
+ ["", "on rgb(30,40,60)"] if zebra else None
505
+ )
506
+ table = Table(
507
+ title="Accounts",
508
+ box=SIMPLE_HEAVY,
509
+ pad_edge=False,
510
+ padding=(0, 0),
511
+ row_styles=row_styles,
512
+ )
513
+
514
+ # Add columns based on profile
515
+ for col in columns:
516
+ table.add_column(
517
+ col.title(),
518
+ style=styles.get(col, ""),
519
+ no_wrap=(col == "name"),
520
+ )
521
+
522
+ # Add rows
523
+ for account in accounts:
524
+ row = []
525
+ indent = account.get("_indent", "")
526
+ for col in columns:
527
+ value = cls._format_value(account, col)
528
+ # Prepend indent to name column in tree mode
529
+ if col == "name" and indent:
530
+ value = indent + value
531
+ row.append(value)
532
+ table.add_row(*row)
533
+
534
+ console.print(table)
535
+
536
+ except subprocess.CalledProcessError as e:
537
+ error_msg = e.stderr or e
538
+ console.print(
539
+ f"[red]Failed to show accounts:[/red] {error_msg}"
540
+ )
541
+ except json.JSONDecodeError as e:
542
+ console.print(
543
+ f"[red]Failed to parse JSON output:[/red] {e}"
544
+ )