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,665 @@
1
+ """Utilities for managing reservations."""
2
+
3
+ import json
4
+ import subprocess
5
+ from datetime import datetime
6
+ from typing import Any, Optional, Union, Dict
7
+
8
+ from rich.markup import escape
9
+
10
+ from .base_resource import BaseSlurmResource
11
+ from .profiles import (
12
+ format_with_template,
13
+ get_profile_config,
14
+ sort_data,
15
+ )
16
+
17
+ # from .resources import Resource
18
+ from .utils import console
19
+
20
+
21
+ class Reservation(BaseSlurmResource):
22
+ _WIDTH = None
23
+
24
+ # Aliases for argument names (short form -> canonical form)
25
+ arg_aliases = {
26
+ "start": "starttime",
27
+ "end": "endtime",
28
+ }
29
+
30
+ @classmethod
31
+ def get_profile_fields(cls) -> dict:
32
+ """Return field names and descriptions for profile templates."""
33
+ return {
34
+ "name": "Reservation name",
35
+ "partition": "Partition name",
36
+ "start_time": "Start time (formatted)",
37
+ "end_time": "End time (formatted)",
38
+ "time_status": "Time status (e.g., 'ends in 5d 3h')",
39
+ "node_count": "Number of nodes",
40
+ "core_count": "Number of cores",
41
+ "node_list": "List of nodes",
42
+ "users": "Allowed users",
43
+ "accounts": "Allowed accounts",
44
+ "flags": "Reservation flags",
45
+ "tres": "TRES specification",
46
+ "max_start_delay": "Max start delay",
47
+ }
48
+
49
+ valid_args = {
50
+ "accounts": {
51
+ "type": "list",
52
+ "help": "Comma-separated list of accounts"
53
+ "that are allowed to use this reservation",
54
+ },
55
+ "burstbuffer": {
56
+ "type": "list",
57
+ "help": "Comma-separated list of burst buffer resources"
58
+ "to be reserved",
59
+ },
60
+ "corecnt": {
61
+ "type": "int",
62
+ "help": "Number of cores to be reserved",
63
+ },
64
+ "licenses": {
65
+ "type": "list",
66
+ "help": "Comma-separated list of licenses" "to be reserved",
67
+ },
68
+ "maxstartdelay": {
69
+ "type": "time",
70
+ "help": "Maximum start delay",
71
+ },
72
+ "nodecnt": {
73
+ "type": "int",
74
+ "help": "Number of nodes to be reserved",
75
+ },
76
+ "nodes": {
77
+ "type": "nodes",
78
+ "help": "Comma-separated list of nodes" "to be reserved",
79
+ },
80
+ "starttime": {
81
+ "type": "time",
82
+ "help": "Start time",
83
+ },
84
+ "endtime": {
85
+ "type": "time",
86
+ "help": "End time",
87
+ },
88
+ "duration": {
89
+ "type": "time",
90
+ "help": "Duration",
91
+ },
92
+ "partitionname": {
93
+ "type": "partition",
94
+ "help": "Partition used to reserve nodes from",
95
+ },
96
+ "flags": {
97
+ "type": "list",
98
+ "help": "Comma-separated list of flags"
99
+ "to be reserved. Flags list: ANY_NODES, "
100
+ "DAILY, FLEX, IGNORE_JOBS, HOURLY, LICENSE_ONLY, "
101
+ "MAINT, MAGNETIC, NO_HOLD_JOBS_AFTER, OVERLAP, "
102
+ "PART_NODES, PURGE_COMP, REPLACE, REPLACE_DOWN, "
103
+ "SPEC_NODES, STATIC_ALLOC, TIME_FLOAT, WEEKDAY, "
104
+ "WEEKEND, WEEKLY",
105
+ },
106
+ "features": {
107
+ "type": "list",
108
+ "help": "Comma-separated list of features" "to be reserved",
109
+ },
110
+ "groups": {
111
+ "type": "list",
112
+ "help": "Comma-separated list of groups" "to be reserved",
113
+ },
114
+ "skip": {
115
+ "type": "[yes, no, y, n, 1, 0]",
116
+ "help": "Skip",
117
+ },
118
+ "users": {
119
+ "type": "list",
120
+ "help": "Comma-separated list of users" "to be reserved",
121
+ },
122
+ "tres": {
123
+ "type": "list",
124
+ "help": "Comma-separated list of TRES" "to be reserved",
125
+ },
126
+ "trespernode": {
127
+ "type": "list",
128
+ "help": "Comma-separated list of TRES per node"
129
+ "to be reserved",
130
+ },
131
+ }
132
+
133
+ def __init__(self, name: str, **kwargs: Any):
134
+ self.name = name
135
+ self.kwargs = kwargs
136
+
137
+ @classmethod
138
+ def max_width(cls) -> int:
139
+ """Get the maximum width of the console."""
140
+ if cls._WIDTH is None:
141
+ cls._WIDTH = console.width
142
+ return cls._WIDTH
143
+
144
+ @classmethod
145
+ def create(
146
+ cls, name: str, verbose: bool = False, **kwargs: Any
147
+ ) -> None:
148
+ """Create a new reservation."""
149
+ set = {}
150
+ add = {}
151
+ delete = {}
152
+ if not cls._check_args(kwargs, set, add, delete):
153
+ return
154
+ options = " ".join(
155
+ [f"{key}={value}" for key, value in set.items()]
156
+ )
157
+ if len(add) > 0:
158
+ console.print(
159
+ "[yellow]Warning: Adding options is not supported"
160
+ " for reservations.[/yellow]"
161
+ )
162
+ if len(delete) > 0:
163
+ console.print(
164
+ "[yellow]Warning: Deleting options is not supported"
165
+ " for reservations.[/yellow]"
166
+ )
167
+ if len(set) > 0:
168
+ options += " "
169
+ options += " ".join(
170
+ [f"{key}-={value}" for key, value in delete.items()]
171
+ )
172
+ args = [
173
+ "scontrol",
174
+ "create",
175
+ "reservation",
176
+ f"name={name}",
177
+ options,
178
+ ]
179
+
180
+ try:
181
+ result = subprocess.run(
182
+ ["echo", *args],
183
+ check=True,
184
+ capture_output=True,
185
+ text=True,
186
+ )
187
+ if result.stdout:
188
+ console.print(result.stdout)
189
+ if verbose:
190
+ console.print(
191
+ f"[green]Reservation '{name}' "
192
+ "created successfully.[/green]"
193
+ )
194
+
195
+ except subprocess.CalledProcessError as e:
196
+ console.print(
197
+ f"[red]Failed to create reservation '{name}':[/red]"
198
+ f" {e.stderr or e}"
199
+ )
200
+
201
+ @classmethod
202
+ def update(
203
+ cls,
204
+ name: str,
205
+ verbose: bool = False,
206
+ dry_run: bool = False,
207
+ **kwargs: Any,
208
+ ) -> None:
209
+ """Update a reservation."""
210
+ set = {}
211
+ add = {}
212
+ delete = {}
213
+ if not cls._check_args(kwargs, set, add, delete):
214
+ return
215
+ options = " ".join(
216
+ [f"{key}={value}" for key, value in set.items()]
217
+ )
218
+ if len(add) > 0:
219
+ options += " "
220
+ options += " ".join(
221
+ [f"{key}+={value}" for key, value in add.items()]
222
+ )
223
+ if len(delete) > 0:
224
+ options += " "
225
+ options += " ".join(
226
+ [f"{key}-={value}" for key, value in delete.items()]
227
+ )
228
+ args = [
229
+ "scontrol",
230
+ "update",
231
+ f"reservationname={name}",
232
+ options,
233
+ ]
234
+
235
+ if dry_run:
236
+ console.print(f"[yellow]DRY RUN:[/yellow] {' '.join(args)}")
237
+ return
238
+
239
+ try:
240
+ result = subprocess.run(
241
+ ["echo", *args],
242
+ check=True,
243
+ capture_output=True,
244
+ text=True,
245
+ )
246
+ if result.stdout:
247
+ console.print(result.stdout)
248
+ if verbose:
249
+ console.print(
250
+ f"[green]Reservation '{name}' "
251
+ "updated successfully.[/green]"
252
+ )
253
+ except subprocess.CalledProcessError as e:
254
+ console.print(
255
+ f"[red]Failed to update reservation '{name}':[/red]"
256
+ f" {e.stderr or e}"
257
+ )
258
+
259
+ @classmethod
260
+ def delete(cls, name: str) -> None:
261
+ """Delete a reservation."""
262
+ args = [
263
+ "scontrol",
264
+ "delete",
265
+ "reservationname={name}",
266
+ ]
267
+ try:
268
+ result = subprocess.run(
269
+ args,
270
+ check=True,
271
+ capture_output=True,
272
+ text=True,
273
+ )
274
+ if result.stdout:
275
+ console.print(result.stdout)
276
+ console.print(
277
+ f"[green]Reservation '{name}' "
278
+ "deleted successfully.[/green]"
279
+ )
280
+ except subprocess.CalledProcessError as e:
281
+ console.print(
282
+ f"[red]Failed to delete reservation '{name}':[/red]"
283
+ f" {e.stderr or e}"
284
+ )
285
+
286
+ @classmethod
287
+ def show(
288
+ cls,
289
+ name: Union[str, None] = None,
290
+ data: Union[Dict[str, Any], None] = None,
291
+ style: str = "pretty",
292
+ delimiter: str = ";",
293
+ zebra: bool = False,
294
+ profile: str = "default",
295
+ profile_str: Optional[str] = None,
296
+ ) -> None:
297
+ """Show reservation information."""
298
+ # Get profile configuration
299
+ _, _, template, sort_field, sort_asc = get_profile_config(
300
+ profile, "reservations", profile_str
301
+ )
302
+ if not data:
303
+ console.print_json("[red]No data available.[/red]")
304
+ return
305
+ if name and name not in data:
306
+ console.print(f"[red]Reservation '{name}' not found.[/red]")
307
+ return
308
+
309
+ # Convert dict to sorted list if sorting is needed
310
+ if sort_field and data and not name:
311
+ items = [{"name": k, **v} for k, v in data.items()]
312
+ items = sort_data(items, sort_field, sort_asc)
313
+ data = {item["name"]: item for item in items}
314
+
315
+ try:
316
+ if style == "json":
317
+ if name:
318
+ console.print_json(json.dumps(data[name], indent=2))
319
+ else:
320
+ console.print_json(json.dumps(data, indent=2))
321
+ elif style == "csv":
322
+ if name:
323
+ data = {name: data[name]}
324
+ cls._show_csv(data, name, delimiter)
325
+ elif template:
326
+ # Use template-based output
327
+ if name:
328
+ res_data = cls._prepare_template_data(
329
+ name, data[name]
330
+ )
331
+ output = format_with_template(
332
+ template, res_data, resource="reservations"
333
+ )
334
+ console.print(output)
335
+ else:
336
+ for res_name, res_data in data.items():
337
+ prepared = cls._prepare_template_data(
338
+ res_name, res_data
339
+ )
340
+ output = format_with_template(
341
+ template, prepared, resource="reservations"
342
+ )
343
+ console.print(output)
344
+ else: # default pretty style
345
+ if name:
346
+ cls.print_one_pretty(name, data[name])
347
+ else:
348
+ for res in data.keys():
349
+ cls.print_one_pretty(res, data[res])
350
+ except subprocess.CalledProcessError as e:
351
+ console.print(
352
+ f"[red]Failed to show reservations:[/red] {e.stderr or e}"
353
+ )
354
+
355
+ @classmethod
356
+ def _prepare_template_data(cls, name: str, data: dict) -> dict:
357
+ """Prepare reservation data for template formatting."""
358
+ result = dict(data)
359
+ result["name"] = name
360
+
361
+ # Format timestamps
362
+ start_time = cls._get_timestamp(data.get("start_time"))
363
+ end_time = cls._get_timestamp(data.get("end_time"))
364
+ result["start_time"] = (
365
+ cls.tm2str(start_time) if start_time else "-"
366
+ )
367
+ result["end_time"] = cls.tm2str(end_time) if end_time else "-"
368
+
369
+ # Calculate deltas
370
+ now = int(datetime.now().timestamp())
371
+ if start_time > now:
372
+ result[
373
+ "time_status"
374
+ ] = f"starts in {cls.delta2str(start_time - now)}"
375
+ elif end_time > now:
376
+ result[
377
+ "time_status"
378
+ ] = f"ends in {cls.delta2str(end_time - now)}"
379
+ else:
380
+ result["time_status"] = "expired"
381
+
382
+ # Format users list
383
+ if "users" in result and isinstance(result["users"], list):
384
+ result["users"] = ",".join(result["users"])
385
+
386
+ # Format accounts list
387
+ if "accounts" in result and isinstance(
388
+ result["accounts"], list
389
+ ):
390
+ result["accounts"] = ",".join(result["accounts"])
391
+
392
+ return result
393
+
394
+ @classmethod
395
+ def _show_csv(
396
+ cls,
397
+ data: dict,
398
+ name: Union[str, None] = None,
399
+ delimiter: str = ";",
400
+ ) -> None:
401
+ """Show reservations in CSV format."""
402
+ # Define columns for CSV output
403
+ columns = [
404
+ "name",
405
+ "partition",
406
+ "start_time",
407
+ "end_time",
408
+ "node_count",
409
+ "core_count",
410
+ "node_list",
411
+ "users",
412
+ "accounts",
413
+ "flags",
414
+ "tres",
415
+ ]
416
+
417
+ # Print header
418
+ print(
419
+ delimiter.join(
420
+ col.title().replace("_", " ") for col in columns
421
+ )
422
+ )
423
+
424
+ # Filter data if name is specified
425
+ items = {name: data[name]} if name else data
426
+
427
+ for res_name, res_data in items.items():
428
+ prepared = cls._prepare_template_data(res_name, res_data)
429
+ row = []
430
+ for col in columns:
431
+ val = prepared.get(col, "")
432
+ if val is None or val == "":
433
+ val = ""
434
+ elif isinstance(val, list):
435
+ val = ",".join(str(v) for v in val)
436
+ elif isinstance(val, dict):
437
+ if val.get("set"):
438
+ val = str(val.get("number", ""))
439
+ else:
440
+ val = ""
441
+ else:
442
+ val = str(val)
443
+ row.append(val)
444
+ print(delimiter.join(row))
445
+
446
+ @classmethod
447
+ def tm2str(cls, tm: int) -> str:
448
+ """Convert time to string."""
449
+ return datetime.fromtimestamp(tm).strftime("%Y-%m-%d %H:%M:%S")
450
+
451
+ @classmethod
452
+ def delta2str(cls, delta: int) -> str:
453
+ """Convert delta to string."""
454
+ days = delta // 86400
455
+ hours = (delta % 86400) // 3600
456
+ minutes = (delta % 3600) // 60
457
+ if days > 0:
458
+ return f"{days}d {hours}h {minutes}m"
459
+ elif hours > 0:
460
+ return f"{hours}h {minutes}m"
461
+ else:
462
+ return f"{minutes}m"
463
+
464
+ @classmethod
465
+ def _get_timestamp(cls, value: Any) -> int:
466
+ """Extract timestamp from value (handles dict with set/number)."""
467
+ if isinstance(value, dict):
468
+ if value.get("set"):
469
+ return int(value.get("number", 0))
470
+ return 0
471
+ return int(value) if value else 0
472
+
473
+ @classmethod
474
+ def print_one_pretty(cls, name: str, data: dict) -> None:
475
+ """Print pretty reservation information."""
476
+ if not data:
477
+ console.print("[red]No data available.[/red]")
478
+ return
479
+ end_time = cls._get_timestamp(data["end_time"])
480
+ start_time = cls._get_timestamp(data["start_time"])
481
+ end_delta = end_time - int(datetime.now().timestamp())
482
+ start_delta = start_time - int(datetime.now().timestamp())
483
+ if start_delta > 0:
484
+ start_str = f"(in [time]{cls.delta2str(start_delta)}[/])"
485
+ end_str = ""
486
+ elif end_delta > 0:
487
+ start_str = ""
488
+ end_str = f"(in [time]{cls.delta2str(end_delta)}[/])"
489
+ else:
490
+ start_str = ""
491
+ end_str = ""
492
+ console.print("=============================================")
493
+ console.print(
494
+ f"Reservation: [object]{escape(name)}[/] Start/End: "
495
+ f"[time]{cls.tm2str(start_time)}[/]{start_str}"
496
+ f" / [time]{cls.tm2str(end_time)}[/]{end_str}"
497
+ )
498
+ console.print(
499
+ f"Partition: [b blue]{escape(data['partition'])}[/] "
500
+ f"Nodes/CPUs: [b]{data['node_count']}/"
501
+ f"{data['core_count']}"
502
+ f"[/] ([nodes]{data['node_list']}[/])"
503
+ )
504
+ data.pop("node_list", None)
505
+ data.pop("partition", None)
506
+ data.pop("core_count", None)
507
+ data.pop("node_count", None)
508
+ data.pop("start_time", None)
509
+ data.pop("end_time", None)
510
+ data.pop("purge_completed", None) # WHAT'S THAT FOR???
511
+ watts = data.pop("watts", None)
512
+ if watts and isinstance(watts, dict) and watts.get("set"):
513
+ data["watts"] = (
514
+ f"[time]{watts['number']}[/]"
515
+ if not watts.get("infinite")
516
+ else "[time]INF[/]"
517
+ )
518
+ elif watts and not isinstance(watts, dict):
519
+ data["watts"] = str(watts)
520
+ # Highlight users in pink
521
+ if "users" in data:
522
+ users_val = data["users"]
523
+ if isinstance(users_val, list):
524
+ users_val = ",".join(users_val)
525
+ data["users"] = f"[hot_pink]{users_val}[/hot_pink]"
526
+ cls.print_dict_pretty(data)
527
+
528
+ @classmethod
529
+ def generate_autocomplete_options(cls) -> str:
530
+ """
531
+ Generate autocomplete for bash completion.
532
+ Assume we already have entered
533
+ "slurm-cli {new|del|upd|show} reservation"
534
+ and we are trying to autocomplete the next command.
535
+
536
+ For each command (new, del, upd, show) generate a list of options
537
+ 1. show:
538
+ - name
539
+ 2. new:
540
+ a. name is not entered:
541
+ - reservationname
542
+ - list of valid_args keys
543
+ b. name is entered:
544
+ I) option name is not entered:
545
+ - list of valid_args keys
546
+ II) option name is entered:
547
+ - list of values,
548
+ depending of type
549
+ format: key=value
550
+ 3. del:
551
+ - name
552
+ 4. upd:
553
+ a. name is not entered:
554
+ - reservationname
555
+ - list of valid_args keys
556
+ b. name is entered:
557
+ I) option name is not entered:
558
+ - list of valid_args keys
559
+ II) option name is entered:
560
+ - list of values,
561
+ depending of type
562
+ format: key=value
563
+ Output should be part of the autocomplete script
564
+ for bash completion.
565
+ For keys with types nodes, partition, account, qos, user
566
+ use jq utility to extract keys from cache files.
567
+ """
568
+
569
+ # Get valid argument keys including aliases
570
+ valid_keys = list(cls.valid_args.keys()) + list(
571
+ cls.arg_aliases.keys()
572
+ )
573
+ # Build types dict including aliases pointing to their canonical types
574
+ valid_types_list = [
575
+ f'[{k}]="{v["type"]}"' for k, v in cls.valid_args.items()
576
+ ]
577
+ # Add alias types (point to same type as canonical)
578
+ for alias, canonical in cls.arg_aliases.items():
579
+ if canonical in cls.valid_args:
580
+ valid_types_list.append(
581
+ f'[{alias}]="{cls.valid_args[canonical]["type"]}"'
582
+ )
583
+ valid_types = " ".join(valid_types_list)
584
+ options = " ".join(f"{k}=" for k in valid_keys)
585
+ # Add nodes+= and nodes-= for adding/removing nodes
586
+ options += " nodes+= nodes-="
587
+ flags = (
588
+ "ANY_NODES DAILY FLEX IGNORE_JOBS HOURLY LICENSE_ONLY MAINT "
589
+ "MAGNETIC NO_HOLD_JOBS_AFTER OVERLAP PART_NODES PURGE_COMP "
590
+ "REPLACE REPLACE_DOWN SPEC_NODES STATIC_ALLOC TIME_FLOAT "
591
+ "WEEKDAY WEEKEND WEEKLY"
592
+ )
593
+
594
+ script = f"""
595
+ _slurm_cli_reservations_autocomplete() {{
596
+ local cmd="$1"
597
+ local pos="$2"
598
+
599
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
600
+ local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
601
+ local name="${{COMP_WORDS[$pos]}}"
602
+
603
+ local cached_reservations="$(_slurm_cache_reservations)"
604
+ local options="{options}"
605
+
606
+ # First argument after 'reservations'
607
+ if [[ $name == reservations && $prev == reservations ]]; then
608
+ _slurm_complete "$cached_reservations" "$cur"
609
+ return
610
+ fi
611
+
612
+ case "$cmd" in
613
+ show|delete) return ;;
614
+ create|update)
615
+ if _slurm_parse_keyval "$cur" "$prev"; then
616
+ local -A valid_types=({valid_types})
617
+ local type=${{valid_types[$_key]}}
618
+ # Handle nodes+ and nodes- specially
619
+ [[ "$_key" == "nodes+" || "$_key" == "nodes-" ]] && type="nodes"
620
+ case "$type" in
621
+ nodes)
622
+ _slurm_complete_nodes_value "$_val" "$cur" "$_key" ;;
623
+ partition)
624
+ _slurm_complete_value "$(_slurm_cache_partitions)" "$_key" "$_val" "$cur" ;;
625
+ account)
626
+ _slurm_complete_value "$(_slurm_cache_accounts)" "$_key" "$_val" "$cur" ;;
627
+ int|time) ;;
628
+ *)
629
+ case "$_key" in
630
+ flags)
631
+ _slurm_complete_value "{flags}" "$_key" "$_val" "$cur" ;;
632
+ skip)
633
+ _slurm_complete_value "yes no y n 1 0" "$_key" "$_val" "$cur" ;;
634
+ state)
635
+ # Node filter: nodes=state=<state>
636
+ local states="idle alloc drain down mixed comp"
637
+ COMPREPLY=($(compgen -W "$states" -- "$_val"))
638
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=state=}}")
639
+ ;;
640
+ partition)
641
+ # Node filter: nodes=partition=<partition>
642
+ COMPREPLY=($(compgen -W "$(_slurm_cache_partitions)" -- "$_val"))
643
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=partition=}}")
644
+ ;;
645
+ user)
646
+ # Node filter: nodes=user=<user>
647
+ COMPREPLY=($(compgen -W "$(_slurm_cache_users)" -- "$_val"))
648
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=user=}}")
649
+ ;;
650
+ reservation)
651
+ # Node filter: nodes=reservation=<reservation>
652
+ COMPREPLY=($(compgen -W "$cached_reservations" -- "$_val"))
653
+ [[ $cur == *=* && ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/nodes=reservation=}}")
654
+ ;;
655
+ esac
656
+ ;;
657
+ esac
658
+ return
659
+ fi
660
+ _slurm_complete "$options" "$cur"
661
+ ;;
662
+ esac
663
+ }}
664
+ """ # noqa: E501
665
+ return script