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,551 @@
1
+ """Job filter utilities for selecting jobs by various criteria.
2
+
3
+ Supports filtering jobs by:
4
+ - user=<username> - jobs by a specific user
5
+ - account=<account> - jobs charged to a specific account
6
+ - partition=<name> - jobs in a specific partition
7
+ - state=<state> - jobs with a specific state
8
+ - name=<pattern> - jobs matching exact name (squeue -n)
9
+ - jobname=<regex> - jobs matching name by regex pattern
10
+ - nodes=<nodelist> - jobs running on specific nodes
11
+ - reservation=<name> - jobs using a specific reservation
12
+
13
+ Exclusion filters (prefix with not:):
14
+ - not:user=<username> - exclude jobs by user
15
+ - not:account=<account> - exclude jobs by account
16
+ - not:partition=<name> - exclude jobs in partition
17
+ - not:state=<state> - exclude jobs with state
18
+ - not:jobname=<regex> - exclude jobs matching name regex
19
+
20
+ Filter syntax can be used in delete and update jobs commands:
21
+ - slurm-cli delete jobs user=john
22
+ - slurm-cli update jobs state=pending priority=100
23
+ - slurm-cli hold partition=gpu not:user=admin
24
+ - slurm-cli hold jobname=test.*
25
+ """
26
+
27
+ import json
28
+ import re
29
+ import subprocess
30
+ from typing import List
31
+
32
+ from .utils import console
33
+
34
+ # Filter prefixes that indicate a job filter expression
35
+ JOB_FILTER_PREFIXES = [
36
+ "user=",
37
+ "account=",
38
+ "partition=",
39
+ "state=",
40
+ "name=",
41
+ "jobname=",
42
+ "nodes=",
43
+ "reservation=",
44
+ ]
45
+
46
+
47
+ def is_job_filter(value: str) -> bool:
48
+ """Check if a value is a job filter expression.
49
+
50
+ Recognizes both positive and negative (not:) filters.
51
+
52
+ Args:
53
+ value: Value to check
54
+
55
+ Returns:
56
+ True if value is a job filter expression
57
+ """
58
+ if not value:
59
+ return False
60
+ value_lower = value.lower()
61
+ # Check for not: prefix
62
+ if value_lower.startswith("not:"):
63
+ value_lower = value_lower[4:]
64
+ return any(value_lower.startswith(p) for p in JOB_FILTER_PREFIXES)
65
+
66
+
67
+ def parse_job_filter(filter_expr: str) -> dict:
68
+ """Parse a job filter expression into key-value pair.
69
+
70
+ Args:
71
+ filter_expr: Filter expression like "user=john"
72
+
73
+ Returns:
74
+ Dict with filter key and value, e.g. {"user": "john"}
75
+ """
76
+ if not filter_expr or "=" not in filter_expr:
77
+ return {}
78
+ key, value = filter_expr.split("=", 1)
79
+ return {key.lower(): value}
80
+
81
+
82
+ def resolve_job_filter(
83
+ filter_expr: str, verbose: bool = False
84
+ ) -> List[str]:
85
+ """Resolve a job filter expression to a list of job IDs.
86
+
87
+ Args:
88
+ filter_expr: Filter expression like "user=john", "state=pending"
89
+ verbose: Print debug information
90
+
91
+ Returns:
92
+ List of job IDs matching the filter
93
+ """
94
+ if not filter_expr:
95
+ return []
96
+
97
+ filter_lower = filter_expr.lower()
98
+
99
+ # Parse filter type and value
100
+ if filter_lower.startswith("user="):
101
+ return _get_jobs_by_user(filter_expr[5:], verbose)
102
+ elif filter_lower.startswith("account="):
103
+ return _get_jobs_by_account(filter_expr[8:], verbose)
104
+ elif filter_lower.startswith("partition="):
105
+ return _get_jobs_by_partition(filter_expr[10:], verbose)
106
+ elif filter_lower.startswith("state="):
107
+ return _get_jobs_by_state(filter_expr[6:], verbose)
108
+ elif filter_lower.startswith("name="):
109
+ return _get_jobs_by_name(filter_expr[5:], verbose)
110
+ elif filter_lower.startswith("jobname="):
111
+ return _get_jobs_by_name_regex(filter_expr[8:], verbose)
112
+ elif filter_lower.startswith("nodes="):
113
+ return _get_jobs_by_nodes(filter_expr[6:], verbose)
114
+ elif filter_lower.startswith("reservation="):
115
+ return _get_jobs_by_reservation(filter_expr[12:], verbose)
116
+ else:
117
+ # Not a filter, assume it's a job ID
118
+ return [filter_expr] if filter_expr.isdigit() else []
119
+
120
+
121
+ def _fetch_all_jobs(verbose: bool = False) -> List[dict]:
122
+ """Fetch all jobs from scontrol."""
123
+ try:
124
+ result = subprocess.run(
125
+ ["scontrol", "show", "job", "--json"],
126
+ capture_output=True,
127
+ text=True,
128
+ check=True,
129
+ errors="replace",
130
+ )
131
+ data = json.loads(result.stdout)
132
+ return data.get("jobs", [])
133
+ except (subprocess.CalledProcessError, json.JSONDecodeError) as e:
134
+ if verbose:
135
+ console.print(f"[red]Failed to fetch jobs: {e}[/red]")
136
+ return []
137
+
138
+
139
+ def _get_jobs_by_user(user: str, verbose: bool = False) -> List[str]:
140
+ """Get job IDs for jobs by a specific user."""
141
+ try:
142
+ # Use squeue for efficiency
143
+ result = subprocess.run(
144
+ ["squeue", "-u", user, "-h", "-o", "%i"],
145
+ capture_output=True,
146
+ text=True,
147
+ check=True,
148
+ errors="replace",
149
+ )
150
+ job_ids = [
151
+ jid.strip()
152
+ for jid in result.stdout.strip().split("\n")
153
+ if jid.strip()
154
+ ]
155
+ if verbose:
156
+ console.print(
157
+ f"[dim]Jobs for user '{user}': {len(job_ids)} found[/dim]"
158
+ )
159
+ return job_ids
160
+ except subprocess.CalledProcessError as e:
161
+ if verbose:
162
+ console.print(
163
+ f"[red]Failed to get jobs by user: {e.stderr}[/red]"
164
+ )
165
+ return []
166
+
167
+
168
+ def _get_jobs_by_account(
169
+ account: str, verbose: bool = False
170
+ ) -> List[str]:
171
+ """Get job IDs for jobs charged to a specific account."""
172
+ try:
173
+ result = subprocess.run(
174
+ ["squeue", "-A", account, "-h", "-o", "%i"],
175
+ capture_output=True,
176
+ text=True,
177
+ check=True,
178
+ errors="replace",
179
+ )
180
+ job_ids = [
181
+ jid.strip()
182
+ for jid in result.stdout.strip().split("\n")
183
+ if jid.strip()
184
+ ]
185
+ if verbose:
186
+ console.print(
187
+ f"[dim]Jobs for account '{account}': "
188
+ f"{len(job_ids)} found[/dim]"
189
+ )
190
+ return job_ids
191
+ except subprocess.CalledProcessError as e:
192
+ if verbose:
193
+ console.print(
194
+ f"[red]Failed to get jobs by account: {e.stderr}[/red]"
195
+ )
196
+ return []
197
+
198
+
199
+ def _get_jobs_by_partition(
200
+ partition: str, verbose: bool = False
201
+ ) -> List[str]:
202
+ """Get job IDs for jobs in a specific partition."""
203
+ try:
204
+ result = subprocess.run(
205
+ ["squeue", "-p", partition, "-h", "-o", "%i"],
206
+ capture_output=True,
207
+ text=True,
208
+ check=True,
209
+ errors="replace",
210
+ )
211
+ job_ids = [
212
+ jid.strip()
213
+ for jid in result.stdout.strip().split("\n")
214
+ if jid.strip()
215
+ ]
216
+ if verbose:
217
+ console.print(
218
+ f"[dim]Jobs in partition '{partition}': "
219
+ f"{len(job_ids)} found[/dim]"
220
+ )
221
+ return job_ids
222
+ except subprocess.CalledProcessError as e:
223
+ if verbose:
224
+ console.print(
225
+ f"[red]Failed to get jobs by partition: {e.stderr}[/red]"
226
+ )
227
+ return []
228
+
229
+
230
+ def _get_jobs_by_state(state: str, verbose: bool = False) -> List[str]:
231
+ """Get job IDs for jobs with a specific state."""
232
+ try:
233
+ result = subprocess.run(
234
+ ["squeue", "-t", state, "-h", "-o", "%i"],
235
+ capture_output=True,
236
+ text=True,
237
+ check=True,
238
+ errors="replace",
239
+ )
240
+ job_ids = [
241
+ jid.strip()
242
+ for jid in result.stdout.strip().split("\n")
243
+ if jid.strip()
244
+ ]
245
+ if verbose:
246
+ console.print(
247
+ f"[dim]Jobs with state '{state}': {len(job_ids)} found[/dim]"
248
+ )
249
+ return job_ids
250
+ except subprocess.CalledProcessError as e:
251
+ if verbose:
252
+ console.print(
253
+ f"[red]Failed to get jobs by state: {e.stderr}[/red]"
254
+ )
255
+ return []
256
+
257
+
258
+ def _get_jobs_by_name(name: str, verbose: bool = False) -> List[str]:
259
+ """Get job IDs for jobs matching a name pattern."""
260
+ try:
261
+ result = subprocess.run(
262
+ ["squeue", "-n", name, "-h", "-o", "%i"],
263
+ capture_output=True,
264
+ text=True,
265
+ check=True,
266
+ errors="replace",
267
+ )
268
+ job_ids = [
269
+ jid.strip()
270
+ for jid in result.stdout.strip().split("\n")
271
+ if jid.strip()
272
+ ]
273
+ if verbose:
274
+ console.print(
275
+ f"[dim]Jobs with name '{name}': {len(job_ids)} found[/dim]"
276
+ )
277
+ return job_ids
278
+ except subprocess.CalledProcessError as e:
279
+ if verbose:
280
+ console.print(
281
+ f"[red]Failed to get jobs by name: {e.stderr}[/red]"
282
+ )
283
+ return []
284
+
285
+
286
+ def _get_jobs_by_name_regex(
287
+ pattern: str, verbose: bool = False
288
+ ) -> List[str]:
289
+ """Get job IDs for jobs with name matching a regex pattern.
290
+
291
+ Args:
292
+ pattern: Regex pattern to match against job names
293
+ verbose: Print debug information
294
+
295
+ Returns:
296
+ List of job IDs with names matching the pattern
297
+ """
298
+ try:
299
+ # Compile regex pattern (case-insensitive)
300
+ try:
301
+ regex = re.compile(pattern, re.IGNORECASE)
302
+ except re.error as e:
303
+ if verbose:
304
+ console.print(
305
+ f"[red]Invalid regex pattern '{pattern}': {e}[/red]"
306
+ )
307
+ return []
308
+
309
+ # Get all jobs with their names
310
+ result = subprocess.run(
311
+ ["squeue", "-h", "-o", "%i %j"],
312
+ capture_output=True,
313
+ text=True,
314
+ check=True,
315
+ errors="replace",
316
+ )
317
+
318
+ job_ids = []
319
+ for line in result.stdout.strip().split("\n"):
320
+ if not line.strip():
321
+ continue
322
+ parts = line.split(maxsplit=1)
323
+ if len(parts) >= 2:
324
+ job_id, job_name = parts[0], parts[1]
325
+ if regex.search(job_name):
326
+ job_ids.append(job_id.strip())
327
+
328
+ if verbose:
329
+ console.print(
330
+ f"[dim]Jobs matching name pattern '{pattern}': "
331
+ f"{len(job_ids)} found[/dim]"
332
+ )
333
+ return job_ids
334
+ except subprocess.CalledProcessError as e:
335
+ if verbose:
336
+ console.print(
337
+ f"[red]Failed to get jobs by name regex: {e.stderr}[/red]"
338
+ )
339
+ return []
340
+
341
+
342
+ def _get_jobs_by_nodes(nodes: str, verbose: bool = False) -> List[str]:
343
+ """Get job IDs for jobs running on specific nodes."""
344
+ try:
345
+ result = subprocess.run(
346
+ ["squeue", "-w", nodes, "-h", "-o", "%i"],
347
+ capture_output=True,
348
+ text=True,
349
+ check=True,
350
+ errors="replace",
351
+ )
352
+ job_ids = [
353
+ jid.strip()
354
+ for jid in result.stdout.strip().split("\n")
355
+ if jid.strip()
356
+ ]
357
+ if verbose:
358
+ console.print(
359
+ f"[dim]Jobs on nodes '{nodes}': {len(job_ids)} found[/dim]"
360
+ )
361
+ return job_ids
362
+ except subprocess.CalledProcessError as e:
363
+ if verbose:
364
+ console.print(
365
+ f"[red]Failed to get jobs by nodes: {e.stderr}[/red]"
366
+ )
367
+ return []
368
+
369
+
370
+ def _get_jobs_by_reservation(
371
+ reservation: str, verbose: bool = False
372
+ ) -> List[str]:
373
+ """Get job IDs for jobs using a specific reservation."""
374
+ try:
375
+ result = subprocess.run(
376
+ ["squeue", "-R", reservation, "-h", "-o", "%i"],
377
+ capture_output=True,
378
+ text=True,
379
+ check=True,
380
+ errors="replace",
381
+ )
382
+ job_ids = [
383
+ jid.strip()
384
+ for jid in result.stdout.strip().split("\n")
385
+ if jid.strip()
386
+ ]
387
+ if verbose:
388
+ console.print(
389
+ f"[dim]Jobs in reservation '{reservation}': "
390
+ f"{len(job_ids)} found[/dim]"
391
+ )
392
+ return job_ids
393
+ except subprocess.CalledProcessError as e:
394
+ if verbose:
395
+ console.print(
396
+ f"[red]Failed to get jobs by reservation: {e.stderr}[/red]"
397
+ )
398
+ return []
399
+
400
+
401
+ def _get_all_jobs(verbose: bool = False) -> List[str]:
402
+ """Get all job IDs from the queue."""
403
+ try:
404
+ result = subprocess.run(
405
+ ["squeue", "-h", "-o", "%i"],
406
+ capture_output=True,
407
+ text=True,
408
+ check=True,
409
+ errors="replace",
410
+ )
411
+ job_ids = [
412
+ jid.strip()
413
+ for jid in result.stdout.strip().split("\n")
414
+ if jid.strip()
415
+ ]
416
+ if verbose:
417
+ console.print(f"[dim]All jobs: {len(job_ids)} found[/dim]")
418
+ return job_ids
419
+ except subprocess.CalledProcessError as e:
420
+ if verbose:
421
+ console.print(
422
+ f"[red]Failed to get all jobs: {e.stderr}[/red]"
423
+ )
424
+ return []
425
+
426
+
427
+ def resolve_job_filters(
428
+ args: List[str], verbose: bool = False
429
+ ) -> tuple[set, List[str]]:
430
+ """Resolve a list of job arguments with inclusion/exclusion support.
431
+
432
+ Handles positive filters, negative filters (not:prefix),
433
+ and direct job IDs.
434
+ Returns a set of job IDs after applying all filters.
435
+
436
+ Args:
437
+ args: List of job IDs or filter expressions
438
+ verbose: Print debug information
439
+
440
+ Returns:
441
+ Tuple of (job_ids_set, other_args) where:
442
+ - job_ids_set: Set of resolved job IDs after exclusions
443
+ - other_args: List of args that are not job IDs or filters
444
+ """
445
+ included_jobs: set = set()
446
+ excluded_jobs: set = set()
447
+ other_args: List[str] = []
448
+ has_positive_filter = False
449
+
450
+ for arg in args:
451
+ if not arg:
452
+ continue
453
+
454
+ arg_lower = arg.lower()
455
+
456
+ # Check for not: prefix (exclusion)
457
+ if arg_lower.startswith("not:"):
458
+ filter_part = arg[4:] # Remove "not:" prefix
459
+ if is_job_filter(filter_part):
460
+ resolved = resolve_job_filter(filter_part, verbose)
461
+ excluded_jobs.update(resolved)
462
+ if verbose:
463
+ console.print(
464
+ f"[dim]Excluding {len(resolved)} jobs "
465
+ f"from filter: {filter_part}[/dim]"
466
+ )
467
+ else:
468
+ other_args.append(arg)
469
+ elif is_job_filter(arg):
470
+ # Positive filter
471
+ has_positive_filter = True
472
+ resolved = resolve_job_filter(arg, verbose)
473
+ included_jobs.update(resolved)
474
+ if verbose:
475
+ console.print(
476
+ f"[dim]Including {len(resolved)} jobs "
477
+ f"from filter: {arg}[/dim]"
478
+ )
479
+ elif arg.isdigit() or "_" in arg:
480
+ # Direct job ID (may include array job IDs like 123_4)
481
+ has_positive_filter = True
482
+ included_jobs.add(arg)
483
+ else:
484
+ other_args.append(arg)
485
+
486
+ # If only exclusions specified, start with all jobs
487
+ if not has_positive_filter and excluded_jobs:
488
+ all_jobs = _get_all_jobs(verbose)
489
+ included_jobs = set(all_jobs)
490
+ if verbose:
491
+ console.print(
492
+ f"[dim]Starting with all {len(included_jobs)} jobs[/dim]"
493
+ )
494
+
495
+ # Apply exclusions
496
+ final_jobs = included_jobs - excluded_jobs
497
+
498
+ if verbose and excluded_jobs:
499
+ console.print(
500
+ f"[dim]After exclusions: {len(final_jobs)} jobs[/dim]"
501
+ )
502
+
503
+ return final_jobs, other_args
504
+
505
+
506
+ def resolve_job_ids(
507
+ args: List[str], verbose: bool = False
508
+ ) -> tuple[List[str], List[str]]:
509
+ """Resolve a list of job IDs and filters to job IDs.
510
+
511
+ Note: This function is kept for backward compatibility with scancel.
512
+ For job control commands that need exclusion support,
513
+ use resolve_job_filters.
514
+
515
+ Args:
516
+ args: List of job IDs or filter expressions
517
+ verbose: Print debug information
518
+
519
+ Returns:
520
+ Tuple of (job_ids, user_filters) where:
521
+ - job_ids: List of resolved job IDs
522
+ - user_filters: List of user= filters (for scancel -u optimization)
523
+ """
524
+ job_ids = []
525
+ user_filters = []
526
+
527
+ for arg in args:
528
+ if not arg:
529
+ continue
530
+ arg_lower = arg.lower()
531
+
532
+ # Special handling for user= filter (can use scancel -u)
533
+ if arg_lower.startswith("user="):
534
+ user_filters.append(arg[5:])
535
+ elif is_job_filter(arg):
536
+ # Resolve filter to job IDs
537
+ resolved = resolve_job_filter(arg, verbose)
538
+ job_ids.extend(resolved)
539
+ elif arg.isdigit() or "_" in arg:
540
+ # Direct job ID (may include array job IDs like 123_4)
541
+ job_ids.append(arg)
542
+
543
+ # Remove duplicates while preserving order
544
+ seen = set()
545
+ unique_job_ids = []
546
+ for jid in job_ids:
547
+ if jid not in seen:
548
+ seen.add(jid)
549
+ unique_job_ids.append(jid)
550
+
551
+ return unique_job_ids, user_filters