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,778 @@
1
+ """Node filter utilities for selecting nodes by various criteria.
2
+
3
+ Supports filtering nodes by:
4
+ - partition=<name> - nodes from a specific partition
5
+ - state=<state> - nodes with a specific state
6
+ - user=<username> - nodes running jobs by a specific user
7
+ - reservation=<name> - nodes in a specific reservation
8
+ - drainreason=<regex> - nodes with drain reason matching regex pattern
9
+
10
+ Prefix with 'not:' to exclude nodes matching the filter:
11
+ - not:partition=<name> - exclude nodes from a specific partition
12
+ - not:state=<state> - exclude nodes with a specific state
13
+ - not:user=<username> - exclude nodes running jobs by a specific user
14
+ - not:reservation=<name> - exclude nodes in a specific reservation
15
+ - not:drainreason=<regex> - exclude nodes with reason matching regex
16
+
17
+ Filter syntax can be used anywhere node names are expected, e.g.:
18
+ - slurm-cli update reservations test nodes=partition=cpu
19
+ - slurm-cli update nodes state=drain partition=gpu
20
+ - slurm-cli drain partition=gpu not:reservation=maint
21
+ - slurm-cli drain drainreason="Not responding"
22
+ """
23
+
24
+ import json
25
+ import re
26
+ import subprocess
27
+ from typing import List, Optional, Set, Tuple
28
+
29
+ from .utils import console
30
+
31
+ # Filter prefixes that indicate a node filter expression
32
+ NODE_FILTER_PREFIXES = [
33
+ "partition=",
34
+ "state=",
35
+ "user=",
36
+ "reservation=",
37
+ "drain=",
38
+ "drainreason=",
39
+ ]
40
+
41
+ # Available node states for completion
42
+ NODE_STATES = [
43
+ "idle",
44
+ "alloc",
45
+ "drain",
46
+ "down",
47
+ "mixed",
48
+ "comp",
49
+ ]
50
+
51
+
52
+ def is_node_filter(value: str) -> bool:
53
+ """Check if a value is a node filter expression or special keyword.
54
+
55
+ Recognizes both positive filters (partition=gpu) and negative/exclusion
56
+ filters (not:partition=gpu). Uses 'not:' prefix to avoid conflicts with
57
+ CLI option parsing (-) and bash tilde expansion (~).
58
+ """
59
+ if not value:
60
+ return False
61
+ value_lower = value.lower()
62
+ # Check for ALL keyword
63
+ if value_lower == "all":
64
+ return True
65
+ # Handle negative filter prefix (not:)
66
+ if value_lower.startswith("not:"):
67
+ value_lower = value_lower[4:]
68
+ return any(value_lower.startswith(p) for p in NODE_FILTER_PREFIXES)
69
+
70
+
71
+ def resolve_node_filter(
72
+ filter_expr: str, verbose: bool = False
73
+ ) -> Optional[str]:
74
+ """Resolve a node filter expression to a comma-separated list of nodes.
75
+
76
+ Args:
77
+ filter_expr: Filter expression like "partition=cpu", "state=idle",
78
+ or "ALL" for all nodes
79
+ verbose: Print debug information
80
+
81
+ Returns:
82
+ Comma-separated list of node names, or None if no nodes match
83
+ """
84
+ if not filter_expr:
85
+ return None
86
+
87
+ filter_lower = filter_expr.lower()
88
+
89
+ # Handle ALL keyword - return "ALL" as-is (Slurm understands it)
90
+ if filter_lower == "all":
91
+ if verbose:
92
+ console.print("[dim]Using ALL nodes[/dim]")
93
+ return "ALL"
94
+
95
+ # Parse filter type and value
96
+ if filter_lower.startswith("partition="):
97
+ return _get_nodes_by_partition(filter_expr[10:], verbose)
98
+ elif filter_lower.startswith("state="):
99
+ return _get_nodes_by_state(filter_expr[6:], verbose)
100
+ elif filter_lower.startswith("user="):
101
+ return _get_nodes_by_user(filter_expr[5:], verbose)
102
+ elif filter_lower.startswith("reservation="):
103
+ return _get_nodes_by_reservation(filter_expr[12:], verbose)
104
+ elif filter_lower.startswith("drain="):
105
+ return _get_nodes_by_reason(filter_expr[6:], verbose)
106
+ elif filter_lower.startswith("drainreason="):
107
+ return _get_nodes_by_reason(filter_expr[12:], verbose)
108
+ else:
109
+ # Not a filter, return as-is
110
+ return filter_expr
111
+
112
+
113
+ def _get_nodes_by_partition(
114
+ partition: str, verbose: bool = False
115
+ ) -> str:
116
+ """Get nodes belonging to a specific partition."""
117
+ try:
118
+ result = subprocess.run(
119
+ ["scontrol", "show", "partition", partition, "--json"],
120
+ capture_output=True,
121
+ text=True,
122
+ check=True,
123
+ )
124
+ data = json.loads(result.stdout)
125
+ partitions = data.get("partitions", [])
126
+ if not partitions:
127
+ if verbose:
128
+ console.print(
129
+ f"[yellow]No partition '{partition}' found[/yellow]"
130
+ )
131
+ return ""
132
+
133
+ # Get nodes from partition
134
+ nodes = partitions[0].get("nodes", {})
135
+ if isinstance(nodes, dict):
136
+ # Handle structured node format
137
+ node_list = nodes.get("nodes", "")
138
+ else:
139
+ node_list = nodes
140
+
141
+ if verbose:
142
+ console.print(
143
+ f"[dim]Nodes from partition '{partition}': {node_list}[/dim]"
144
+ )
145
+ return node_list
146
+ except subprocess.CalledProcessError as e:
147
+ if verbose:
148
+ console.print(
149
+ f"[red]Failed to get nodes from partition: {e.stderr}[/red]"
150
+ )
151
+ return ""
152
+ except json.JSONDecodeError:
153
+ # Try non-JSON fallback
154
+ return _get_nodes_by_partition_text(partition, verbose)
155
+
156
+
157
+ def _get_nodes_by_partition_text(
158
+ partition: str, verbose: bool = False
159
+ ) -> str:
160
+ """Get nodes from partition using text output (fallback)."""
161
+ try:
162
+ result = subprocess.run(
163
+ ["sinfo", "-p", partition, "-h", "-o", "%N"],
164
+ capture_output=True,
165
+ text=True,
166
+ check=True,
167
+ )
168
+ nodes = result.stdout.strip()
169
+ if verbose:
170
+ console.print(
171
+ f"[dim]Nodes from partition '{partition}': {nodes}[/dim]"
172
+ )
173
+ return nodes
174
+ except subprocess.CalledProcessError:
175
+ return ""
176
+
177
+
178
+ def _get_nodes_by_state(state: str, verbose: bool = False) -> str:
179
+ """Get nodes with a specific state."""
180
+ try:
181
+ # Use scontrol with JSON for reliable parsing
182
+ result = subprocess.run(
183
+ ["scontrol", "show", "nodes", "--json"],
184
+ capture_output=True,
185
+ text=True,
186
+ check=True,
187
+ )
188
+ data = json.loads(result.stdout)
189
+ state_lower = state.lower()
190
+ node_set = set()
191
+ for node in data.get("nodes", []):
192
+ node_state = node.get("state", [])
193
+ # state can be a list like ["IDLE"] or ["ALLOCATED", "DRAIN"]
194
+ if isinstance(node_state, list):
195
+ state_strs = [s.lower() for s in node_state]
196
+ else:
197
+ state_strs = [str(node_state).lower()]
198
+ # Match if any state component matches
199
+ for s in state_strs:
200
+ if state_lower in s or s.startswith(state_lower):
201
+ node_set.add(node.get("name", ""))
202
+ break
203
+ nodes = ",".join(sorted(node_set))
204
+ if verbose:
205
+ console.print(
206
+ f"[dim]Nodes with state '{state}': {nodes}[/dim]"
207
+ )
208
+ return nodes
209
+ except subprocess.CalledProcessError as e:
210
+ if verbose:
211
+ console.print(
212
+ f"[red]Failed to get nodes by state: {e.stderr}[/red]"
213
+ )
214
+ return ""
215
+ except json.JSONDecodeError:
216
+ return _get_nodes_by_state_text(state, verbose)
217
+
218
+
219
+ def _get_nodes_by_state_text(state: str, verbose: bool = False) -> str:
220
+ """Get nodes by state using text output (fallback)."""
221
+ try:
222
+ result = subprocess.run(
223
+ ["sinfo", "-t", state, "-h", "-N", "-o", "%N"],
224
+ capture_output=True,
225
+ text=True,
226
+ check=True,
227
+ )
228
+ node_set = set()
229
+ for line in result.stdout.strip().split("\n"):
230
+ if line.strip():
231
+ node_set.add(line.strip())
232
+ nodes = ",".join(sorted(node_set))
233
+ if verbose:
234
+ console.print(
235
+ f"[dim]Nodes with state '{state}': {nodes}[/dim]"
236
+ )
237
+ return nodes
238
+ except subprocess.CalledProcessError:
239
+ return ""
240
+
241
+
242
+ def _get_nodes_by_user(user: str, verbose: bool = False) -> str:
243
+ """Get nodes running jobs by a specific user."""
244
+ try:
245
+ # Use JSON output for reliable parsing
246
+ result = subprocess.run(
247
+ ["squeue", "-u", user, "--json"],
248
+ capture_output=True,
249
+ text=True,
250
+ check=True,
251
+ )
252
+ data = json.loads(result.stdout)
253
+ # Collect unique nodes from all jobs
254
+ node_set = set()
255
+ for job in data.get("jobs", []):
256
+ nodes = job.get("nodes", "")
257
+ if isinstance(nodes, str) and nodes:
258
+ # Handle comma-separated nodes or ranges
259
+ for node in nodes.split(","):
260
+ if node.strip():
261
+ node_set.add(node.strip())
262
+
263
+ nodes = ",".join(sorted(node_set))
264
+ if verbose:
265
+ console.print(
266
+ f"[dim]Nodes used by user '{user}': {nodes}[/dim]"
267
+ )
268
+ return nodes
269
+ except subprocess.CalledProcessError as e:
270
+ if verbose:
271
+ console.print(
272
+ f"[red]Failed to get nodes by user: {e.stderr}[/red]"
273
+ )
274
+ return ""
275
+ except json.JSONDecodeError:
276
+ # Fallback to text parsing
277
+ return _get_nodes_by_user_text(user, verbose)
278
+
279
+
280
+ def _get_nodes_by_user_text(user: str, verbose: bool = False) -> str:
281
+ """Get nodes by user using text output (fallback)."""
282
+ try:
283
+ result = subprocess.run(
284
+ ["squeue", "-u", user, "-h", "-o", "%N"],
285
+ capture_output=True,
286
+ text=True,
287
+ check=True,
288
+ )
289
+ node_set = set()
290
+ for line in result.stdout.strip().split("\n"):
291
+ if line.strip():
292
+ node_set.add(line.strip())
293
+
294
+ nodes = ",".join(sorted(node_set))
295
+ if verbose:
296
+ console.print(
297
+ f"[dim]Nodes used by user '{user}': {nodes}[/dim]"
298
+ )
299
+ return nodes
300
+ except subprocess.CalledProcessError:
301
+ return ""
302
+
303
+
304
+ def _get_nodes_by_reservation(
305
+ reservation: str, verbose: bool = False
306
+ ) -> str:
307
+ """Get nodes in a specific reservation."""
308
+ try:
309
+ result = subprocess.run(
310
+ ["scontrol", "show", "reservation", reservation, "--json"],
311
+ capture_output=True,
312
+ text=True,
313
+ check=True,
314
+ )
315
+ data = json.loads(result.stdout)
316
+ reservations = data.get("reservations", [])
317
+ if not reservations:
318
+ if verbose:
319
+ console.print(
320
+ f"[yellow]No reservation '{reservation}' found[/yellow]"
321
+ )
322
+ return ""
323
+
324
+ nodes = reservations[0].get("node_list", "")
325
+ if verbose:
326
+ console.print(
327
+ f"[dim]Nodes in reservation '{reservation}': {nodes}[/dim]"
328
+ )
329
+ return nodes
330
+ except subprocess.CalledProcessError as e:
331
+ if verbose:
332
+ console.print(
333
+ f"[red]Failed to get reservation nodes: {e.stderr}[/red]"
334
+ )
335
+ return ""
336
+ except json.JSONDecodeError:
337
+ return _get_nodes_by_reservation_text(reservation, verbose)
338
+
339
+
340
+ def _get_nodes_by_reservation_text(
341
+ reservation: str, verbose: bool = False
342
+ ) -> str:
343
+ """Get nodes from reservation using text output (fallback)."""
344
+ try:
345
+ result = subprocess.run(
346
+ ["scontrol", "show", "reservation", reservation],
347
+ capture_output=True,
348
+ text=True,
349
+ check=True,
350
+ )
351
+ # Parse Nodes= from output
352
+ for line in result.stdout.split("\n"):
353
+ if "Nodes=" in line:
354
+ parts = line.split()
355
+ for part in parts:
356
+ if part.startswith("Nodes="):
357
+ nodes = part[6:]
358
+ if verbose:
359
+ console.print(
360
+ f"[dim]Nodes in reservation "
361
+ f"'{reservation}': {nodes}[/dim]"
362
+ )
363
+ return nodes
364
+ return ""
365
+ except subprocess.CalledProcessError:
366
+ return ""
367
+
368
+
369
+ def _get_nodes_by_reason(
370
+ reason_pattern: str, verbose: bool = False
371
+ ) -> str:
372
+ """Get nodes with reason matching a regex pattern.
373
+
374
+ Args:
375
+ reason_pattern: Regex pattern to match against node reason
376
+ verbose: Print debug information
377
+
378
+ Returns:
379
+ Comma-separated list of matching node names
380
+ """
381
+ try:
382
+ # Use scontrol with JSON for reliable parsing
383
+ result = subprocess.run(
384
+ ["scontrol", "show", "nodes", "--json"],
385
+ capture_output=True,
386
+ text=True,
387
+ check=True,
388
+ )
389
+ data = json.loads(result.stdout)
390
+ try:
391
+ pattern = re.compile(reason_pattern, re.IGNORECASE)
392
+ except re.error as e:
393
+ if verbose:
394
+ console.print(
395
+ f"[red]Invalid regex pattern '{reason_pattern}': "
396
+ f"{e}[/red]"
397
+ )
398
+ return ""
399
+
400
+ node_set = set()
401
+ for node in data.get("nodes", []):
402
+ reason = node.get("reason", "")
403
+ if reason and pattern.search(reason):
404
+ node_set.add(node.get("name", ""))
405
+
406
+ nodes = ",".join(sorted(node_set))
407
+ if verbose:
408
+ console.print(
409
+ f"[dim]Nodes matching reason '{reason_pattern}': "
410
+ f"{nodes}[/dim]"
411
+ )
412
+ return nodes
413
+ except subprocess.CalledProcessError as e:
414
+ if verbose:
415
+ console.print(
416
+ f"[red]Failed to get nodes by reason: {e.stderr}[/red]"
417
+ )
418
+ return ""
419
+ except json.JSONDecodeError:
420
+ return _get_nodes_by_reason_text(reason_pattern, verbose)
421
+
422
+
423
+ def _get_nodes_by_reason_text(
424
+ reason_pattern: str, verbose: bool = False
425
+ ) -> str:
426
+ """Get nodes by reason using text output (fallback)."""
427
+ try:
428
+ result = subprocess.run(
429
+ ["scontrol", "show", "nodes"],
430
+ capture_output=True,
431
+ text=True,
432
+ check=True,
433
+ )
434
+ try:
435
+ pattern = re.compile(reason_pattern, re.IGNORECASE)
436
+ except re.error:
437
+ return ""
438
+
439
+ node_set = set()
440
+ current_node = None
441
+ for line in result.stdout.split("\n"):
442
+ if line.startswith("NodeName="):
443
+ # Extract node name
444
+ parts = line.split()
445
+ for part in parts:
446
+ if part.startswith("NodeName="):
447
+ current_node = part[9:]
448
+ break
449
+ if "Reason=" in line and current_node:
450
+ # Extract reason
451
+ idx = line.find("Reason=")
452
+ if idx >= 0:
453
+ reason = line[idx + 7 :].strip()
454
+ if pattern.search(reason):
455
+ node_set.add(current_node)
456
+
457
+ nodes = ",".join(sorted(node_set))
458
+ if verbose:
459
+ console.print(
460
+ f"[dim]Nodes matching reason '{reason_pattern}': "
461
+ f"{nodes}[/dim]"
462
+ )
463
+ return nodes
464
+ except subprocess.CalledProcessError:
465
+ return ""
466
+
467
+
468
+ def resolve_nodes_value(value: str, verbose: bool = False) -> str:
469
+ """Resolve a nodes value, handling both direct names and filters.
470
+
471
+ Args:
472
+ value: Node specification (names, range, or filter expression)
473
+ verbose: Print debug information
474
+
475
+ Returns:
476
+ Resolved node specification (names or range)
477
+ """
478
+ if is_node_filter(value):
479
+ resolved = resolve_node_filter(value, verbose)
480
+ if not resolved:
481
+ console.print(
482
+ f"[yellow]Warning: No nodes matched filter '{value}'[/yellow]"
483
+ )
484
+ return ""
485
+ return resolved
486
+ return value
487
+
488
+
489
+ def _get_all_nodes(verbose: bool = False) -> Set[str]:
490
+ """Get all nodes in the cluster."""
491
+ try:
492
+ result = subprocess.run(
493
+ ["scontrol", "show", "nodes", "--json"],
494
+ capture_output=True,
495
+ text=True,
496
+ check=True,
497
+ )
498
+ data = json.loads(result.stdout)
499
+ nodes = {node.get("name", "") for node in data.get("nodes", [])}
500
+ nodes.discard("")
501
+ return nodes
502
+ except (subprocess.CalledProcessError, json.JSONDecodeError):
503
+ return set()
504
+
505
+
506
+ # Expand Slurm-style node list with ranges
507
+ def _expand_range(expr: str) -> Set[str]:
508
+ """Expand a Slurm range expression like [001-003,005]
509
+ to a list of strings.
510
+
511
+ Args:
512
+ expr: Slurm range expression like "001-003,005"
513
+
514
+ Returns:
515
+ Set of node names
516
+ """
517
+ result = set()
518
+ # e.g., expr = "001-003,005"
519
+ for part in expr.split(","):
520
+ part = part.strip()
521
+ if "-" in part:
522
+ start, end = part.split("-", 1)
523
+ # Keep the original width for leading zeros
524
+ width = max(len(start), len(end))
525
+ try:
526
+ for i in range(int(start), int(end) + 1):
527
+ result.add(str(i).zfill(width))
528
+ except ValueError:
529
+ result.add(part) # If badly formatted, keep as is
530
+ elif part:
531
+ result.add(part)
532
+ return result
533
+
534
+
535
+ def _split_hostlist(node_str: str) -> List[str]:
536
+ """Split a hostlist by commas, respecting brackets.
537
+
538
+ E.g., "node[1-3,5],foo[2-4]" -> ["node[1-3,5]", "foo[2-4]"]
539
+ """
540
+ segments = []
541
+ current = []
542
+ depth = 0
543
+ for char in node_str:
544
+ if char == "[":
545
+ depth += 1
546
+ current.append(char)
547
+ elif char == "]":
548
+ depth -= 1
549
+ current.append(char)
550
+ elif char == "," and depth == 0:
551
+ segment = "".join(current).strip()
552
+ if segment:
553
+ segments.append(segment)
554
+ current = []
555
+ else:
556
+ current.append(char)
557
+ # Don't forget the last segment
558
+ segment = "".join(current).strip()
559
+ if segment:
560
+ segments.append(segment)
561
+ return segments
562
+
563
+
564
+ def _expand_node_list(node_str: str) -> Set[str]:
565
+ """Expand a comma-separated node list or range to a set of nodes.
566
+
567
+ Handles Slurm hostlist format like:
568
+ - "node[10-14,19],node[20,22,25-27]"
569
+ - "gpu-node[001-004],cpu-node[1-3]"
570
+ """
571
+ if not node_str:
572
+ return set()
573
+
574
+ # Simple case: no brackets or commas, just return as-is
575
+ if "[" not in node_str and "," not in node_str:
576
+ return {node_str}
577
+
578
+ # Parse hostlist like "node[001-004,007],foo1,foo[2-3]"
579
+ node_names = set()
580
+ pattern = re.compile(r"^([^\[]+)\[(.+)\]$")
581
+ # ^ matches "prefix[ranges]"
582
+
583
+ for segment in _split_hostlist(node_str):
584
+ segment = segment.strip()
585
+ if not segment:
586
+ continue
587
+ m = pattern.match(segment)
588
+ if m:
589
+ prefix = m.group(1)
590
+ ranges = m.group(2)
591
+ for suffix in _expand_range(ranges):
592
+ node_names.add(f"{prefix}{suffix}")
593
+ else:
594
+ # No brackets, just a plain node name
595
+ node_names.add(segment)
596
+
597
+ return node_names
598
+
599
+
600
+ def resolve_node_filters(
601
+ args: List[str], verbose: bool = False
602
+ ) -> Tuple[Set[str], List[str]]:
603
+ """Resolve multiple node filters including exclusions.
604
+
605
+ Handles:
606
+ - Direct node names/ranges
607
+ - Positive filters (partition=gpu, state=idle, etc.) - INTERSECTED
608
+ - Negative filters (not:partition=gpu, not:state=drain, etc.)
609
+
610
+ Multiple positive filters are INTERSECTED (AND logic):
611
+ partition=gpu state=drain -> nodes that are in gpu AND drained
612
+
613
+ Args:
614
+ args: List of node specs and filters
615
+ verbose: Print debug information
616
+
617
+ Returns:
618
+ Tuple of (resolved node set, list of unrecognized args)
619
+ """
620
+ # List of filter results to intersect
621
+ include_filters: List[Set[str]] = []
622
+ exclude_nodes: Set[str] = set()
623
+ other_args: List[str] = []
624
+ direct_nodes: Set[str] = set()
625
+
626
+ for arg in args:
627
+ if not arg:
628
+ continue
629
+
630
+ # Check for negative/exclusion filter (not: prefix)
631
+ if arg.lower().startswith("not:") and is_node_filter(arg):
632
+ # Negative filter: not:partition=gpu, not:state=drain, etc.
633
+ filter_expr = arg[4:] # Remove leading 'not:'
634
+ resolved = resolve_node_filter(filter_expr, verbose)
635
+ if resolved and resolved != "ALL":
636
+ exclude_nodes.update(_expand_node_list(resolved))
637
+ if verbose:
638
+ console.print(
639
+ f"[dim]Excluding nodes from '{filter_expr}': "
640
+ f"{len(exclude_nodes)} nodes[/dim]"
641
+ )
642
+ elif is_node_filter(arg):
643
+ # Positive filter - add to list for intersection
644
+ if arg.lower() == "all":
645
+ include_filters.append(_get_all_nodes(verbose))
646
+ else:
647
+ resolved = resolve_node_filter(arg, verbose)
648
+ if resolved and resolved != "ALL":
649
+ include_filters.append(_expand_node_list(resolved))
650
+ elif resolved == "ALL":
651
+ include_filters.append(_get_all_nodes(verbose))
652
+ elif "=" not in arg and not arg.lower().startswith("not:"):
653
+ # Direct node name or range
654
+ direct_nodes.update(_expand_node_list(arg))
655
+ else:
656
+ # Not a node filter, pass through
657
+ other_args.append(arg)
658
+
659
+ # Build result from filters
660
+ if include_filters:
661
+ # Intersect all positive filters (AND logic)
662
+ include_nodes = include_filters[0]
663
+ for filter_set in include_filters[1:]:
664
+ include_nodes = include_nodes & filter_set
665
+ # Add any direct nodes
666
+ if direct_nodes:
667
+ include_nodes = include_nodes | direct_nodes
668
+ elif direct_nodes:
669
+ # Only direct nodes
670
+ include_nodes = direct_nodes
671
+ elif exclude_nodes:
672
+ # Only exclusions, start with all nodes
673
+ include_nodes = _get_all_nodes(verbose)
674
+ else:
675
+ # No filters at all
676
+ include_nodes = set()
677
+
678
+ # Apply exclusions
679
+ result_nodes = include_nodes - exclude_nodes
680
+
681
+ if verbose and exclude_nodes:
682
+ console.print(
683
+ f"[dim]After exclusions: {len(result_nodes)} nodes[/dim]"
684
+ )
685
+
686
+ return result_nodes, other_args
687
+
688
+
689
+ def generate_node_filter_autocomplete() -> str:
690
+ """Generate bash autocomplete script for node filters.
691
+
692
+ Returns:
693
+ Bash script fragment for node filter completion
694
+ """
695
+ states = " ".join(NODE_STATES)
696
+ filters = " ".join(NODE_FILTER_PREFIXES)
697
+ neg_filters = " ".join(f"not:{p}" for p in NODE_FILTER_PREFIXES)
698
+
699
+ return f"""
700
+ # Node filter completion helper
701
+ _slurm_complete_node_filter() {{
702
+ local cur="$1"
703
+ local prev="$2"
704
+ local cached_nodes="$(_slurm_cache_nodes)"
705
+ local cached_partitions="$(_slurm_cache_partitions)"
706
+ local node_filters="{filters}"
707
+ local neg_filters="{neg_filters}"
708
+ local node_states="{states}"
709
+
710
+ # Handle negative filters (not: prefix)
711
+ if [[ "$cur" == not:partition=* ]]; then
712
+ local val="${{cur#not:partition=}}"
713
+ COMPREPLY=($(compgen -W "$cached_partitions" -- "$val"))
714
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/not:partition=}}")
715
+ return 0
716
+ elif [[ "$cur" == not:state=* ]]; then
717
+ local val="${{cur#not:state=}}"
718
+ COMPREPLY=($(compgen -W "$node_states" -- "$val"))
719
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/not:state=}}")
720
+ return 0
721
+ elif [[ "$cur" == not:user=* ]]; then
722
+ local val="${{cur#not:user=}}"
723
+ local users="$(_slurm_cache_users)"
724
+ COMPREPLY=($(compgen -W "$users" -- "$val"))
725
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/not:user=}}")
726
+ return 0
727
+ elif [[ "$cur" == not:reservation=* ]]; then
728
+ local val="${{cur#not:reservation=}}"
729
+ local reservations="$(_slurm_cache_reservations)"
730
+ COMPREPLY=($(compgen -W "$reservations" -- "$val"))
731
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && COMPREPLY=("${{COMPREPLY[@]/#/not:reservation=}}")
732
+ return 0
733
+ elif [[ "$cur" == not:drain=* ]]; then
734
+ COMPREPLY=("not:drain=REGEXP")
735
+ return 0
736
+ elif [[ "$cur" == not:drainreason=* ]]; then
737
+ COMPREPLY=("not:drainreason=REGEXP")
738
+ return 0
739
+ # Handle positive filters
740
+ elif [[ "$cur" == partition=* ]] || [[ "$prev" == "=" && "${{COMP_WORDS[COMP_CWORD-2]}}" == "partition" ]]; then
741
+ local val="${{cur#partition=}}"
742
+ [[ "$prev" == "=" ]] && val="$cur"
743
+ COMPREPLY=($(compgen -W "$cached_partitions" -- "$val"))
744
+ [[ ${{#COMPREPLY[@]}} -gt 0 && "$cur" == *=* ]] && COMPREPLY=("${{COMPREPLY[@]/#/partition=}}")
745
+ return 0
746
+ elif [[ "$cur" == state=* ]] || [[ "$prev" == "=" && "${{COMP_WORDS[COMP_CWORD-2]}}" == "state" ]]; then
747
+ local val="${{cur#state=}}"
748
+ [[ "$prev" == "=" ]] && val="$cur"
749
+ COMPREPLY=($(compgen -W "$node_states" -- "$val"))
750
+ [[ ${{#COMPREPLY[@]}} -gt 0 && "$cur" == *=* ]] && COMPREPLY=("${{COMPREPLY[@]/#/state=}}")
751
+ return 0
752
+ elif [[ "$cur" == user=* ]] || [[ "$prev" == "=" && "${{COMP_WORDS[COMP_CWORD-2]}}" == "user" ]]; then
753
+ local val="${{cur#user=}}"
754
+ [[ "$prev" == "=" ]] && val="$cur"
755
+ local users="$(_slurm_cache_users)"
756
+ COMPREPLY=($(compgen -W "$users" -- "$val"))
757
+ [[ ${{#COMPREPLY[@]}} -gt 0 && "$cur" == *=* ]] && COMPREPLY=("${{COMPREPLY[@]/#/user=}}")
758
+ return 0
759
+ elif [[ "$cur" == reservation=* ]] || [[ "$prev" == "=" && "${{COMP_WORDS[COMP_CWORD-2]}}" == "reservation" ]]; then
760
+ local val="${{cur#reservation=}}"
761
+ [[ "$prev" == "=" ]] && val="$cur"
762
+ local reservations="$(_slurm_cache_reservations)"
763
+ COMPREPLY=($(compgen -W "$reservations" -- "$val"))
764
+ [[ ${{#COMPREPLY[@]}} -gt 0 && "$cur" == *=* ]] && COMPREPLY=("${{COMPREPLY[@]/#/reservation=}}")
765
+ return 0
766
+ elif [[ "$cur" == drain=* ]]; then
767
+ COMPREPLY=("drain=REGEXP")
768
+ return 0
769
+ elif [[ "$cur" == drainreason=* ]]; then
770
+ COMPREPLY=("drainreason=REGEXP")
771
+ return 0
772
+ fi
773
+
774
+ # Default: show nodes and filter options
775
+ COMPREPLY=($(compgen -W "$cached_nodes $node_filters $neg_filters" -- "$cur"))
776
+ return 0
777
+ }}
778
+ """ # noqa: E501