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,837 @@
1
+ """Utilities for managing partitions."""
2
+
3
+ import json
4
+ import subprocess
5
+ from typing import Any, Optional, Union, Dict
6
+
7
+ from rich.box import SIMPLE_HEAVY
8
+ from rich.markup import escape
9
+ from rich.table import Table
10
+
11
+ from .base_resource import BaseSlurmResource
12
+ from .profiles import (
13
+ format_with_template,
14
+ get_profile_config,
15
+ sort_data,
16
+ )
17
+
18
+ # from .resources import Resource, ResourceType
19
+ from .utils import console
20
+
21
+
22
+ class Partition(BaseSlurmResource):
23
+ _WIDTH = None
24
+
25
+ @classmethod
26
+ def get_profile_fields(cls) -> dict:
27
+ """Return field names and descriptions for profile templates."""
28
+ return {
29
+ "PartitionName": "Partition name",
30
+ "State": "Partition state",
31
+ "TotalNodes": "Total nodes in partition",
32
+ "TotalCPUs": "Total CPUs in partition",
33
+ "MaxTime": "Max time limit",
34
+ "DefaultTime": "Default time limit",
35
+ "Nodes": "Node list",
36
+ "AllowGroups": "Allowed groups",
37
+ "AllowAccounts": "Allowed accounts",
38
+ "DenyAccounts": "Denied accounts",
39
+ "AllowQos": "Allowed QoS",
40
+ "DenyQos": "Denied QoS",
41
+ "Default": "Is default partition",
42
+ "MaxNodes": "Max nodes per job",
43
+ "MinNodes": "Min nodes per job",
44
+ }
45
+
46
+ valid_args = {
47
+ "allocnodes": {
48
+ "type": "nodes",
49
+ "help": "Node list that can be allocated to jobs",
50
+ },
51
+ "allowaccounts": {
52
+ "type": "accounts",
53
+ "help": "Comma-separated list of accounts"
54
+ "that are allowed to use this partition",
55
+ },
56
+ "allowgroups": {
57
+ "type": "list",
58
+ "help": "Comma-separated list of groups"
59
+ "that are allowed to use this partition",
60
+ },
61
+ "allowqos": {
62
+ "type": "qos_list",
63
+ "help": "Comma-separated list of QOSs"
64
+ "that are allowed to use this partition",
65
+ },
66
+ "alternate": {
67
+ "type": "partition",
68
+ "help": "Alternate partition to be used if the "
69
+ 'state of this partition is "DRAIN" or "INACTIVE."',
70
+ },
71
+ "cpubind": {
72
+ "type": "[none, socket, ldom, core, thread, off]",
73
+ "help": "Specify the task binding mode to be used by"
74
+ " default for this partition",
75
+ },
76
+ "default": {
77
+ "type": "[yes, no, y, n, 1, 0]",
78
+ "help": "Specify if this partition is to be used by jobs"
79
+ "which do not explicitly identify a partition to use",
80
+ },
81
+ "defaulttime": {
82
+ "type": "time",
83
+ "help": "Run time limit used for jobs that don't specify a value",
84
+ },
85
+ "defmempercpu": {
86
+ "type": "memory",
87
+ "help": "Set the default memory to be allocated per CPU"
88
+ "for jobs in this partition",
89
+ },
90
+ "defmempernode": {
91
+ "type": "memory",
92
+ "help": "Set the default memory to be allocated per node"
93
+ "for jobs in this partition",
94
+ },
95
+ "denyaccounts": {
96
+ "type": "accounts",
97
+ "help": "Identify the Accounts which should be denied access"
98
+ "to this partition",
99
+ },
100
+ "denyqos": {
101
+ "type": "qos_list",
102
+ "help": "Identify the QOSs which should be denied access"
103
+ "to this partition",
104
+ },
105
+ "disablerootjobs": {
106
+ "type": "[yes, no, y, n, 1, 0]",
107
+ "help": "Specify if jobs can be executed as user root",
108
+ },
109
+ "exclusiveuser": {
110
+ "type": "[yes, no, y, n, 1, 0]",
111
+ "help": "Specify if nodes will be exclusively allocated to users",
112
+ },
113
+ "gracetime": {
114
+ "type": "time",
115
+ "help": "Specify the preemption grace time to be extended to"
116
+ " a job which has been selected for preemption",
117
+ },
118
+ "hidden": {
119
+ "type": "[yes, no, y, n, 1, 0]",
120
+ "help": "Specify if the partition and its jobs should be hidden"
121
+ "from view",
122
+ },
123
+ "jobdefaults": {
124
+ "type": "list",
125
+ "help": "Specify job default values using a comma-delimited list"
126
+ 'of "key=value" pairs',
127
+ },
128
+ "lln": {
129
+ "type": "[yes, no, y, n, 1, 0]",
130
+ "help": "Schedule jobs on the least loaded nodes "
131
+ "(based on the number of idle CPUs)",
132
+ },
133
+ "maxcpuspernode": {
134
+ "type": "int",
135
+ "help": "Set the maximum number of CPUs that can be allocated per"
136
+ " node to all jobs in this partition",
137
+ },
138
+ "maxcpuspersocket": {
139
+ "type": "int",
140
+ "help": "Set the maximum number of CPUs that can be allocated per"
141
+ " socket to all jobs in this partition",
142
+ },
143
+ "maxmempercpu": {
144
+ "type": "memory",
145
+ "help": "Set the maximum number of CPUs that can be allocated per"
146
+ "CPU for jobs in this partition",
147
+ },
148
+ "maxmempernode": {
149
+ "type": "memory",
150
+ "help": "Set the maximum number of memory that can be allocated"
151
+ " per node to all jobs in this partition",
152
+ },
153
+ "maxnodes": {
154
+ "type": "int",
155
+ "help": "Set the maximum number of nodes that can be allocated to"
156
+ "all jobs in this partition",
157
+ },
158
+ "maxtime": {
159
+ "type": "time",
160
+ "help": "Set the maximum time limit for all jobs in" " this partition",
161
+ },
162
+ "minnodes": {
163
+ "type": "int",
164
+ "help": "Set the minimum number of nodes that can be allocated to"
165
+ "all jobs in this partition",
166
+ },
167
+ "nodes": {
168
+ "type": "nodes",
169
+ "help": "Identify the node(s) to be associated with this" " partition",
170
+ },
171
+ "oversubscribe": {
172
+ "type": "[yes, no, y, n, 1, 0]",
173
+ "help": "Specify if compute resources (i.e. individual CPUs) in"
174
+ " this partition can be shared by multiple jobs",
175
+ },
176
+ "overtimelimit": {
177
+ "type": "int",
178
+ "help": "Number of minutes by which a job can exceed its time "
179
+ "limit before being canceled",
180
+ },
181
+ "powerdownonidle": {
182
+ "type": "[yes, no, y, n, 1, 0]",
183
+ "help": "If set to 'yes', then nodes allocated from this partition"
184
+ " will immediately be requested to power down upon becoming IDLE",
185
+ },
186
+ "preemptmode": {
187
+ "type": "[off, cancel, requeue, suspend]",
188
+ "help": "Reset the mechanism used to preempt jobs in this" " partition",
189
+ },
190
+ "priority": {
191
+ "type": "int",
192
+ "help": "Jobs submitted to a higher priority partition will"
193
+ " be dispatched before pending jobs in lower priority partitions",
194
+ },
195
+ "priorityjobfactor": {
196
+ "type": "int",
197
+ "help": "Partition factor used by priority/multifactor plugin in"
198
+ " calculating job priority",
199
+ },
200
+ "prioritytier": {
201
+ "type": "int",
202
+ "help": "Jobs submitted to a partition with a higher priority tier"
203
+ " value will be dispatched before pending jobs in partition with"
204
+ " lower priority tier value",
205
+ },
206
+ "qos": {
207
+ "type": "qos",
208
+ "help": "Set the partition QOS with a QOS name or to remove the"
209
+ " Partition QOS",
210
+ },
211
+ "reqresv": {
212
+ "type": "[yes, no, y, n, 1, 0]",
213
+ "help": "Specify if only allocation requests designating a"
214
+ " reservation will be satisfied",
215
+ },
216
+ "rootonly": {
217
+ "type": "[yes, no, y, n, 1, 0]",
218
+ "help": "Specify if only allocation requests initiated by user"
219
+ " root will be satisfied",
220
+ },
221
+ "tresbillingweights": {
222
+ "type": "list",
223
+ "help": "TRES Billing Weights",
224
+ },
225
+ "partitionname": {
226
+ "type": "str",
227
+ "help": "Partition name",
228
+ },
229
+ "shared": {
230
+ "type": "[yes, no, exclusive, force]",
231
+ "help": "Allow shared resources (deprecated, use oversubscribe)",
232
+ },
233
+ "state": {
234
+ "type": "[up, down, drain, inactive]",
235
+ "help": "Partition state",
236
+ },
237
+ }
238
+ value_types = {
239
+ "allowgroups": {"def": "ALL", "flag": False},
240
+ "allowaccounts": {"def": "ALL", "flag": False},
241
+ "allowqos": {"def": "ALL", "flag": False},
242
+ "allocnodes": {"def": "ALL", "flag": False},
243
+ "default": {"def": "NO", "flag": True},
244
+ "defmempernode": {"def": "UNLIMITED", "flag": False},
245
+ "defmempercpu": {"def": "UNLIMITED", "flag": False},
246
+ "qos": {"def": "", "flag": False},
247
+ "disablerootjobs": {"def": "NO", "flag": True},
248
+ "exclusiveuser": {"def": "NO", "flag": True},
249
+ "exclusivetopo": {"def": "NO", "flag": True},
250
+ "gracetime": {"def": "0", "flag": False},
251
+ "hidden": {"def": "NO", "flag": True},
252
+ "maxnodes": {"def": "UNLIMITED", "flag": False},
253
+ "maxtime": {"def": "", "flag": False},
254
+ "minnodes": {"def": "1", "flag": False},
255
+ "lln": {"def": "NO", "flag": True},
256
+ "maxcpuspernode": {"def": "UNLIMITED", "flag": False},
257
+ "maxcpuspersocket": {"def": "UNLIMITED", "flag": False},
258
+ "priorityjobfactor": {"def": "1", "flag": False},
259
+ "prioritytier": {"def": "1", "flag": False},
260
+ "rootonly": {"def": "NO", "flag": True},
261
+ "reqresv": {"def": "NO", "flag": True},
262
+ "oversubscribe": {"def": "NO", "flag": True},
263
+ "overtimelimit": {"def": "NONE", "flag": False},
264
+ "preemptmode": {"def": "OFF", "flag": False},
265
+ "selecttypeparameters": {"def": "NONE", "flag": False},
266
+ "jobdefaults": {"def": "(null)", "flag": False},
267
+ "maxmempernode": {"def": "UNLIMITED", "flag": False},
268
+ "tres": {"def": "", "flag": False},
269
+ "tresbillingweights": {"def": "", "flag": False},
270
+ }
271
+
272
+ def __init__(self, name: "str", **kwargs: Any):
273
+ self.name = name
274
+ self.kwargs = kwargs
275
+
276
+ @classmethod
277
+ def max_width(cls) -> int:
278
+ """Get the maximum width of the console."""
279
+ if cls._WIDTH is None:
280
+ cls._WIDTH = console.width
281
+ return cls._WIDTH
282
+
283
+ @classmethod
284
+ def create(cls, name: str, verbose: bool = False, **kwargs: Any) -> None:
285
+ """Create a new partition."""
286
+ set = {}
287
+ add = {}
288
+ delete = {}
289
+ if not cls._check_args(kwargs, set, add, delete):
290
+ return
291
+ options = " ".join([f"{key}={value}" for key, value in set.items()])
292
+ if len(add) > 0:
293
+ console.print(
294
+ "[yellow]Warning: Adding options is not supported"
295
+ " for partitions.[/yellow]"
296
+ )
297
+ if len(delete) > 0:
298
+ console.print(
299
+ "[yellow]Warning: Deleting options is not supported"
300
+ " for partitions.[/yellow]"
301
+ )
302
+ if len(set) > 0:
303
+ options += " "
304
+ options += " ".join([f"{key}-={value}" for key, value in delete.items()])
305
+ args = [
306
+ "scontrol",
307
+ "create",
308
+ "partition",
309
+ f"name={name}",
310
+ options,
311
+ ]
312
+
313
+ try:
314
+ result = subprocess.run(
315
+ ["echo", *args],
316
+ check=True,
317
+ capture_output=True,
318
+ text=True,
319
+ )
320
+ if result.stdout:
321
+ console.print(result.stdout)
322
+ if verbose:
323
+ console.print(
324
+ f"[green]Partition '{name}' created successfully.[/green]"
325
+ )
326
+
327
+ except subprocess.CalledProcessError as e:
328
+ console.print(
329
+ f"[red]Failed to create partition '{name}':[/red]" f" {e.stderr or e}"
330
+ )
331
+
332
+ @classmethod
333
+ def update(
334
+ cls,
335
+ name: str,
336
+ verbose: bool = False,
337
+ dry_run: bool = False,
338
+ **kwargs: Any,
339
+ ) -> None:
340
+ """Update a partition."""
341
+ set = {}
342
+ add = {}
343
+ delete = {}
344
+ if not cls._check_args(kwargs, set, add, delete):
345
+ return
346
+ options = " ".join([f"{key}={value}" for key, value in set.items()])
347
+ if len(add) > 0:
348
+ options += " "
349
+ options += " ".join([f"{key}+={value}" for key, value in add.items()])
350
+ if len(delete) > 0:
351
+ options += " "
352
+ options += " ".join([f"{key}-={value}" for key, value in delete.items()])
353
+ # console.print(
354
+ # f"Updating partition: {name} with options: {options}"
355
+ # )
356
+ args = [
357
+ "scontrol",
358
+ "update",
359
+ f"partitionname={name}",
360
+ options,
361
+ ]
362
+
363
+ if dry_run:
364
+ console.print(f"[yellow]DRY RUN:[/yellow] {' '.join(args)}")
365
+ return
366
+
367
+ try:
368
+ result = subprocess.run(
369
+ ["echo", *args],
370
+ check=True,
371
+ capture_output=True,
372
+ text=True,
373
+ )
374
+ if result.stdout:
375
+ console.print(result.stdout)
376
+ if verbose:
377
+ console.print(
378
+ f"[green]Partition '{name}' updated successfully.[/green]"
379
+ )
380
+ except subprocess.CalledProcessError as e:
381
+ console.print(
382
+ f"[red]Failed to update partition '{name}':[/red]" f" {e.stderr or e}"
383
+ )
384
+
385
+ @classmethod
386
+ def delete(cls, name: str, verbose: bool = False) -> None:
387
+ """Delete a partition."""
388
+ args = [
389
+ "scontrol",
390
+ "delete",
391
+ f"partitionname={name}",
392
+ ]
393
+ if verbose:
394
+ console.print(f"Running: {' '.join(args)}")
395
+ try:
396
+ result = subprocess.run(
397
+ args,
398
+ check=True,
399
+ capture_output=True,
400
+ text=True,
401
+ )
402
+ if result.stdout:
403
+ console.print(result.stdout)
404
+ console.print(f"[green]Partition '{name}' " "deleted successfully.[/green]")
405
+ except subprocess.CalledProcessError as e:
406
+ console.print(
407
+ f"[red]Failed to delete partition '{name}':[/red]" f" {e.stderr or e}"
408
+ )
409
+
410
+ @classmethod
411
+ def show(
412
+ cls,
413
+ name: Optional[str] = None,
414
+ data: Optional[Dict[str, Any]] = None,
415
+ style: str = "pretty",
416
+ force_cache_update: bool = False,
417
+ delimiter: str = ";",
418
+ profile: str = "default",
419
+ profile_str: Optional[str] = None,
420
+ zebra: bool = False,
421
+ ) -> None:
422
+ """Show partition information."""
423
+ # Get profile configuration
424
+ (
425
+ columns_cfg,
426
+ styles_cfg,
427
+ template_cfg,
428
+ sort_field,
429
+ sort_asc,
430
+ ) = get_profile_config(profile, "partitions", profile_str)
431
+
432
+ if not data:
433
+ console.print("[red]No partitions found.[/red]")
434
+ return
435
+
436
+ # Convert dict to sorted list if sorting is needed
437
+ if sort_field and data and not name:
438
+ items = [{"name": k, **v} for k, v in data.items()]
439
+ items = sort_data(items, sort_field, sort_asc)
440
+ data = {item["name"]: item for item in items}
441
+
442
+ if style == "json":
443
+ if name:
444
+ console.print_json(
445
+ json.dumps(
446
+ data[name],
447
+ indent=4,
448
+ )
449
+ )
450
+ else:
451
+ console.print_json(
452
+ json.dumps(
453
+ data,
454
+ indent=4,
455
+ )
456
+ )
457
+ elif template_cfg and style == "pretty":
458
+ # Use template-based output (e.g., oneline profile)
459
+ partitions_to_show = {name: data[name]} if name and name in data else data
460
+ for part_name, part_data in sorted(partitions_to_show.items()):
461
+ # Prepare data with PartitionName included
462
+ prepared = {"PartitionName": part_name, **part_data}
463
+ output = format_with_template(
464
+ template_cfg, prepared, resource="partitions"
465
+ )
466
+ console.print(output)
467
+ elif columns_cfg and columns_cfg != "*" and style == "pretty":
468
+ # Use column-based table output (e.g., compact, minimal)
469
+ cls.show_columns(name, data, columns_cfg, styles_cfg, zebra) # type: ignore
470
+ elif style == "pretty":
471
+ # Default pretty output
472
+ cls.show_pretty(name, data)
473
+ elif style == "csv":
474
+ cls.show_csv(name, data, delimiter, columns_cfg)
475
+ else:
476
+ console.print(f"[red]Invalid style '{style}'.[/red]")
477
+
478
+ @classmethod
479
+ def show_columns(
480
+ cls,
481
+ name: Optional[str] = None,
482
+ partitions: Optional[dict] = None,
483
+ columns: Optional[Union[list[str], str]] = None,
484
+ styles: Optional[dict] = None,
485
+ zebra: bool = False,
486
+ ) -> None:
487
+ """Show partitions in a column-based table."""
488
+ if not partitions:
489
+ console.print("[red]No partitions found.[/red]")
490
+ return
491
+
492
+ partitions_to_show = (
493
+ {name: partitions[name]} if name and name in partitions else partitions
494
+ )
495
+
496
+ if isinstance(columns, str):
497
+ columns_list = [col.strip() for col in columns.split(",") if col.strip()]
498
+ elif isinstance(columns, list):
499
+ columns_list = columns
500
+ else:
501
+ console.print("[red]Invalid columns format.[/red]")
502
+ return
503
+
504
+ # Create table
505
+ row_styles = ["", "dim"] if zebra else None
506
+ table = Table(
507
+ title="Partitions",
508
+ box=SIMPLE_HEAVY,
509
+ pad_edge=False,
510
+ row_styles=row_styles,
511
+ )
512
+
513
+ # Normalize column names - handle both lowercase and original case
514
+ normalized_columns = []
515
+ for col in columns_list:
516
+ col_lower = col.lower()
517
+ if col_lower in ["name", "partitionname"]:
518
+ normalized_columns.append("PartitionName")
519
+ elif col_lower == "state":
520
+ normalized_columns.append("State")
521
+ elif col_lower == "nodes":
522
+ normalized_columns.append("TotalNodes")
523
+ elif col_lower == "totalnodes":
524
+ normalized_columns.append("TotalNodes")
525
+ elif col_lower == "totalcpus":
526
+ normalized_columns.append("TotalCPUs")
527
+ elif col_lower == "maxtime":
528
+ normalized_columns.append("MaxTime")
529
+ elif col_lower == "defaulttime":
530
+ normalized_columns.append("DefaultTime")
531
+ else:
532
+ # Try to find matching field (case-insensitive)
533
+ for key in next(iter(partitions_to_show.values()), {}).keys():
534
+ if key.lower() == col_lower:
535
+ normalized_columns.append(key)
536
+ break
537
+ else:
538
+ normalized_columns.append(col)
539
+
540
+ # Add columns to table
541
+ styles = styles or {}
542
+ for col in normalized_columns:
543
+ style = styles.get(col.lower(), styles.get("name", "cyan"))
544
+ table.add_column(col, style=style)
545
+
546
+ # Add rows
547
+ for part_name in sorted(partitions_to_show.keys()):
548
+ part_data = partitions_to_show[part_name]
549
+ row = []
550
+ for col in normalized_columns:
551
+ if col == "PartitionName":
552
+ row.append(part_name)
553
+ else:
554
+ row.append(str(part_data.get(col, "")))
555
+ table.add_row(*row)
556
+
557
+ console.print(table)
558
+
559
+ @classmethod
560
+ def show_csv(
561
+ cls,
562
+ name: Optional[str] = None,
563
+ partitions: Optional[dict] = None,
564
+ delimiter: str = ";",
565
+ columns: Optional[Union[list[str], str]] = None,
566
+ ) -> None:
567
+ """Show partition information in CSV format."""
568
+ if not partitions:
569
+ console.print("[red]No partitions found.[/red]")
570
+ return
571
+
572
+ partitions_to_show = (
573
+ {name: partitions[name]} if name and name in partitions else partitions
574
+ )
575
+
576
+ if columns and columns != "*":
577
+ # Use specified columns
578
+ # Normalize column names
579
+ normalized_columns = []
580
+ for col in columns:
581
+ col_lower = col.lower()
582
+ if col_lower in ["name", "partitionname"]:
583
+ normalized_columns.append("PartitionName")
584
+ elif col_lower == "state":
585
+ normalized_columns.append("State")
586
+ elif col_lower == "nodes":
587
+ normalized_columns.append("TotalNodes")
588
+ elif col_lower == "totalnodes":
589
+ normalized_columns.append("TotalNodes")
590
+ elif col_lower == "totalcpus":
591
+ normalized_columns.append("TotalCPUs")
592
+ elif col_lower == "maxtime":
593
+ normalized_columns.append("MaxTime")
594
+ elif col_lower == "defaulttime":
595
+ normalized_columns.append("DefaultTime")
596
+ else:
597
+ # Try to find matching field
598
+ for key in next(iter(partitions_to_show.values()), {}).keys():
599
+ if key.lower() == col_lower:
600
+ normalized_columns.append(key)
601
+ break
602
+ else:
603
+ normalized_columns.append(col)
604
+
605
+ # Print CSV header
606
+ print(delimiter.join(normalized_columns))
607
+
608
+ # Print data rows
609
+ for partition_name in sorted(partitions_to_show.keys()):
610
+ data = partitions_to_show[partition_name]
611
+ row = []
612
+ for col in normalized_columns:
613
+ if col == "PartitionName":
614
+ row.append(partition_name)
615
+ else:
616
+ row.append(str(data.get(col, "")))
617
+ print(delimiter.join(row))
618
+ else:
619
+ # Show all fields
620
+ all_fields = set()
621
+ for partition_data in partitions_to_show.values():
622
+ all_fields.update(partition_data.keys())
623
+
624
+ # Sort fields for consistent output
625
+ priority_fields = [
626
+ "State",
627
+ "TotalNodes",
628
+ "TotalCPUs",
629
+ "MaxTime",
630
+ "DefaultTime",
631
+ ]
632
+ sorted_fields = [f for f in priority_fields if f in all_fields] + sorted(
633
+ [f for f in all_fields if f not in priority_fields]
634
+ )
635
+
636
+ # Print CSV header
637
+ headers = ["PartitionName"] + sorted_fields
638
+ print(delimiter.join(headers))
639
+
640
+ # Print data rows
641
+ for partition_name in sorted(partitions_to_show.keys()):
642
+ data = partitions_to_show[partition_name]
643
+ row = [partition_name] + [
644
+ str(data.get(field, "")) for field in sorted_fields
645
+ ]
646
+ print(delimiter.join(row))
647
+
648
+ @classmethod
649
+ def show_pretty(
650
+ cls, name: Optional[str] = None, partitions: Optional[dict] = None
651
+ ) -> None:
652
+ if not partitions:
653
+ console.print("[red]No partitions found.[/red]")
654
+ return
655
+ if name:
656
+ Partition.show_one_pretty(name, partitions[name])
657
+ else:
658
+ for partition in sorted(partitions.keys()):
659
+ Partition.show_one_pretty(partition, partitions[partition])
660
+
661
+ # @classmethod
662
+ # def show_one(cls, name: str, partitions: dict) -> None:
663
+ # """Show partition information."""
664
+ # if not partitions:
665
+ # console.print("[red]No partitions found.[/red]")
666
+ # return
667
+ # if name:
668
+ # Partition.show_one(name, partitions[name])
669
+ # else:
670
+ # for partition in partitions.keys():
671
+ # Partition.show_one(partition, partitions[partition])
672
+
673
+ @classmethod
674
+ def show_one_pretty(cls, name: str, data: dict[str, Any]) -> None:
675
+ """Show one partition information."""
676
+ states = {
677
+ "UP": "[green]UP [/green]",
678
+ "DRAIN": "[yellow]DRN[/yellow]",
679
+ "INACTIVE": "[blue]INA[/blue]",
680
+ "DOWN": "[red]DWN[/red]",
681
+ }
682
+ width = cls.max_width()
683
+ state = states[data.pop("State")]
684
+ max_time = data.pop("MaxTime")
685
+ def_time = data.pop("DefaultTime")
686
+ total_nodes = data.pop("TotalNodes")
687
+ total_cpus = data.pop("TotalCPUs")
688
+ second_line_len = len(f"Nodes/CPUs: {total_nodes}/{total_cpus} ")
689
+ nodes = (
690
+ data["Nodes"]
691
+ if len(data["Nodes"]) < width - second_line_len - 3
692
+ else data["Nodes"][: (width - second_line_len - 5)] + "..."
693
+ )
694
+ data.pop("Nodes")
695
+ console.print(
696
+ "=============================================\n"
697
+ f"Partition: [object]{escape(name)}[/] {state} "
698
+ f"def/max [time]{def_time}/{max_time}[/]"
699
+ )
700
+ console.print(
701
+ f"Nodes/CPUs: [b]{total_nodes}/{total_cpus}"
702
+ f"[/] ([nodes]{escape(nodes)}[/])"
703
+ )
704
+
705
+ # Check for missing fields and track them
706
+ missing_fields = []
707
+ extended_value_types = dict(cls.value_types)
708
+ for key in data.keys():
709
+ if key.lower() not in cls.value_types:
710
+ missing_fields.append(key)
711
+ # Use default values for missing fields
712
+ extended_value_types[key.lower()] = {
713
+ "def": "",
714
+ "flag": False,
715
+ }
716
+
717
+ flags = {
718
+ key.lower(): value
719
+ for key, value in data.items()
720
+ if extended_value_types[key.lower()]["flag"]
721
+ }
722
+ not_flags = {
723
+ key.lower(): value
724
+ for key, value in data.items()
725
+ if not extended_value_types[key.lower()]["flag"]
726
+ }
727
+ flag_was_printed = cls.print_dict_pretty_flags_def(flags, extended_value_types)
728
+ if flag_was_printed:
729
+ console.print(" ", end="")
730
+ cls.print_dict_pretty_def(not_flags, extended_value_types)
731
+
732
+ # Show warning for missing fields
733
+ if missing_fields:
734
+ console.print(
735
+ f"\n[yellow]Warning: Unknown partition fields "
736
+ f"(using defaults): {', '.join(missing_fields)}[/yellow]"
737
+ )
738
+
739
+ @classmethod
740
+ def generate_autocomplete_options(cls) -> str:
741
+ """Generate bash autocomplete script for partition options."""
742
+ valid_keys = list(cls.valid_args.keys())
743
+ options = " ".join(f"{k}=" for k in valid_keys)
744
+ # Add nodes+= and nodes-= for adding/removing nodes
745
+ options += " nodes+= nodes-="
746
+ state_values = "up down drain inactive UP DOWN DRAIN INACTIVE"
747
+ preempt_values = "off cancel requeue suspend OFF CANCEL REQUEUE SUSPEND"
748
+ yesno_values = "yes no YES NO"
749
+ cpubind_values = "none socket ldom core thread off"
750
+ yesno_keys = (
751
+ "default|disablerootjobs|exclusiveuser|hidden|lln|"
752
+ "oversubscribe|powerdownonidle|reqresv|rootonly|shared"
753
+ )
754
+
755
+ script = f"""
756
+ _slurm_cli_partitions_autocomplete() {{
757
+ local cmd="$1"
758
+ local pos="$2"
759
+
760
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
761
+ local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
762
+
763
+ local cached_partitions="$(_slurm_cache_partitions)"
764
+ local options="{options}"
765
+
766
+ # First argument after 'partitions'
767
+ if [[ $prev == partitions || $prev == part || $prev == parts ]]; then
768
+ case "$cmd" in
769
+ show|delete|update|modify|set) _slurm_complete "$cached_partitions $options" "$cur" ;;
770
+ create|add|new) _slurm_complete "$options" "$cur" ;;
771
+ esac
772
+ return
773
+ fi
774
+
775
+ # Handle key=value completion
776
+ if _slurm_parse_keyval "$cur" "$prev"; then
777
+ # Check if we're in a node filter context by checking COMP_LINE
778
+ local in_node_filter=false
779
+ [[ "$COMP_LINE" == *nodes=state=* || "$COMP_LINE" == *nodes=partition=* || \
780
+ "$COMP_LINE" == *nodes=user=* || "$COMP_LINE" == *nodes=reservation=* || \
781
+ "$COMP_LINE" == *Nodes=state=* || "$COMP_LINE" == *Nodes=partition=* || \
782
+ "$COMP_LINE" == *Nodes=user=* || "$COMP_LINE" == *Nodes=reservation=* || \
783
+ "$COMP_LINE" == *nodes+=state=* || "$COMP_LINE" == *nodes+=partition=* || \
784
+ "$COMP_LINE" == *nodes+=user=* || "$COMP_LINE" == *nodes+=reservation=* || \
785
+ "$COMP_LINE" == *nodes-=state=* || "$COMP_LINE" == *nodes-=partition=* || \
786
+ "$COMP_LINE" == *nodes-=user=* || "$COMP_LINE" == *nodes-=reservation=* ]] && in_node_filter=true
787
+
788
+ case "$_key" in
789
+ state)
790
+ if $in_node_filter; then
791
+ # Node filter: nodes=state=<state>
792
+ local node_states="idle alloc drain down mixed comp"
793
+ COMPREPLY=($(compgen -W "$node_states" -- "$_val"))
794
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=state=}}")
795
+ else
796
+ # Partition state
797
+ _slurm_complete_value "{state_values}" "$_key" "$_val" "$cur"
798
+ fi
799
+ ;;
800
+ preemptmode)
801
+ _slurm_complete_value "{preempt_values}" "$_key" "$_val" "$cur" ;;
802
+ cpubind)
803
+ _slurm_complete_value "{cpubind_values}" "$_key" "$_val" "$cur" ;;
804
+ {yesno_keys})
805
+ _slurm_complete_value "{yesno_values}" "$_key" "$_val" "$cur" ;;
806
+ allowaccounts|denyaccounts)
807
+ _slurm_complete_value "$(_slurm_cache_accounts)" "$_key" "$_val" "$cur" ;;
808
+ allowqos|denyqos|qos)
809
+ _slurm_complete_value "$(_slurm_cache_qos)" "$_key" "$_val" "$cur" ;;
810
+ nodes|nodes+|nodes-)
811
+ _slurm_complete_nodes_value "$_val" "$cur" "$_key" ;;
812
+ alternate|partitionname)
813
+ _slurm_complete_value "$cached_partitions" "$_key" "$_val" "$cur" ;;
814
+ partition)
815
+ # Node filter: nodes=partition=<partition>
816
+ COMPREPLY=($(compgen -W "$cached_partitions" -- "$_val"))
817
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=partition=}}")
818
+ ;;
819
+ user)
820
+ # Node filter: nodes=user=<user>
821
+ COMPREPLY=($(compgen -W "$(_slurm_cache_users)" -- "$_val"))
822
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=user=}}")
823
+ ;;
824
+ reservation)
825
+ # Node filter: nodes=reservation=<reservation>
826
+ COMPREPLY=($(compgen -W "$(_slurm_cache_reservations)" -- "$_val"))
827
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=reservation=}}")
828
+ ;;
829
+ esac
830
+ return
831
+ fi
832
+
833
+ # Complete option names
834
+ _slurm_complete "$options" "$cur"
835
+ }}
836
+ """ # noqa: E501
837
+ return script