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,88 @@
1
+ """Configuration constants for Slurm CLI."""
2
+
3
+ VERBS = {
4
+ "show": ["ls", "list", "get"],
5
+ "update": ["set", "modify", "edit"],
6
+ "create": ["add", "create", "new"],
7
+ "delete": ["remove", "delete", "rm"],
8
+ "write_config": ["wconf"],
9
+ }
10
+
11
+ ROUTES = {
12
+ "get-set": {
13
+ "partitions": {
14
+ "name": "name",
15
+ "state": "state",
16
+ "nodes": "nodes",
17
+ "accounts": "accounts",
18
+ "hidden": "hidden",
19
+ },
20
+ "nodes": {
21
+ "name": "name",
22
+ "state": "state",
23
+ "partitions": "partitions",
24
+ "users": "users",
25
+ "account": "account",
26
+ },
27
+ "jobs": {
28
+ "state": "state",
29
+ "user": "user",
30
+ "account": "account",
31
+ "partition": "partition",
32
+ "reservation": "reservation",
33
+ },
34
+ "users": {
35
+ "name": "name",
36
+ "account": "account",
37
+ "state": "state",
38
+ "qos": "qos",
39
+ "reservation": "reservation",
40
+ "nodes": "nodes",
41
+ "partition": "partition",
42
+ },
43
+ "qos": {
44
+ "name": "name",
45
+ "default": "default",
46
+ "accounts": "accounts",
47
+ "partition": "partition",
48
+ "users": "users",
49
+ },
50
+ "accounts": {
51
+ "name": "name",
52
+ "users": "users",
53
+ "partitions": "partitions",
54
+ "qos": "qos",
55
+ },
56
+ "associations": {
57
+ "account": "account",
58
+ "user": "user",
59
+ "cluster": "cluster",
60
+ "partition": "partition",
61
+ "qos": "qos",
62
+ },
63
+ "reservations": {
64
+ "name": "name",
65
+ "users": "users",
66
+ "partitions": "partitions",
67
+ },
68
+ "coordinators": {"user": "user", "accounts": "account"},
69
+ "events": {
70
+ "cluster": "cluster",
71
+ "node": "node",
72
+ "state": "state",
73
+ "user": "user",
74
+ "reason": "reason",
75
+ },
76
+ "config": {},
77
+ },
78
+ "create": {
79
+ "partitions": {},
80
+ "nodes": {},
81
+ "users": {},
82
+ "qos": {},
83
+ "accounts": {},
84
+ "associations": {},
85
+ "reservations": {},
86
+ "coordinators": {},
87
+ },
88
+ }
@@ -0,0 +1,426 @@
1
+ """Utilities for managing coordinators."""
2
+
3
+ import json
4
+ import subprocess
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ from rich.box import SIMPLE_HEAVY
8
+ from rich.table import Table
9
+
10
+ from .base_resource import BaseSlurmResource
11
+ from .profiles import get_profile_config, sort_data
12
+ from .utils import console
13
+
14
+
15
+ class Coordinator(BaseSlurmResource):
16
+ def __init__(self, name: str, **kwargs: Any):
17
+ self.name = name
18
+ self.kwargs = kwargs
19
+
20
+ @classmethod
21
+ def get_profile_fields(cls) -> dict:
22
+ """Return field names and descriptions for profile templates."""
23
+ return {
24
+ "account": "Account name",
25
+ "name": "Coordinator username",
26
+ "direct": "Whether coordinator is directly assigned",
27
+ }
28
+
29
+ # Default column configuration for coordinators
30
+ DEFAULT_COLUMNS = ["name", "account", "direct"]
31
+ DEFAULT_STYLES = {
32
+ "name": "cyan",
33
+ "account": "green",
34
+ "direct": "yellow",
35
+ }
36
+
37
+ # Coordinator options for autocomplete
38
+ COORDINATOR_OPTIONS = ["account", "name"]
39
+
40
+ @classmethod
41
+ def generate_autocomplete_options(cls) -> str:
42
+ """Generate bash autocomplete script for coordinator options."""
43
+ script = """
44
+ _slurm_cli_coordinators_autocomplete() {
45
+ local cmd="$1"
46
+ local pos="$2"
47
+
48
+ local cur="${COMP_WORDS[COMP_CWORD]}"
49
+ local prev="${COMP_WORDS[COMP_CWORD-1]}"
50
+
51
+ local cached_accounts="$(_slurm_cache_accounts)"
52
+ local cached_users="$(_slurm_cache_users)"
53
+ local options="account= user= name="
54
+
55
+ # Handle key=value completion for current word
56
+ if _slurm_parse_keyval "$cur" "$prev"; then
57
+ case "$_key" in
58
+ account) _slurm_complete_value "$cached_accounts" "$_key" "$_val" "$cur" ;;
59
+ name|user) _slurm_complete_value "$cached_users" "$_key" "$_val" "$cur" ;;
60
+ esac
61
+ [[ ${#COMPREPLY[@]} -gt 0 ]] && return
62
+ fi
63
+
64
+ # For create, check what's already been specified
65
+ if [[ "$cmd" == "create" ]]; then
66
+ local has_account=false
67
+ local has_user=false
68
+ local has_positional_user=false
69
+
70
+ # Scan previous words to see what's already specified
71
+ for ((i=pos+1; i<COMP_CWORD; i++)); do
72
+ local word="${COMP_WORDS[$i]}"
73
+ if [[ "$word" == account=* ]]; then
74
+ has_account=true
75
+ elif [[ "$word" == name=* || "$word" == user=* ]]; then
76
+ has_user=true
77
+ elif [[ "$word" != *=* && "$word" != -* ]]; then
78
+ # Positional argument (user)
79
+ has_positional_user=true
80
+ fi
81
+ done
82
+
83
+ # First arg after coordinators: show options + users
84
+ if [[ $prev == coordinators || $prev == coord ]]; then
85
+ _slurm_complete "$options $cached_users" "$cur"
86
+ return
87
+ fi
88
+
89
+ # After user= or positional user: suggest account=
90
+ if $has_user || $has_positional_user; then
91
+ if ! $has_account; then
92
+ _slurm_complete "$options" "$cur"
93
+ return
94
+ fi
95
+ fi
96
+
97
+ # After account=: suggest user= with users
98
+ if $has_account; then
99
+ if ! $has_user && ! $has_positional_user; then
100
+ _slurm_complete "$options $cached_users" "$cur"
101
+ return
102
+ fi
103
+ fi
104
+
105
+ # Default: show all options
106
+ _slurm_complete "$options $cached_users" "$cur"
107
+ return
108
+ fi
109
+
110
+ # For show/delete
111
+ if [[ $prev == coordinators || $prev == coord ]]; then
112
+ _slurm_complete "$options $cached_accounts $cached_users" "$cur"
113
+ else
114
+ _slurm_complete "$options" "$cur"
115
+ fi
116
+ }
117
+ """ # noqa: E501
118
+ return script
119
+
120
+ @classmethod
121
+ def create(
122
+ cls,
123
+ user_name: Union[str, None] = None,
124
+ verbose: bool = False,
125
+ account: Union[str, None] = None,
126
+ **kwargs,
127
+ ) -> None:
128
+ """Create a new coordinator.
129
+
130
+ Args:
131
+ user_name: User name (from positional arg or name= option)
132
+ verbose: Enable verbose output
133
+ account: Account name (from account= option)
134
+ **kwargs: Additional options
135
+ """
136
+ if not account:
137
+ console.print(
138
+ "[red]Coordinator creation failed:[/] "
139
+ "account= is required.\n"
140
+ "Usage: slurm-cli create coordinators USER account=ACCOUNT"
141
+ )
142
+ return
143
+
144
+ if not user_name:
145
+ console.print(
146
+ "[red]Coordinator creation failed:[/] "
147
+ "User name is required.\n"
148
+ "Usage: slurm-cli create coordinators USER account=ACCOUNT"
149
+ )
150
+ return
151
+
152
+ args = [
153
+ "sacctmgr",
154
+ "-i",
155
+ "add",
156
+ "coordinator",
157
+ f"accounts={account}",
158
+ f"names={user_name}",
159
+ ]
160
+
161
+ if verbose:
162
+ console.print(f"[dim]Running: {' '.join(args)}[/dim]")
163
+
164
+ try:
165
+ result = subprocess.run(
166
+ args,
167
+ check=True,
168
+ capture_output=True,
169
+ text=True,
170
+ )
171
+ console.print(
172
+ f"[green]Coordinator '{user_name}' added to account "
173
+ f"'{account}' successfully.[/green]"
174
+ )
175
+ if result.stdout:
176
+ console.print(result.stdout)
177
+ except subprocess.CalledProcessError as e:
178
+ console.print(
179
+ f"[red]Failed to create coordinator '{user_name}' "
180
+ f"for account '{account}':[/] {e.stderr or e}"
181
+ )
182
+
183
+ @classmethod
184
+ def update(
185
+ cls,
186
+ account: Union[str, None] = None,
187
+ verbose: bool = False,
188
+ where_conditions: Union[List[str], None] = None,
189
+ set_values: Union[List[str], None] = None,
190
+ **kwargs: Any,
191
+ ) -> None:
192
+ """Update operation is not supported for coordinators.
193
+
194
+ Coordinators can only be added (create) or removed (delete).
195
+ """
196
+ console.print(
197
+ "[red]Update operation is not supported for coordinators.[/red]\n"
198
+ "Use 'slurm-cli create coordinators' to add coordinators or "
199
+ "'slurm-cli delete coordinators' to remove them."
200
+ )
201
+
202
+ @classmethod
203
+ def delete(
204
+ cls,
205
+ account: Union[str, None] = None,
206
+ names: Union[List[str], None] = None,
207
+ verbose: bool = False,
208
+ ) -> None:
209
+ """Delete coordinators from an account.
210
+
211
+ Args:
212
+ account: Account name to remove coordinators from
213
+ names: List of coordinator names to remove
214
+ verbose: Enable verbose output
215
+ """
216
+ if not names:
217
+ console.print(
218
+ "[red]No coordinator names specified for deletion.[/red]"
219
+ )
220
+ return
221
+
222
+ for name in names:
223
+ args = [
224
+ "sacctmgr",
225
+ "-i",
226
+ "delete",
227
+ "coordinator",
228
+ f"account={account}",
229
+ f"name={name}",
230
+ ]
231
+
232
+ if verbose:
233
+ console.print(f"[dim]Running: {' '.join(args)}[/dim]")
234
+
235
+ try:
236
+ result = subprocess.run(
237
+ args,
238
+ check=True,
239
+ capture_output=True,
240
+ text=True,
241
+ )
242
+ console.print(
243
+ f"[green]Removed coordinator '{name}' "
244
+ f"from account '{account}'[/green]"
245
+ )
246
+ if result.stdout:
247
+ console.print(result.stdout)
248
+ except subprocess.CalledProcessError as e:
249
+ console.print(
250
+ f"[red]Failed to delete coordinator '{name}':[/red] "
251
+ f"{e.stderr or e}"
252
+ )
253
+
254
+ @classmethod
255
+ def _extract_coordinators(
256
+ cls, accounts: List[Dict[str, Any]]
257
+ ) -> List[Dict[str, Any]]:
258
+ """Extract coordinators from accounts data.
259
+
260
+ Returns a list of coordinator records with account info.
261
+ """
262
+ coordinators = []
263
+ for account in accounts:
264
+ account_name = account.get("name", "")
265
+ for coord in account.get("coordinators", []):
266
+ coordinators.append(
267
+ {
268
+ "name": coord.get("name", ""),
269
+ "account": account_name,
270
+ "direct": "Yes"
271
+ if coord.get("direct")
272
+ else "No",
273
+ }
274
+ )
275
+ return coordinators
276
+
277
+ @classmethod
278
+ def _format_value(cls, coord: Dict[str, Any], column: str) -> str:
279
+ """Format a value for display."""
280
+ value = coord.get(column, "")
281
+ if value is None or value == "":
282
+ return "-"
283
+ return str(value)
284
+
285
+ @classmethod
286
+ def show(
287
+ cls,
288
+ field: Union[str, None] = None,
289
+ style: str = "pretty",
290
+ force_cache_update: bool = False,
291
+ delimiter: str = ";",
292
+ zebra: bool = False,
293
+ profile: str = "default",
294
+ profile_str: Optional[str] = None,
295
+ ) -> None:
296
+ """Show coordinator information.
297
+
298
+ Args:
299
+ field: Optional filter (user name or account=name)
300
+ style: Output style ("pretty", "json", or "csv")
301
+ force_cache_update: Whether to force cache update (unused)
302
+ delimiter: Delimiter for CSV output (default: ";")
303
+ zebra: Use zebra striping for table rows
304
+ profile: Profile name to use for output formatting
305
+ profile_str: Inline profile string (overrides profile)
306
+ """
307
+ # Get profile configuration
308
+ (
309
+ columns,
310
+ styles,
311
+ template,
312
+ sort_field,
313
+ sort_asc,
314
+ ) = get_profile_config(profile, "coordinators", profile_str)
315
+
316
+ # Use default columns if not specified
317
+ if columns == "*" or columns is None:
318
+ columns = cls.DEFAULT_COLUMNS
319
+
320
+ # Merge with default styles
321
+ merged_styles = dict(cls.DEFAULT_STYLES)
322
+ if styles:
323
+ merged_styles.update(styles)
324
+
325
+ try:
326
+ result = subprocess.run(
327
+ [
328
+ "sacctmgr",
329
+ "show",
330
+ "accounts",
331
+ "withcoord",
332
+ "--json",
333
+ ],
334
+ check=True,
335
+ capture_output=True,
336
+ text=True,
337
+ )
338
+
339
+ if not result.stdout:
340
+ console.print("[yellow]No coordinators found.[/yellow]")
341
+ return
342
+
343
+ # Parse JSON data
344
+ data = json.loads(result.stdout)
345
+ accounts = data.get("accounts", [])
346
+
347
+ # Extract coordinators from accounts
348
+ coordinators = cls._extract_coordinators(accounts)
349
+
350
+ if not coordinators:
351
+ console.print("[yellow]No coordinators found.[/yellow]")
352
+ return
353
+
354
+ # Filter if field is specified
355
+ if field:
356
+ if "=" in field:
357
+ # Filter like account=nvidia
358
+ key, value = field.split("=", 1)
359
+ key = key.lower()
360
+ coordinators = [
361
+ c
362
+ for c in coordinators
363
+ if str(c.get(key, "")).lower() == value.lower()
364
+ ]
365
+ else:
366
+ # Filter by coordinator name
367
+ coordinators = [
368
+ c
369
+ for c in coordinators
370
+ if c.get("name", "").lower() == field.lower()
371
+ ]
372
+
373
+ if not coordinators:
374
+ console.print(
375
+ f"[yellow]No coordinators matching "
376
+ f"'{field}' found.[/yellow]"
377
+ )
378
+ return
379
+
380
+ # Apply sorting
381
+ if sort_field:
382
+ coordinators = sort_data(
383
+ coordinators, sort_field, sort_asc
384
+ )
385
+
386
+ # Output based on style
387
+ if style == "json":
388
+ console.print_json(json.dumps(coordinators, indent=2))
389
+ elif style == "csv":
390
+ # CSV header
391
+ print(delimiter.join(columns))
392
+ for coord in coordinators:
393
+ row = [
394
+ cls._format_value(coord, col) for col in columns
395
+ ]
396
+ print(delimiter.join(row))
397
+ else:
398
+ # Pretty table output
399
+ table = Table(
400
+ title="Coordinators",
401
+ box=SIMPLE_HEAVY,
402
+ show_header=True,
403
+ header_style="bold",
404
+ )
405
+
406
+ # Add columns
407
+ for col in columns:
408
+ style = merged_styles.get(col, "white")
409
+ table.add_column(col.title(), style=style)
410
+
411
+ # Add rows
412
+ for i, coord in enumerate(coordinators):
413
+ row_style = None
414
+ if zebra and i % 2 == 1:
415
+ row_style = "on grey15"
416
+ row = [
417
+ cls._format_value(coord, col) for col in columns
418
+ ]
419
+ table.add_row(*row, style=row_style)
420
+
421
+ console.print(table)
422
+
423
+ except subprocess.CalledProcessError as e:
424
+ console.print(
425
+ f"[red]Failed to show coordinators:[/red] {e.stderr or e}"
426
+ )