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.
- slurm_cli/__init__.py +17 -0
- slurm_cli/cli.py +5113 -0
- slurm_cli/py.typed +0 -0
- slurm_cli/utils/__init__.py +1 -0
- slurm_cli/utils/accounts.py +544 -0
- slurm_cli/utils/associations.py +871 -0
- slurm_cli/utils/autocomplete_helpers.py +266 -0
- slurm_cli/utils/base_resource.py +349 -0
- slurm_cli/utils/config.py +88 -0
- slurm_cli/utils/coordinators.py +426 -0
- slurm_cli/utils/events.py +695 -0
- slurm_cli/utils/job_filter.py +551 -0
- slurm_cli/utils/jobs.py +854 -0
- slurm_cli/utils/node_filter.py +778 -0
- slurm_cli/utils/nodes.py +774 -0
- slurm_cli/utils/partitions.py +837 -0
- slurm_cli/utils/prefix_utils.py +1050 -0
- slurm_cli/utils/profiles.py +1360 -0
- slurm_cli/utils/qos.py +883 -0
- slurm_cli/utils/reservations.py +665 -0
- slurm_cli/utils/resources.py +341 -0
- slurm_cli/utils/slurm_config.py +73 -0
- slurm_cli/utils/users.py +649 -0
- slurm_cli/utils/utils.py +21 -0
- slurm_cli-1.0.0.dist-info/METADATA +216 -0
- slurm_cli-1.0.0.dist-info/RECORD +29 -0
- slurm_cli-1.0.0.dist-info/WHEEL +4 -0
- slurm_cli-1.0.0.dist-info/entry_points.txt +3 -0
- slurm_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
"""Utilities for managing Slurm events."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
from typing import Any, Dict, List, Optional, Union
|
|
8
|
+
|
|
9
|
+
from rich.box import (
|
|
10
|
+
SIMPLE_HEAVY,
|
|
11
|
+
) # pyright: ignore[reportMissingImports]
|
|
12
|
+
from rich.table import Table # pyright: ignore[reportMissingImports]
|
|
13
|
+
|
|
14
|
+
from .base_resource import BaseSlurmResource
|
|
15
|
+
from .node_filter import is_node_filter, resolve_node_filter
|
|
16
|
+
from .profiles import get_profile_config, sort_data
|
|
17
|
+
from .utils import console
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def expand_node_ranges(node_spec: str) -> set:
|
|
21
|
+
"""Expand Slurm node range notation to individual node names.
|
|
22
|
+
|
|
23
|
+
Examples:
|
|
24
|
+
"node[1-3]" -> {"node1", "node2", "node3"}
|
|
25
|
+
"node1,node2" -> {"node1", "node2"}
|
|
26
|
+
"a[1-2],b[1-2]" -> {"a1", "a2", "b1", "b2"}
|
|
27
|
+
"""
|
|
28
|
+
nodes = set()
|
|
29
|
+
for part in node_spec.split(","):
|
|
30
|
+
part = part.strip()
|
|
31
|
+
if not part:
|
|
32
|
+
continue
|
|
33
|
+
# Check for range notation like node[1-3] or node[01-03]
|
|
34
|
+
match = re.match(r"^(.+?)\[([^\]]+)\](.*)$", part)
|
|
35
|
+
if match:
|
|
36
|
+
prefix, ranges, suffix = match.groups()
|
|
37
|
+
for range_part in ranges.split(","):
|
|
38
|
+
if "-" in range_part:
|
|
39
|
+
start, end = range_part.split("-", 1)
|
|
40
|
+
# Preserve leading zeros
|
|
41
|
+
width = len(start)
|
|
42
|
+
for i in range(int(start), int(end) + 1):
|
|
43
|
+
nodes.add(
|
|
44
|
+
f"{prefix}{str(i).zfill(width)}{suffix}"
|
|
45
|
+
)
|
|
46
|
+
else:
|
|
47
|
+
nodes.add(f"{prefix}{range_part}{suffix}")
|
|
48
|
+
else:
|
|
49
|
+
nodes.add(part)
|
|
50
|
+
return nodes
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Cache file paths
|
|
54
|
+
CACHE_DIR = "/tmp/"
|
|
55
|
+
EVENTS_CACHE_FILE = f"{CACHE_DIR}slurm_cli_events.txt"
|
|
56
|
+
EVENTS_JSON_CACHE_FILE = f"{CACHE_DIR}slurm_cli_events.json"
|
|
57
|
+
# Flag file to indicate JSON format is not supported
|
|
58
|
+
EVENTS_NO_JSON_FLAG = f"{CACHE_DIR}.slurm_cli_events_no_json"
|
|
59
|
+
|
|
60
|
+
# Event filter options
|
|
61
|
+
EVENT_FILTER_OPTIONS: List[str] = [
|
|
62
|
+
"Clusters",
|
|
63
|
+
"CondFlags",
|
|
64
|
+
"End",
|
|
65
|
+
"Events",
|
|
66
|
+
"MaxCPUs",
|
|
67
|
+
"MinCPUs",
|
|
68
|
+
"MaxNodes",
|
|
69
|
+
"MinNodes",
|
|
70
|
+
"Nodes",
|
|
71
|
+
"Reason",
|
|
72
|
+
"Start",
|
|
73
|
+
"States",
|
|
74
|
+
"User",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
# Column mapping from sacctmgr output to our field names
|
|
78
|
+
COLUMN_MAPPING = {
|
|
79
|
+
"Cluster": "cluster",
|
|
80
|
+
"Cluster Nodes": "cluster_nodes",
|
|
81
|
+
"Duration": "duration",
|
|
82
|
+
"TimeStart": "start",
|
|
83
|
+
"TimeEnd": "end",
|
|
84
|
+
"Event": "event",
|
|
85
|
+
"EventRaw": "event_raw",
|
|
86
|
+
"NodeName": "node",
|
|
87
|
+
"State": "state",
|
|
88
|
+
"StateRaw": "state_raw",
|
|
89
|
+
"TRES": "tres",
|
|
90
|
+
"User": "user",
|
|
91
|
+
"Reason": "reason",
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Event(BaseSlurmResource):
|
|
96
|
+
"""Slurm event resource handler."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, **kwargs: Any):
|
|
99
|
+
self.kwargs = kwargs
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def get_profile_fields(cls) -> dict:
|
|
103
|
+
"""Return field names and descriptions for profile templates."""
|
|
104
|
+
return {
|
|
105
|
+
"cluster": "Cluster name",
|
|
106
|
+
"cluster_nodes": "Nodes in cluster at time of event",
|
|
107
|
+
"duration": "Event duration",
|
|
108
|
+
"start": "Event start time",
|
|
109
|
+
"end": "Event end time",
|
|
110
|
+
"event": "Event type (Cluster or Node)",
|
|
111
|
+
"event_raw": "Raw event code",
|
|
112
|
+
"node": "Node name affected",
|
|
113
|
+
"state": "Node state",
|
|
114
|
+
"state_raw": "Raw state code",
|
|
115
|
+
"tres": "Trackable resources",
|
|
116
|
+
"user": "User who triggered event",
|
|
117
|
+
"reason": "Event reason",
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
# All available columns
|
|
121
|
+
ALL_COLUMNS = [
|
|
122
|
+
"cluster",
|
|
123
|
+
"cluster_nodes",
|
|
124
|
+
"duration",
|
|
125
|
+
"start",
|
|
126
|
+
"end",
|
|
127
|
+
"event",
|
|
128
|
+
"event_raw",
|
|
129
|
+
"node",
|
|
130
|
+
"state",
|
|
131
|
+
"state_raw",
|
|
132
|
+
"tres",
|
|
133
|
+
"user",
|
|
134
|
+
"reason",
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
# Default column configuration for events
|
|
138
|
+
DEFAULT_COLUMNS = [
|
|
139
|
+
"node",
|
|
140
|
+
"state",
|
|
141
|
+
"start",
|
|
142
|
+
"end",
|
|
143
|
+
"duration",
|
|
144
|
+
"user",
|
|
145
|
+
"reason",
|
|
146
|
+
]
|
|
147
|
+
DEFAULT_STYLES = {
|
|
148
|
+
"cluster": "cyan",
|
|
149
|
+
"cluster_nodes": "dim",
|
|
150
|
+
"duration": "yellow",
|
|
151
|
+
"start": "green",
|
|
152
|
+
"end": "green",
|
|
153
|
+
"event": "magenta",
|
|
154
|
+
"event_raw": "dim",
|
|
155
|
+
"node": "cyan bold",
|
|
156
|
+
"state": "yellow",
|
|
157
|
+
"state_raw": "dim",
|
|
158
|
+
"tres": "dim",
|
|
159
|
+
"user": "blue",
|
|
160
|
+
"reason": "white",
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def _parse_events(cls, data: str) -> List[Dict[str, Any]]:
|
|
165
|
+
"""Parse pipe-delimited event data into list of dicts."""
|
|
166
|
+
events = []
|
|
167
|
+
lines = data.strip().split("\n")
|
|
168
|
+
|
|
169
|
+
if not lines:
|
|
170
|
+
return events
|
|
171
|
+
|
|
172
|
+
# First line is header
|
|
173
|
+
header = lines[0].split("|")
|
|
174
|
+
# Map header names to our field names
|
|
175
|
+
field_names = []
|
|
176
|
+
for col in header:
|
|
177
|
+
col = col.strip()
|
|
178
|
+
field_names.append(COLUMN_MAPPING.get(col, col.lower()))
|
|
179
|
+
|
|
180
|
+
# Parse data lines
|
|
181
|
+
for line in lines[1:]:
|
|
182
|
+
if not line.strip():
|
|
183
|
+
continue
|
|
184
|
+
values = line.split("|")
|
|
185
|
+
event = {}
|
|
186
|
+
for i, value in enumerate(values):
|
|
187
|
+
if i < len(field_names):
|
|
188
|
+
event[field_names[i]] = value.strip()
|
|
189
|
+
if event:
|
|
190
|
+
events.append(event)
|
|
191
|
+
|
|
192
|
+
return events
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def _extract_cpus(cls, tres: str) -> int:
|
|
196
|
+
"""Extract CPU count from TRES string."""
|
|
197
|
+
if not tres:
|
|
198
|
+
return 0
|
|
199
|
+
match = re.search(r"cpu=(\d+)", tres)
|
|
200
|
+
return int(match.group(1)) if match else 0
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def _extract_nodes(cls, tres: str) -> int:
|
|
204
|
+
"""Extract node count from TRES string."""
|
|
205
|
+
if not tres:
|
|
206
|
+
return 0
|
|
207
|
+
match = re.search(r"node=(\d+)", tres)
|
|
208
|
+
return int(match.group(1)) if match else 0
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def _apply_filters(
|
|
212
|
+
cls,
|
|
213
|
+
events: List[Dict[str, Any]],
|
|
214
|
+
filters: Dict[str, str],
|
|
215
|
+
) -> List[Dict[str, Any]]:
|
|
216
|
+
"""Apply filters to event list."""
|
|
217
|
+
result = events
|
|
218
|
+
|
|
219
|
+
for key, value in filters.items():
|
|
220
|
+
key_lower = key.lower()
|
|
221
|
+
|
|
222
|
+
if key_lower == "clusters":
|
|
223
|
+
result = [
|
|
224
|
+
e
|
|
225
|
+
for e in result
|
|
226
|
+
if e.get("cluster", "").lower() == value.lower()
|
|
227
|
+
]
|
|
228
|
+
elif key_lower == "events":
|
|
229
|
+
result = [
|
|
230
|
+
e
|
|
231
|
+
for e in result
|
|
232
|
+
if e.get("event", "").lower() == value.lower()
|
|
233
|
+
]
|
|
234
|
+
elif key_lower == "nodes":
|
|
235
|
+
# Check if filter contains node ranges or multiple nodes
|
|
236
|
+
if "[" in value and "]" in value:
|
|
237
|
+
# Expand node ranges to individual names for matching
|
|
238
|
+
filter_nodes = expand_node_ranges(value.lower())
|
|
239
|
+
result = [
|
|
240
|
+
e
|
|
241
|
+
for e in result
|
|
242
|
+
if e.get("node", "").lower() in filter_nodes
|
|
243
|
+
]
|
|
244
|
+
elif "," in value:
|
|
245
|
+
# Multiple comma-separated nodes (from resolved filter)
|
|
246
|
+
filter_nodes = {
|
|
247
|
+
n.strip().lower() for n in value.split(",")
|
|
248
|
+
}
|
|
249
|
+
result = [
|
|
250
|
+
e
|
|
251
|
+
for e in result
|
|
252
|
+
if e.get("node", "").lower() in filter_nodes
|
|
253
|
+
]
|
|
254
|
+
else:
|
|
255
|
+
# Simple substring match for partial names
|
|
256
|
+
result = [
|
|
257
|
+
e
|
|
258
|
+
for e in result
|
|
259
|
+
if value.lower() in e.get("node", "").lower()
|
|
260
|
+
]
|
|
261
|
+
elif key_lower == "states":
|
|
262
|
+
result = [
|
|
263
|
+
e
|
|
264
|
+
for e in result
|
|
265
|
+
if value.lower() in e.get("state", "").lower()
|
|
266
|
+
]
|
|
267
|
+
elif key_lower == "user":
|
|
268
|
+
result = [
|
|
269
|
+
e
|
|
270
|
+
for e in result
|
|
271
|
+
if value.lower() in e.get("user", "").lower()
|
|
272
|
+
]
|
|
273
|
+
elif key_lower == "reason":
|
|
274
|
+
result = [
|
|
275
|
+
e
|
|
276
|
+
for e in result
|
|
277
|
+
if value.lower() in e.get("reason", "").lower()
|
|
278
|
+
]
|
|
279
|
+
elif key_lower == "mincpus":
|
|
280
|
+
min_cpus = int(value)
|
|
281
|
+
result = [
|
|
282
|
+
e
|
|
283
|
+
for e in result
|
|
284
|
+
if cls._extract_cpus(e.get("tres", "")) >= min_cpus
|
|
285
|
+
]
|
|
286
|
+
elif key_lower == "maxcpus":
|
|
287
|
+
max_cpus = int(value)
|
|
288
|
+
result = [
|
|
289
|
+
e
|
|
290
|
+
for e in result
|
|
291
|
+
if cls._extract_cpus(e.get("tres", "")) <= max_cpus
|
|
292
|
+
]
|
|
293
|
+
elif key_lower == "minnodes":
|
|
294
|
+
min_nodes = int(value)
|
|
295
|
+
result = [
|
|
296
|
+
e
|
|
297
|
+
for e in result
|
|
298
|
+
if cls._extract_nodes(e.get("tres", ""))
|
|
299
|
+
>= min_nodes
|
|
300
|
+
]
|
|
301
|
+
elif key_lower == "maxnodes":
|
|
302
|
+
max_nodes = int(value)
|
|
303
|
+
result = [
|
|
304
|
+
e
|
|
305
|
+
for e in result
|
|
306
|
+
if cls._extract_nodes(e.get("tres", ""))
|
|
307
|
+
<= max_nodes
|
|
308
|
+
]
|
|
309
|
+
# Start and End filters would need date parsing - simplified here
|
|
310
|
+
elif key_lower == "start":
|
|
311
|
+
result = [
|
|
312
|
+
e for e in result if value in e.get("start", "")
|
|
313
|
+
]
|
|
314
|
+
elif key_lower == "end":
|
|
315
|
+
result = [
|
|
316
|
+
e for e in result if value in e.get("end", "")
|
|
317
|
+
]
|
|
318
|
+
|
|
319
|
+
return result
|
|
320
|
+
|
|
321
|
+
@classmethod
|
|
322
|
+
def _format_value(
|
|
323
|
+
cls, event: Dict[str, Any], column: str, truncate: bool = True
|
|
324
|
+
) -> str:
|
|
325
|
+
"""Format a value for display.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
event: Event dictionary
|
|
329
|
+
column: Column name
|
|
330
|
+
truncate: Whether to truncate long values (for pretty output)
|
|
331
|
+
"""
|
|
332
|
+
value = event.get(column, "")
|
|
333
|
+
if value is None or value == "":
|
|
334
|
+
return "-"
|
|
335
|
+
# Truncate long values only for pretty output
|
|
336
|
+
if truncate:
|
|
337
|
+
if column == "reason" and len(str(value)) > 60:
|
|
338
|
+
return str(value)[:57] + "..."
|
|
339
|
+
if column == "cluster_nodes" and len(str(value)) > 40:
|
|
340
|
+
return str(value)[:37] + "..."
|
|
341
|
+
if column == "tres" and len(str(value)) > 50:
|
|
342
|
+
return str(value)[:47] + "..."
|
|
343
|
+
return str(value)
|
|
344
|
+
|
|
345
|
+
@classmethod
|
|
346
|
+
def _get_sacctmgr_command(
|
|
347
|
+
cls, filters: Union[Dict[str, str], None] = None, use_json: bool = False
|
|
348
|
+
) -> List[str]:
|
|
349
|
+
"""Build sacctmgr command with filters."""
|
|
350
|
+
cmd = ["sacctmgr", "list", "event"]
|
|
351
|
+
|
|
352
|
+
if use_json:
|
|
353
|
+
cmd.append("--json")
|
|
354
|
+
else:
|
|
355
|
+
cmd.extend(
|
|
356
|
+
[
|
|
357
|
+
"format=Cluster,ClusterNodes,Duration,Start,End,"
|
|
358
|
+
"Event,EventRaw,NodeName,State,StateRaw,TRES,User,Reason",
|
|
359
|
+
"-p",
|
|
360
|
+
]
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
if filters:
|
|
364
|
+
for key, value in filters.items():
|
|
365
|
+
# These are sacctmgr-level filters
|
|
366
|
+
if key.lower() in [
|
|
367
|
+
"clusters",
|
|
368
|
+
"condflags",
|
|
369
|
+
"end",
|
|
370
|
+
"events",
|
|
371
|
+
"nodes",
|
|
372
|
+
"reason",
|
|
373
|
+
"start",
|
|
374
|
+
"states",
|
|
375
|
+
"user",
|
|
376
|
+
]:
|
|
377
|
+
cmd.append(f"{key}={value}")
|
|
378
|
+
|
|
379
|
+
return cmd
|
|
380
|
+
|
|
381
|
+
@classmethod
|
|
382
|
+
def _parse_json_events(cls, data: str) -> List[Dict[str, Any]]:
|
|
383
|
+
"""Parse JSON event data into list of dicts."""
|
|
384
|
+
try:
|
|
385
|
+
parsed = json.loads(data)
|
|
386
|
+
events = parsed.get("events", [])
|
|
387
|
+
# Normalize field names to match our internal format
|
|
388
|
+
normalized = []
|
|
389
|
+
for event in events:
|
|
390
|
+
norm_event = {}
|
|
391
|
+
for key, value in event.items():
|
|
392
|
+
# Map JSON keys to our field names
|
|
393
|
+
mapped_key = COLUMN_MAPPING.get(key, key.lower())
|
|
394
|
+
norm_event[mapped_key] = value
|
|
395
|
+
normalized.append(norm_event)
|
|
396
|
+
return normalized
|
|
397
|
+
except json.JSONDecodeError:
|
|
398
|
+
return []
|
|
399
|
+
|
|
400
|
+
@classmethod
|
|
401
|
+
def _fetch_events(
|
|
402
|
+
cls, filters: Union[Dict[str, str], None] = None
|
|
403
|
+
) -> List[Dict[str, Any]]:
|
|
404
|
+
"""Fetch events with JSON fallback to text format.
|
|
405
|
+
|
|
406
|
+
Tries JSON format first. If it fails or returns invalid JSON,
|
|
407
|
+
sets a flag file and uses text format instead.
|
|
408
|
+
"""
|
|
409
|
+
# Check if we already know JSON doesn't work
|
|
410
|
+
use_json = not os.path.exists(EVENTS_NO_JSON_FLAG)
|
|
411
|
+
|
|
412
|
+
if use_json:
|
|
413
|
+
try:
|
|
414
|
+
cmd = cls._get_sacctmgr_command(filters, use_json=True)
|
|
415
|
+
result = subprocess.run(
|
|
416
|
+
cmd,
|
|
417
|
+
check=True,
|
|
418
|
+
capture_output=True,
|
|
419
|
+
text=True,
|
|
420
|
+
errors="replace", # Handle invalid UTF-8 bytes
|
|
421
|
+
)
|
|
422
|
+
events = cls._parse_json_events(result.stdout)
|
|
423
|
+
if events or not result.stdout.strip():
|
|
424
|
+
# JSON worked (either got events or empty result)
|
|
425
|
+
return events
|
|
426
|
+
# Got output but couldn't parse as JSON - set flag
|
|
427
|
+
with open(EVENTS_NO_JSON_FLAG, "w") as f:
|
|
428
|
+
f.write(
|
|
429
|
+
"JSON format not supported by this Slurm version"
|
|
430
|
+
)
|
|
431
|
+
except (
|
|
432
|
+
subprocess.CalledProcessError,
|
|
433
|
+
json.JSONDecodeError,
|
|
434
|
+
):
|
|
435
|
+
# JSON failed - set flag and fall through to text format
|
|
436
|
+
with open(EVENTS_NO_JSON_FLAG, "w") as f:
|
|
437
|
+
f.write(
|
|
438
|
+
"JSON format not supported by this Slurm version"
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
# Use text format
|
|
442
|
+
cmd = cls._get_sacctmgr_command(filters, use_json=False)
|
|
443
|
+
result = subprocess.run(
|
|
444
|
+
cmd,
|
|
445
|
+
check=True,
|
|
446
|
+
capture_output=True,
|
|
447
|
+
text=True,
|
|
448
|
+
errors="replace", # Handle invalid UTF-8 bytes
|
|
449
|
+
)
|
|
450
|
+
return cls._parse_events(result.stdout)
|
|
451
|
+
|
|
452
|
+
@classmethod
|
|
453
|
+
def show(
|
|
454
|
+
cls,
|
|
455
|
+
field: Union[str, None] = None,
|
|
456
|
+
style: str = "pretty",
|
|
457
|
+
force_cache_update: bool = False,
|
|
458
|
+
delimiter: str = ";",
|
|
459
|
+
zebra: bool = False,
|
|
460
|
+
profile: str = "default",
|
|
461
|
+
profile_str: Optional[str] = None,
|
|
462
|
+
) -> None:
|
|
463
|
+
"""Show event information.
|
|
464
|
+
|
|
465
|
+
Args:
|
|
466
|
+
field: Optional filter (e.g., Nodes=h100-pool0-0290)
|
|
467
|
+
style: Output style ("pretty", "json", or "csv")
|
|
468
|
+
force_cache_update: Whether to force cache update
|
|
469
|
+
delimiter: Delimiter for CSV output (default: ";")
|
|
470
|
+
zebra: Use zebra striping for table rows
|
|
471
|
+
profile: Profile name to use for output formatting
|
|
472
|
+
profile_str: Inline profile string (overrides profile)
|
|
473
|
+
"""
|
|
474
|
+
# Get profile configuration
|
|
475
|
+
(
|
|
476
|
+
columns,
|
|
477
|
+
styles,
|
|
478
|
+
template,
|
|
479
|
+
sort_field,
|
|
480
|
+
sort_asc,
|
|
481
|
+
) = get_profile_config(profile, "events", profile_str)
|
|
482
|
+
|
|
483
|
+
# Use default columns if not specified, or all columns if "*"
|
|
484
|
+
if columns == "*":
|
|
485
|
+
columns = cls.ALL_COLUMNS
|
|
486
|
+
elif columns is None:
|
|
487
|
+
columns = cls.DEFAULT_COLUMNS
|
|
488
|
+
|
|
489
|
+
# Merge with default styles
|
|
490
|
+
merged_styles = dict(cls.DEFAULT_STYLES)
|
|
491
|
+
if styles:
|
|
492
|
+
merged_styles.update(styles)
|
|
493
|
+
|
|
494
|
+
# Parse filters from field argument
|
|
495
|
+
filters: Dict[str, str] = {}
|
|
496
|
+
if field:
|
|
497
|
+
# Parse multiple filters like "Nodes=x States=DRAIN"
|
|
498
|
+
parts = field.split()
|
|
499
|
+
for part in parts:
|
|
500
|
+
if "=" in part:
|
|
501
|
+
key, value = part.split("=", 1)
|
|
502
|
+
filters[key] = value
|
|
503
|
+
|
|
504
|
+
# Resolve node filters
|
|
505
|
+
# (e.g., nodes=partition=defq -> nodes=node1,node2)
|
|
506
|
+
nodes_value = filters.get("nodes") or filters.get("Nodes")
|
|
507
|
+
if nodes_value and is_node_filter(nodes_value):
|
|
508
|
+
resolved = resolve_node_filter(nodes_value)
|
|
509
|
+
if resolved:
|
|
510
|
+
# Update the filter with resolved node names
|
|
511
|
+
if "nodes" in filters:
|
|
512
|
+
filters["nodes"] = resolved
|
|
513
|
+
if "Nodes" in filters:
|
|
514
|
+
filters["Nodes"] = resolved
|
|
515
|
+
else:
|
|
516
|
+
console.print(
|
|
517
|
+
f"[yellow]No nodes found matching filter: "
|
|
518
|
+
f"{nodes_value}[/yellow]"
|
|
519
|
+
)
|
|
520
|
+
return
|
|
521
|
+
|
|
522
|
+
# Check if CondFlags=Open - if so, always run live
|
|
523
|
+
use_cache = True
|
|
524
|
+
if filters.get("CondFlags", "").lower() == "open":
|
|
525
|
+
use_cache = False
|
|
526
|
+
|
|
527
|
+
try:
|
|
528
|
+
events = []
|
|
529
|
+
|
|
530
|
+
# Try to use cache if allowed
|
|
531
|
+
if use_cache and not force_cache_update:
|
|
532
|
+
# Try JSON cache first, then text cache
|
|
533
|
+
if os.path.exists(EVENTS_JSON_CACHE_FILE):
|
|
534
|
+
with open(EVENTS_JSON_CACHE_FILE, "r") as f:
|
|
535
|
+
events = cls._parse_json_events(f.read())
|
|
536
|
+
elif os.path.exists(EVENTS_CACHE_FILE):
|
|
537
|
+
with open(EVENTS_CACHE_FILE, "r") as f:
|
|
538
|
+
events = cls._parse_events(f.read())
|
|
539
|
+
|
|
540
|
+
# If no cache or forced update, run command
|
|
541
|
+
if not events or force_cache_update or not use_cache:
|
|
542
|
+
# Build command with sacctmgr-level filters
|
|
543
|
+
sacctmgr_filters = {
|
|
544
|
+
k: v
|
|
545
|
+
for k, v in filters.items()
|
|
546
|
+
if k.lower()
|
|
547
|
+
in [
|
|
548
|
+
"clusters",
|
|
549
|
+
"condflags",
|
|
550
|
+
"end",
|
|
551
|
+
"events",
|
|
552
|
+
"nodes",
|
|
553
|
+
"reason",
|
|
554
|
+
"start",
|
|
555
|
+
"states",
|
|
556
|
+
"user",
|
|
557
|
+
]
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
# Fetch events with JSON fallback
|
|
561
|
+
events = cls._fetch_events(sacctmgr_filters)
|
|
562
|
+
|
|
563
|
+
# Save to cache only if not using CondFlags=Open
|
|
564
|
+
if use_cache and events:
|
|
565
|
+
# Save as JSON for faster loading next time
|
|
566
|
+
with open(EVENTS_JSON_CACHE_FILE, "w") as f:
|
|
567
|
+
json.dump({"events": events}, f)
|
|
568
|
+
|
|
569
|
+
if not events:
|
|
570
|
+
console.print("[yellow]No events found.[/yellow]")
|
|
571
|
+
return
|
|
572
|
+
|
|
573
|
+
# Apply client-side filters (all filters that need post-processing)
|
|
574
|
+
# This handles cases where sacctmgr mock doesn't filter
|
|
575
|
+
if filters:
|
|
576
|
+
events = cls._apply_filters(events, filters)
|
|
577
|
+
|
|
578
|
+
if not events:
|
|
579
|
+
console.print(
|
|
580
|
+
"[yellow]No events matching filters found.[/yellow]"
|
|
581
|
+
)
|
|
582
|
+
return
|
|
583
|
+
|
|
584
|
+
# Apply sorting
|
|
585
|
+
if sort_field:
|
|
586
|
+
events = sort_data(events, sort_field, sort_asc)
|
|
587
|
+
|
|
588
|
+
# Output based on style
|
|
589
|
+
if style == "json":
|
|
590
|
+
console.print_json(json.dumps(events, indent=2))
|
|
591
|
+
elif style == "csv":
|
|
592
|
+
# CSV header
|
|
593
|
+
print(delimiter.join(columns))
|
|
594
|
+
for event in events:
|
|
595
|
+
row = [
|
|
596
|
+
cls._format_value(event, col, truncate=False)
|
|
597
|
+
for col in columns
|
|
598
|
+
]
|
|
599
|
+
print(delimiter.join(row))
|
|
600
|
+
else:
|
|
601
|
+
# Pretty table output
|
|
602
|
+
table = Table(
|
|
603
|
+
title="Slurm Events",
|
|
604
|
+
box=SIMPLE_HEAVY,
|
|
605
|
+
show_header=True,
|
|
606
|
+
header_style="bold",
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
# Add columns
|
|
610
|
+
for col in columns:
|
|
611
|
+
col_style = merged_styles.get(col, "white")
|
|
612
|
+
table.add_column(col.title(), style=col_style)
|
|
613
|
+
|
|
614
|
+
# Add rows
|
|
615
|
+
for i, event in enumerate(events):
|
|
616
|
+
row_style = None
|
|
617
|
+
if zebra and i % 2 == 1:
|
|
618
|
+
row_style = "on grey15"
|
|
619
|
+
row = [
|
|
620
|
+
cls._format_value(event, col) for col in columns
|
|
621
|
+
]
|
|
622
|
+
table.add_row(*row, style=row_style)
|
|
623
|
+
|
|
624
|
+
console.print(table)
|
|
625
|
+
|
|
626
|
+
except subprocess.CalledProcessError as e:
|
|
627
|
+
console.print(
|
|
628
|
+
f"[red]Failed to show events:[/red] {e.stderr or e}"
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
@classmethod
|
|
632
|
+
def create(cls, *args, **kwargs) -> None:
|
|
633
|
+
"""Events cannot be created."""
|
|
634
|
+
console.print("[red]Events cannot be created manually.[/red]")
|
|
635
|
+
|
|
636
|
+
@classmethod
|
|
637
|
+
def update(cls, *args, **kwargs) -> None:
|
|
638
|
+
"""Events cannot be updated."""
|
|
639
|
+
console.print("[red]Events cannot be updated manually.[/red]")
|
|
640
|
+
|
|
641
|
+
@classmethod
|
|
642
|
+
def delete(cls, *args, **kwargs) -> None:
|
|
643
|
+
"""Events cannot be deleted."""
|
|
644
|
+
console.print("[red]Events cannot be deleted manually.[/red]")
|
|
645
|
+
|
|
646
|
+
@classmethod
|
|
647
|
+
def generate_autocomplete_options(cls) -> str:
|
|
648
|
+
"""Generate bash autocomplete script for event options."""
|
|
649
|
+
filter_opts = " ".join(
|
|
650
|
+
f"{opt}=" for opt in EVENT_FILTER_OPTIONS
|
|
651
|
+
)
|
|
652
|
+
states = "DOWN DRAIN FAIL FUTR IDLE MAINT POWER REBOOT"
|
|
653
|
+
|
|
654
|
+
script = f"""
|
|
655
|
+
_slurm_cli_events_autocomplete() {{
|
|
656
|
+
local cmd="$1"
|
|
657
|
+
local pos="$2"
|
|
658
|
+
|
|
659
|
+
local cur="${{COMP_WORDS[COMP_CWORD]}}"
|
|
660
|
+
local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
|
|
661
|
+
local filter_options="{filter_opts}"
|
|
662
|
+
|
|
663
|
+
# Handle key=value completion
|
|
664
|
+
if _slurm_parse_keyval "$cur" "$prev"; then
|
|
665
|
+
case "$_key" in
|
|
666
|
+
condflags)
|
|
667
|
+
_slurm_complete_value "Open" "$_key" "$_val" "$cur" ;;
|
|
668
|
+
states)
|
|
669
|
+
_slurm_complete_value "{states}" "$_key" "$_val" "$cur" ;;
|
|
670
|
+
events)
|
|
671
|
+
_slurm_complete_value "Cluster Node" "$_key" "$_val" "$cur" ;;
|
|
672
|
+
nodes)
|
|
673
|
+
_slurm_complete_nodes_value "$_val" "$cur" "$_key" ;;
|
|
674
|
+
clusters)
|
|
675
|
+
# Note: clusters don't have a cache, so no value completion
|
|
676
|
+
;;
|
|
677
|
+
user)
|
|
678
|
+
local cached_users="$(_slurm_cache_users)"
|
|
679
|
+
_slurm_complete_value "$cached_users" "$_key" "$_val" "$cur" ;;
|
|
680
|
+
# Node filter nested keys (when = is a word break, these are parsed as top-level keys)
|
|
681
|
+
partition)
|
|
682
|
+
_slurm_complete_value "$(_slurm_cache_partitions)" "$_key" "$_val" "$cur" ;;
|
|
683
|
+
state)
|
|
684
|
+
_slurm_complete_value "idle alloc drain down mixed comp" "$_key" "$_val" "$cur" ;;
|
|
685
|
+
reservation)
|
|
686
|
+
_slurm_complete_value "$(_slurm_cache_reservations)" "$_key" "$_val" "$cur" ;;
|
|
687
|
+
esac
|
|
688
|
+
[[ ${{#COMPREPLY[@]}} -gt 0 ]] && return
|
|
689
|
+
fi
|
|
690
|
+
|
|
691
|
+
# Default: show filter options
|
|
692
|
+
[[ $cmd == "show" ]] && _slurm_complete "$filter_options" "$cur"
|
|
693
|
+
}}
|
|
694
|
+
""" # noqa: E501
|
|
695
|
+
return script
|