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.
@@ -0,0 +1,871 @@
1
+ """Utilities for managing associations."""
2
+
3
+ import io
4
+ import json
5
+ import subprocess
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ from rich.box import SIMPLE_HEAVY
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from .base_resource import BaseSlurmResource
13
+ from .profiles import (
14
+ format_with_template,
15
+ get_profile_config,
16
+ sort_data,
17
+ sort_hierarchical_data,
18
+ )
19
+ from .utils import console
20
+
21
+ # Association filter/select options (used for WHERE clause)
22
+ ASSOCIATION_FILTER_OPTIONS: List[str] = [
23
+ "Account",
24
+ "Cluster",
25
+ "Partition",
26
+ "User",
27
+ ]
28
+
29
+ # Association SET options (sacctmgr field names for create/update)
30
+ ASSOCIATION_SET_OPTIONS: List[str] = [
31
+ "DefaultQOS",
32
+ "Fairshare",
33
+ "Share",
34
+ "GrpJobs",
35
+ "GrpJobsAccrue",
36
+ "GrpSubmit",
37
+ "GrpSubmitJobs",
38
+ "GrpTRES",
39
+ "GrpTRESMins",
40
+ "GrpTRESRunMins",
41
+ "GrpWall",
42
+ "MaxJobs",
43
+ "MaxJobsAccrue",
44
+ "MaxSubmit",
45
+ "MaxSubmitJobs",
46
+ "MaxTRES",
47
+ "MaxTRESPJ",
48
+ "MaxTRESPerJob",
49
+ "MaxTRESMins",
50
+ "MaxTRESMinsPJ",
51
+ "MaxTRESMinsPerJob",
52
+ "MaxTRESPN",
53
+ "MaxTRESPerNode",
54
+ "MaxWall",
55
+ "MaxWallDurationPerJob",
56
+ "Priority",
57
+ ]
58
+
59
+ # QosLevel supports =, +=, -= operators
60
+ ASSOCIATION_QOSLEVEL_OPTIONS: List[str] = [
61
+ "QosLevel=",
62
+ "QosLevel+=",
63
+ "QosLevel-=",
64
+ ]
65
+
66
+ # Combined options for backward compatibility
67
+ ASSOCIATION_OPTIONS: List[str] = (
68
+ ASSOCIATION_FILTER_OPTIONS + ASSOCIATION_SET_OPTIONS
69
+ )
70
+
71
+
72
+ class Association(BaseSlurmResource):
73
+ def __init__(self, account: str, **kwargs: Any):
74
+ self.account = account
75
+ self.kwargs = kwargs
76
+
77
+ @classmethod
78
+ def get_profile_fields(cls) -> dict:
79
+ """Return field names and descriptions for profile templates."""
80
+ return {
81
+ "account": "Account name",
82
+ "user": "User name (empty for account associations)",
83
+ "cluster": "Cluster name",
84
+ "partition": "Partition name",
85
+ "shares_raw": "Raw shares value",
86
+ "priority": "Priority value",
87
+ "qos": "List of allowed QOS",
88
+ "is_default": "Whether this is the default association",
89
+ "lineage": "Account lineage path",
90
+ "parent_account": "Parent account name",
91
+ # SET options
92
+ "default_qos": "Default QOS for association",
93
+ "fairshare": "Fairshare value",
94
+ "grp_jobs": "Group jobs limit",
95
+ "grp_jobs_accrue": "Group jobs accrue limit",
96
+ "grp_submit": "Group submit limit",
97
+ "grp_submit_jobs": "Group submit jobs limit",
98
+ "grp_tres": "Group TRES limits",
99
+ "grp_tres_mins": "Group TRES minutes limit",
100
+ "grp_tres_run_mins": "Group TRES running minutes limit",
101
+ "grp_wall": "Group wall time limit",
102
+ "max_jobs": "Maximum jobs limit",
103
+ "max_jobs_accrue": "Maximum jobs accrue limit",
104
+ "max_submit": "Maximum submit limit",
105
+ "max_submit_jobs": "Maximum submit jobs limit",
106
+ "max_tres": "Maximum TRES limits",
107
+ "max_tres_pj": "Maximum TRES per job",
108
+ "max_tres_mins": "Maximum TRES minutes",
109
+ "max_tres_mins_pj": "Maximum TRES minutes per job",
110
+ "max_tres_pn": "Maximum TRES per node",
111
+ "max_wall": "Maximum wall time limit",
112
+ "max_wall_pj": "Maximum wall time per job",
113
+ }
114
+
115
+ @classmethod
116
+ def generate_autocomplete_options(cls) -> str:
117
+ """Generate bash autocomplete script for association options."""
118
+ filter_keys = [
119
+ opt.lower() for opt in ASSOCIATION_FILTER_OPTIONS
120
+ ]
121
+ set_keys = [opt.lower() for opt in ASSOCIATION_SET_OPTIONS]
122
+ qoslevel_opts = " ".join(
123
+ opt.lower() for opt in ASSOCIATION_QOSLEVEL_OPTIONS
124
+ )
125
+ filter_opts = " ".join(f"{k}=" for k in filter_keys)
126
+ set_opts = " ".join(f"{k}=" for k in set_keys)
127
+
128
+ script = f"""
129
+ _slurm_cli_associations_autocomplete() {{
130
+ local cmd="$1"
131
+ local pos="$2"
132
+
133
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
134
+ local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
135
+ local name="${{COMP_WORDS[$pos]}}"
136
+
137
+ local cached_accounts="$(_slurm_cache_accounts)"
138
+ local cached_users="$(_slurm_cache_users)"
139
+ local filter_options="{filter_opts}"
140
+ local set_options="{set_opts} {qoslevel_opts}"
141
+ local update_options="$filter_options $set_options set"
142
+ local create_options="$filter_options $set_options"
143
+
144
+ # Handle key=value, key+=value, or key-=value completion
145
+ if _slurm_parse_keyval_ext "$cur" "$prev"; then
146
+ case "$_key" in
147
+ account)
148
+ _slurm_complete_value "$cached_accounts" "$_key" "$_val" "$cur" ;;
149
+ user)
150
+ _slurm_complete_value "$cached_users" "$_key" "$_val" "$cur" ;;
151
+ defaultqos|qos|qoslevel)
152
+ _slurm_complete_value "$(_slurm_cache_qos)" "$_key" "$_val" "$cur" ;;
153
+ partition)
154
+ _slurm_complete_value "$(_slurm_cache_partitions)" "$_key" "$_val" "$cur" ;;
155
+ esac
156
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && return
157
+ fi
158
+
159
+ # First argument after 'associations'
160
+ if [[ $name == associations && $prev == associations ]]; then
161
+ case "$cmd" in
162
+ show|delete) _slurm_complete "$filter_options $cached_accounts" "$cur" ;;
163
+ create) _slurm_complete "$create_options" "$cur" ;;
164
+ update) _slurm_complete "$update_options $cached_accounts" "$cur" ;;
165
+ esac
166
+ return
167
+ fi
168
+
169
+ # Default completion for subsequent arguments
170
+ case "$cmd" in
171
+ show|delete) _slurm_complete "$filter_options" "$cur" ;;
172
+ create) _slurm_complete "$create_options" "$cur" ;;
173
+ update) _slurm_complete "$update_options" "$cur" ;;
174
+ esac
175
+ }}
176
+ """ # noqa: E501
177
+ return script
178
+
179
+ # Default column configuration for associations
180
+ DEFAULT_COLUMNS = [
181
+ "account",
182
+ "user",
183
+ "cluster",
184
+ "partition",
185
+ "shares_raw",
186
+ "qos",
187
+ ]
188
+ # All available columns from Slurm JSON output
189
+ ALL_COLUMNS = [
190
+ "account",
191
+ "user",
192
+ "cluster",
193
+ "partition",
194
+ "shares_raw",
195
+ "priority",
196
+ "qos",
197
+ "is_default",
198
+ "lineage",
199
+ "parent_account",
200
+ "id",
201
+ "comment",
202
+ "flags",
203
+ "default",
204
+ "max",
205
+ "min",
206
+ ]
207
+ DEFAULT_STYLES = {
208
+ "account": "cyan",
209
+ "user": "green",
210
+ "cluster": "yellow",
211
+ "partition": "magenta",
212
+ "shares_raw": "white",
213
+ "qos": "blue",
214
+ }
215
+
216
+ @classmethod
217
+ def _get_column_config(
218
+ cls,
219
+ profile: str = "default",
220
+ profile_str: Optional[str] = None,
221
+ ) -> tuple:
222
+ """Get column configuration from profile.
223
+
224
+ Returns:
225
+ Tuple of (columns, styles, template, sort_field, sort_asc)
226
+ """
227
+ (
228
+ columns,
229
+ styles,
230
+ template,
231
+ sort_field,
232
+ sort_asc,
233
+ ) = get_profile_config(profile, "associations", profile_str)
234
+
235
+ # Use all columns if profile specifies "*"
236
+ if columns == "*":
237
+ columns = cls.ALL_COLUMNS
238
+ # Use default columns if no columns specified
239
+ elif columns is None:
240
+ columns = cls.DEFAULT_COLUMNS
241
+
242
+ # Merge with default styles
243
+ merged_styles = dict(cls.DEFAULT_STYLES)
244
+ merged_styles.update(styles)
245
+
246
+ return columns, merged_styles, template, sort_field, sort_asc
247
+
248
+ @classmethod
249
+ def _format_value(cls, assoc: Dict[str, Any], column: str) -> str:
250
+ """Format a value for display."""
251
+ value = assoc.get(column, "")
252
+ # Handle array fields
253
+ if column in ("qos", "flags", "accounting"):
254
+ if isinstance(value, list):
255
+ return ",".join(str(v) for v in value) if value else "-"
256
+ # Handle nested id field
257
+ if column == "id" and isinstance(value, dict):
258
+ return str(value.get("id", "-"))
259
+ # Handle priority field (may be a dict with set/number)
260
+ if column == "priority" and isinstance(value, dict):
261
+ if value.get("set"):
262
+ return str(value.get("number", 0))
263
+ return "-"
264
+ # Handle nested 'default' field (contains qos)
265
+ if column == "default" and isinstance(value, dict):
266
+ qos = value.get("qos", "")
267
+ return qos if qos else "-"
268
+ # Handle nested 'max' and 'min' fields (complex limit structures)
269
+ if column in ("max", "min") and isinstance(value, dict):
270
+ # Summarize the nested structure
271
+ parts = []
272
+ if "jobs" in value:
273
+ jobs = value["jobs"]
274
+ if isinstance(jobs, dict):
275
+ active = jobs.get("active", {})
276
+ if isinstance(active, dict) and active.get("set"):
277
+ parts.append(f"jobs={active.get('number', 0)}")
278
+ if "tres" in value:
279
+ tres = value["tres"]
280
+ if isinstance(tres, dict):
281
+ for tres_type in ("per", "minutes"):
282
+ if tres_type in tres and isinstance(
283
+ tres[tres_type], dict
284
+ ):
285
+ for k, v in tres[tres_type].items():
286
+ if isinstance(v, dict) and v.get("set"):
287
+ parts.append(
288
+ f"{k}={v.get('number', 0)}"
289
+ )
290
+ return ", ".join(parts) if parts else "-"
291
+ if value is None or value == "":
292
+ return "-"
293
+ return str(value)
294
+
295
+ @classmethod
296
+ def _parse_filter(cls, filter_str: str) -> Optional[tuple]:
297
+ """Parse a filter string like 'account=nvidia'.
298
+
299
+ Returns:
300
+ Tuple of (key, value) if valid filter, None otherwise.
301
+ """
302
+ if "=" in filter_str:
303
+ key, value = filter_str.split("=", 1)
304
+ return (key.lower(), value)
305
+ return None
306
+
307
+ @classmethod
308
+ def _apply_filters(
309
+ cls, associations: List[Dict[str, Any]], filters: List[tuple]
310
+ ) -> List[Dict[str, Any]]:
311
+ """Apply filters to association list.
312
+
313
+ Args:
314
+ associations: List of association dictionaries
315
+ filters: List of (key, value) tuples to filter by
316
+
317
+ Returns:
318
+ Filtered list of associations
319
+ """
320
+ for key, value in filters:
321
+ associations = [
322
+ assoc
323
+ for assoc in associations
324
+ if str(assoc.get(key, "")).lower() == value.lower()
325
+ ]
326
+ return associations
327
+
328
+ @classmethod
329
+ def _sort_hierarchically(
330
+ cls, associations: List[Dict[str, Any]], indent: str = " "
331
+ ) -> List[Dict[str, Any]]:
332
+ """Sort associations hierarchically and add depth/indent info.
333
+
334
+ Args:
335
+ associations: List of association dictionaries
336
+ indent: Indentation string per level (default: two spaces)
337
+
338
+ Returns:
339
+ Sorted list with '_depth' and '_indent' keys added
340
+ """
341
+ # Build account hierarchy
342
+ accounts = {} # account -> {parent, users, children, assocs}
343
+ for assoc in associations:
344
+ account = assoc.get("account", "")
345
+ parent = assoc.get("parent_account", "")
346
+ user = assoc.get("user", "")
347
+
348
+ if account not in accounts:
349
+ accounts[account] = {
350
+ "parent": parent,
351
+ "users": [],
352
+ "children": [],
353
+ "account_assoc": None,
354
+ }
355
+
356
+ if user:
357
+ accounts[account]["users"].append(assoc)
358
+ else:
359
+ accounts[account]["account_assoc"] = assoc
360
+
361
+ # Build parent-child relationships
362
+ for account, info in accounts.items():
363
+ parent = info["parent"]
364
+ if parent and parent in accounts:
365
+ if account not in accounts[parent]["children"]:
366
+ accounts[parent]["children"].append(account)
367
+
368
+ # Find root accounts
369
+ root_accounts = [
370
+ acc
371
+ for acc, info in accounts.items()
372
+ if not info["parent"] or info["parent"] not in accounts
373
+ ]
374
+ root_accounts.sort()
375
+
376
+ # Traverse tree and build sorted list with depth
377
+ result = []
378
+
379
+ def add_account(account_name: str, depth: int):
380
+ info = accounts.get(account_name, {})
381
+
382
+ # Add account-level association
383
+ if info.get("account_assoc"):
384
+ assoc = info["account_assoc"].copy()
385
+ assoc["_depth"] = depth
386
+ assoc["_indent"] = indent * depth
387
+ assoc["_is_account"] = True # Flag for sorting
388
+ result.append(assoc)
389
+
390
+ # Add users (sorted)
391
+ users = sorted(
392
+ info.get("users", []), key=lambda u: u.get("user", "")
393
+ )
394
+ for user_assoc in users:
395
+ assoc = user_assoc.copy()
396
+ assoc["_depth"] = depth + 1
397
+ assoc["_indent"] = indent * (depth + 1)
398
+ assoc[
399
+ "_parent_id"
400
+ ] = account_name # For hierarchical sorting
401
+ assoc["_is_account"] = False
402
+ result.append(assoc)
403
+
404
+ # Add child accounts (sorted)
405
+ children = sorted(info.get("children", []))
406
+ for child in children:
407
+ add_account(child, depth + 1)
408
+
409
+ for root in root_accounts:
410
+ add_account(root, 0)
411
+
412
+ return result
413
+
414
+ @classmethod
415
+ def _show_tree(cls, associations: List[Dict[str, Any]]) -> None:
416
+ """Display associations in a hierarchical tree format.
417
+
418
+ Groups associations by account hierarchy and shows users under
419
+ their respective accounts with proper indentation.
420
+
421
+ Args:
422
+ associations: List of association dictionaries
423
+ """
424
+ from rich.tree import Tree
425
+
426
+ # Build account hierarchy
427
+ # First, find all unique accounts and their parent relationships
428
+ accounts = {} # account -> {parent, users, children}
429
+ for assoc in associations:
430
+ account = assoc.get("account", "")
431
+ parent = assoc.get("parent_account", "")
432
+ user = assoc.get("user", "")
433
+ partition = assoc.get("partition", "")
434
+ qos = assoc.get("qos", [])
435
+ if isinstance(qos, list):
436
+ qos = ",".join(qos) if qos else ""
437
+
438
+ if account not in accounts:
439
+ accounts[account] = {
440
+ "parent": parent,
441
+ "users": [],
442
+ "children": [],
443
+ "partition": partition,
444
+ "qos": qos,
445
+ }
446
+
447
+ # If this is a user association, add to users list
448
+ if user:
449
+ accounts[account]["users"].append(
450
+ {"user": user, "partition": partition, "qos": qos}
451
+ )
452
+
453
+ # Build parent-child relationships
454
+ for account, info in accounts.items():
455
+ parent = info["parent"]
456
+ if parent and parent in accounts:
457
+ if account not in accounts[parent]["children"]:
458
+ accounts[parent]["children"].append(account)
459
+
460
+ # Find root accounts (no parent or parent not in list)
461
+ root_accounts = [
462
+ acc
463
+ for acc, info in accounts.items()
464
+ if not info["parent"] or info["parent"] not in accounts
465
+ ]
466
+
467
+ # Sort root accounts
468
+ root_accounts.sort()
469
+
470
+ def add_children_to_node(
471
+ parent_node, account_name: str, info: dict
472
+ ):
473
+ """Add users and child accounts to a node."""
474
+ # Add users under this account
475
+ users = info.get("users", [])
476
+ users.sort(key=lambda u: u["user"])
477
+ for user_info in users:
478
+ user = user_info["user"]
479
+ u_qos = user_info.get("qos", "")
480
+ u_part = user_info.get("partition", "")
481
+ u_qos_str = f" [dim]qos={u_qos}[/dim]" if u_qos else ""
482
+ u_part_str = (
483
+ f" [dim]partition={u_part}[/dim]" if u_part else ""
484
+ )
485
+ parent_node.add(
486
+ f"[green]{user}[/green]{u_part_str}{u_qos_str}"
487
+ )
488
+
489
+ # Add child accounts
490
+ children = info.get("children", [])
491
+ children.sort()
492
+ for child in children:
493
+ child_info = accounts.get(child, {})
494
+ qos_str = (
495
+ f" [dim]qos={child_info.get('qos', '')}[/dim]"
496
+ if child_info.get("qos")
497
+ else ""
498
+ )
499
+ part_str = (
500
+ f" [dim]partition={child_info.get('partition', '')}[/dim]"
501
+ if child_info.get("partition")
502
+ else ""
503
+ )
504
+ child_node = parent_node.add(
505
+ f"[bold yellow]{child}[/bold yellow]{part_str}{qos_str}"
506
+ )
507
+ add_children_to_node(child_node, child, child_info)
508
+
509
+ # Build and print tree for each root account
510
+ for root in root_accounts:
511
+ info = accounts.get(root, {})
512
+ qos_str = (
513
+ f" [dim]qos={info.get('qos', '')}[/dim]"
514
+ if info.get("qos")
515
+ else ""
516
+ )
517
+ part_str = (
518
+ f" [dim]partition={info.get('partition', '')}[/dim]"
519
+ if info.get("partition")
520
+ else ""
521
+ )
522
+ tree = Tree(
523
+ f"[bold yellow]{root}[/bold yellow]{part_str}{qos_str}"
524
+ )
525
+ add_children_to_node(tree, root, info)
526
+ console.print(tree)
527
+
528
+ @classmethod
529
+ def show(
530
+ cls,
531
+ field: Union[str, None] = None,
532
+ style: str = "pretty",
533
+ force_cache_update: bool = False,
534
+ delimiter: str = ";",
535
+ zebra: bool = False,
536
+ profile: str = "default",
537
+ profile_str: Optional[str] = None,
538
+ tree: bool = False,
539
+ indent: str = " ",
540
+ ) -> None:
541
+ """Show association information.
542
+
543
+ Args:
544
+ field: Optional filter (e.g., account=nvidia or user=john)
545
+ style: Output style ("pretty", "json", or "csv")
546
+ force_cache_update: Whether to force cache update (unused)
547
+ delimiter: Delimiter for CSV output (default: ";")
548
+ zebra: Use zebra striping for table rows (default: False)
549
+ profile: Profile name to use for output formatting
550
+ profile_str: Inline profile string (overrides profile)
551
+ indent: Indentation string for tree mode (default: two spaces)
552
+ tree: Show associations in hierarchical tree format
553
+ """
554
+ try:
555
+ # Always get JSON output from sacctmgr
556
+ result = subprocess.run(
557
+ ["sacctmgr", "show", "associations", "--json"],
558
+ check=True,
559
+ capture_output=True,
560
+ text=True,
561
+ )
562
+
563
+ if not result.stdout:
564
+ console.print("[yellow]No associations found.[/yellow]")
565
+ return
566
+
567
+ # Parse JSON data
568
+ data = json.loads(result.stdout)
569
+ associations = data.get("associations", [])
570
+
571
+ # Filter by field if specified
572
+ if field:
573
+ # Check if field is a filter (contains '=') or a name
574
+ parsed_filter = cls._parse_filter(field)
575
+ if parsed_filter:
576
+ # It's a filter like account=nvidia
577
+ associations = cls._apply_filters(
578
+ associations, [parsed_filter]
579
+ )
580
+ if not associations:
581
+ console.print(
582
+ f"[yellow]No associations match filter "
583
+ f"'{field}'.[/yellow]"
584
+ )
585
+ return
586
+ else:
587
+ # Treat as account name filter
588
+ associations = [
589
+ assoc
590
+ for assoc in associations
591
+ if assoc.get("account") == field
592
+ ]
593
+ if not associations:
594
+ console.print(
595
+ f"[yellow]No associations for account "
596
+ f"'{field}'.[/yellow]"
597
+ )
598
+ return
599
+
600
+ # Get column configuration from profile (once)
601
+ (
602
+ columns,
603
+ styles,
604
+ template,
605
+ sort_field,
606
+ sort_asc,
607
+ ) = cls._get_column_config(profile, profile_str)
608
+
609
+ if tree:
610
+ # Tree mode - sort hierarchically and add indent
611
+ associations = cls._sort_hierarchically(
612
+ associations, indent
613
+ )
614
+ # Apply hierarchical sorting if specified
615
+ if sort_field:
616
+ associations = sort_hierarchical_data(
617
+ associations,
618
+ sort_field,
619
+ sort_asc,
620
+ depth_key="_depth",
621
+ parent_key="parent_account",
622
+ id_key="account",
623
+ )
624
+ elif sort_field:
625
+ # Flat mode sorting
626
+ associations = sort_data(
627
+ associations, sort_field, sort_asc
628
+ )
629
+
630
+ if style == "json":
631
+ # Print filtered JSON
632
+ filtered_data = {"associations": associations}
633
+ console.print_json(json.dumps(filtered_data, indent=2))
634
+ elif style == "csv":
635
+ # Header
636
+ headers = [col.title() for col in columns]
637
+ print(delimiter.join(headers))
638
+
639
+ # Data rows
640
+ for assoc in associations:
641
+ row = []
642
+ for i, col in enumerate(columns):
643
+ value = cls._format_value(assoc, col)
644
+ # Add indent to first column in tree mode
645
+ if i == 0 and tree and "_indent" in assoc:
646
+ value = assoc["_indent"] + value
647
+ row.append(value)
648
+ # Replace "-" with empty for CSV
649
+ row = ["" if v == "-" else v for v in row]
650
+ print(delimiter.join(row))
651
+ else: # pretty style
652
+ # If template is specified, use template-based output
653
+ if template:
654
+ for assoc in associations:
655
+ output = format_with_template(
656
+ template, assoc, resource="associations"
657
+ )
658
+ console.print(output)
659
+ else:
660
+ # Create a rich table
661
+ row_styles = (
662
+ ["", "on rgb(30,40,60)"] if zebra else None
663
+ )
664
+ table = Table(
665
+ title="Associations",
666
+ box=SIMPLE_HEAVY,
667
+ pad_edge=False,
668
+ padding=(0, 0),
669
+ row_styles=row_styles,
670
+ expand=False,
671
+ )
672
+
673
+ # Add columns based on profile
674
+ for col in columns:
675
+ table.add_column(
676
+ col.title(),
677
+ style=styles.get(col, ""),
678
+ no_wrap=True,
679
+ overflow="ignore",
680
+ )
681
+
682
+ # Add rows
683
+ for assoc in associations:
684
+ row = []
685
+ for i, col in enumerate(columns):
686
+ value = cls._format_value(assoc, col)
687
+ # Add indent to first column in tree mode
688
+ if i == 0 and tree and "_indent" in assoc:
689
+ value = assoc["_indent"] + value
690
+ row.append(value)
691
+ table.add_row(*row)
692
+
693
+ # Use buffer-based console to prevent column truncation
694
+ buf = io.StringIO()
695
+ wide_console = Console(
696
+ file=buf, width=500, force_terminal=True
697
+ )
698
+ wide_console.print(table)
699
+ output = buf.getvalue()
700
+ print(output, end="")
701
+
702
+ except subprocess.CalledProcessError as e:
703
+ error_msg = e.stderr or e
704
+ console.print(
705
+ f"[red]Failed to show associations:[/red] {error_msg}"
706
+ )
707
+ except json.JSONDecodeError as e:
708
+ console.print(
709
+ f"[red]Failed to parse JSON output:[/red] {e}"
710
+ )
711
+
712
+ @classmethod
713
+ def create(
714
+ cls, name: str, verbose: bool = False, **kwargs: Any
715
+ ) -> None:
716
+ """Create a new association.
717
+
718
+ Uses 'sacctmgr create user' command which creates user associations.
719
+
720
+ Args:
721
+ name: Username for the association
722
+ verbose: Enable verbose output
723
+ **kwargs: Additional options (account, partition, qos, etc.)
724
+ """
725
+ console.print(f"Creating association for user: {name}")
726
+ args = [
727
+ "sacctmgr",
728
+ "-i",
729
+ "create",
730
+ "user",
731
+ f"name={name}",
732
+ ]
733
+ for key, value in kwargs.items():
734
+ if value is not None:
735
+ args.append(f"{key}={value}")
736
+
737
+ try:
738
+ result = subprocess.run(
739
+ args,
740
+ check=True,
741
+ capture_output=True,
742
+ text=True,
743
+ )
744
+ console.print(
745
+ f"[green]Association for user '{name}' created "
746
+ f"successfully.[/green]"
747
+ )
748
+ if result.stdout:
749
+ console.print(result.stdout)
750
+ except subprocess.CalledProcessError as e:
751
+ error_msg = e.stderr or e
752
+ console.print(
753
+ f"[red]Failed to create association for user "
754
+ f"'{name}':[/red] {error_msg}"
755
+ )
756
+
757
+ @classmethod
758
+ def update(
759
+ cls,
760
+ name: str,
761
+ verbose: bool = False,
762
+ dry_run: bool = False,
763
+ where_conditions: Optional[List[str]] = None,
764
+ set_values: Optional[List[str]] = None,
765
+ **kwargs: Any,
766
+ ) -> None:
767
+ """Update an association.
768
+
769
+ Uses 'sacctmgr modify user' command.
770
+
771
+ Args:
772
+ name: Username for the association
773
+ verbose: Enable verbose output
774
+ dry_run: If True, print command without executing
775
+ where_conditions: List of WHERE conditions
776
+ set_values: List of SET values
777
+ **kwargs: Additional SET values
778
+ """
779
+ args = ["sacctmgr", "-i", "modify", "user"]
780
+
781
+ if where_conditions is not None:
782
+ args.append("where")
783
+ args.extend(where_conditions)
784
+ args.append("set")
785
+ if set_values:
786
+ args.extend(set_values)
787
+ if not dry_run:
788
+ console.print(
789
+ f"Updating user associations where "
790
+ f"{' '.join(where_conditions)}"
791
+ )
792
+ else:
793
+ args.append("where")
794
+ args.append(f"name={name}")
795
+ args.append("set")
796
+ for key, value in kwargs.items():
797
+ if value is not None:
798
+ args.append(f"{key}={value}")
799
+ if not dry_run:
800
+ console.print(f"Updating association for user: {name}")
801
+
802
+ if dry_run:
803
+ console.print(f"[yellow]DRY RUN:[/yellow] {' '.join(args)}")
804
+ return
805
+
806
+ try:
807
+ result = subprocess.run(
808
+ args,
809
+ check=True,
810
+ capture_output=True,
811
+ text=True,
812
+ )
813
+ if result.stdout:
814
+ console.print(result.stdout)
815
+ if verbose:
816
+ console.print(
817
+ "[green]Association updated successfully.[/green]"
818
+ )
819
+ except subprocess.CalledProcessError as e:
820
+ console.print(
821
+ f"[red]Failed to update association:[/red] {e.stderr or e}"
822
+ )
823
+
824
+ @classmethod
825
+ def delete(
826
+ cls,
827
+ conditions: List[str],
828
+ dry_run: bool = False,
829
+ force: bool = False,
830
+ ) -> None:
831
+ """Delete associations matching the given conditions.
832
+
833
+ Args:
834
+ conditions: List of filter conditions
835
+ (e.g., ["user=john", "partition=batch"])
836
+ dry_run: If True, only show what would be deleted
837
+ force: If True, skip confirmation
838
+ """
839
+ if not conditions:
840
+ console.print(
841
+ "[red]No conditions specified for delete[/red]"
842
+ )
843
+ return
844
+
845
+ # Build the WHERE clause
846
+ where_clause = " ".join(conditions)
847
+
848
+ if dry_run:
849
+ console.print(
850
+ f"[yellow]DRY RUN:[/yellow] Would delete associations "
851
+ f"where {where_clause}"
852
+ )
853
+ return
854
+
855
+ # Build and execute the command
856
+ cmd = ["sacctmgr", "-i", "delete", "association", "where"]
857
+ cmd.extend(conditions)
858
+
859
+ try:
860
+ result = subprocess.run(
861
+ cmd, check=True, capture_output=True, text=True
862
+ )
863
+ console.print(
864
+ f"[green]Deleted associations where {where_clause}[/green]"
865
+ )
866
+ if result.stdout:
867
+ console.print(result.stdout)
868
+ except subprocess.CalledProcessError as e:
869
+ console.print(
870
+ f"[red]Failed to delete associations:[/red] {e.stderr or e}"
871
+ )