richqueue 0.1__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.
richqueue/__init__.py ADDED
File without changes
richqueue/slurm.py ADDED
@@ -0,0 +1,407 @@
1
+ from typer import Typer
2
+ import json
3
+ import datetime
4
+ from rich.console import Console
5
+ from rich.panel import Panel
6
+ from rich.layout import Layout
7
+ from pandas import DataFrame
8
+
9
+ console = Console()
10
+
11
+ METADATA = {}
12
+
13
+ app = Typer()
14
+
15
+ def color_by_state(state):
16
+
17
+ if state == "RUNNING":
18
+ return "[bold bright_green]Running"
19
+ elif state == "PENDING":
20
+ return "[bright_yellow]Pending"
21
+ elif state == "CANCELLED":
22
+ return "[orange3]Cancelled"
23
+ elif state == "FAILED":
24
+ return "[bold bright_red]Failed"
25
+ elif state == "COMPLETED":
26
+ return "[bold bright_green]Completed"
27
+ else:
28
+ return state
29
+
30
+ def extract_inner(df, key, inner):
31
+
32
+ def _inner(x):
33
+ d = x[key]
34
+ if "set" in d:
35
+ if d["set"]:
36
+ return d[inner]
37
+ else:
38
+ return None
39
+ else:
40
+ return d[inner]
41
+
42
+ df[key] = df.apply(_inner, axis=1)
43
+
44
+ def extract_time(df, key):
45
+ df[key] = df.apply(
46
+ lambda x: datetime.datetime.fromtimestamp(x[key]["number"]), axis=1
47
+ )
48
+
49
+ def extract_list(df, key):
50
+ def inner(x):
51
+ if len(x[key]) == 1:
52
+ return x[key][0]
53
+ else:
54
+ return x[key]
55
+
56
+ df[key] = df.apply(inner, axis=1)
57
+
58
+
59
+ def job_table(
60
+ df,
61
+ title: str = "jobs",
62
+ long: bool = False,
63
+ return_table: bool = False,
64
+ box: bool = False,
65
+ panel: bool = True,
66
+ ):
67
+
68
+ from rich.table import Table
69
+
70
+ if box:
71
+ from rich.box import SIMPLE
72
+
73
+ box = SIMPLE
74
+
75
+ from .tools import human_timedelta, human_datetime
76
+
77
+ num_nodes = "node_count" in df.columns
78
+ num_cores = "cpus" in df.columns
79
+ start_time = "start_time" in df.columns
80
+
81
+ table = Table(title=title, box=box, header_style="")
82
+
83
+ table.add_column(
84
+ "[bold underline]Job Id", justify="right", style="bold", no_wrap=True
85
+ )
86
+ table.add_column(
87
+ "[underline cyan]Job Name", justify="left", style="cyan", no_wrap=False
88
+ )
89
+ if num_nodes:
90
+ table.add_column(
91
+ "[underline magenta]#N", justify="right", style="magenta", no_wrap=True
92
+ )
93
+ if num_cores:
94
+ table.add_column(
95
+ "[underline magenta]#C", justify="right", style="magenta", no_wrap=True
96
+ )
97
+
98
+ if long and start_time:
99
+ table.add_column(
100
+ "[underline dodger_blue2]Start Time",
101
+ justify="right",
102
+ style="dodger_blue2",
103
+ no_wrap=True,
104
+ )
105
+
106
+ if start_time:
107
+ table.add_column(
108
+ "[underline dodger_blue2]Run Time",
109
+ justify="right",
110
+ style="dodger_blue2",
111
+ no_wrap=True,
112
+ )
113
+
114
+ if long:
115
+ table.add_column(
116
+ "[underline green_yellow]Partition",
117
+ justify="right",
118
+ style="green_yellow",
119
+ no_wrap=True,
120
+ )
121
+ table.add_column(
122
+ "[underline green_yellow]Nodes",
123
+ justify="left",
124
+ style="green_yellow",
125
+ no_wrap=False,
126
+ )
127
+
128
+ table.add_column(
129
+ "[underline bold]State", justify="left", style=None, no_wrap=True
130
+ )
131
+
132
+ for i, row in df.iterrows():
133
+
134
+ if start_time:
135
+ start_time = human_datetime(row.start_time)
136
+ run_time = human_timedelta(datetime.datetime.now() - row.start_time)
137
+
138
+ values = [row.job_id, row["name"]]
139
+
140
+ if num_nodes:
141
+ values.append(row.node_count)
142
+ if num_cores:
143
+ values.append(row.cpus)
144
+
145
+ if long and start_time:
146
+ values.append(start_time)
147
+
148
+ if start_time:
149
+ values.append(run_time)
150
+
151
+ if long:
152
+ values += [row.partition, row.nodes]
153
+
154
+ values.append(color_by_state(row.job_state))
155
+
156
+ table.add_row(*[str(v) for v in values])
157
+
158
+ if panel:
159
+ table = Panel(table, expand=False)
160
+
161
+ if return_table:
162
+ return table
163
+
164
+ console.print(table)
165
+
166
+
167
+ def parse_squeue_json(payload: dict) -> "DataFrame":
168
+
169
+ command = "squeue"
170
+
171
+ global METADATA
172
+
173
+ METADATA = {
174
+ "cluster_name": payload["meta"]["slurm"]["cluster"],
175
+ "user": payload["meta"]["client"]["user"],
176
+ "group": payload["meta"]["client"]["group"],
177
+ }
178
+
179
+ # parse payload
180
+ df = DataFrame(payload["jobs"])
181
+
182
+ # filter columns
183
+
184
+ columns = COLUMNS[command]
185
+
186
+ try:
187
+ df = df[columns]
188
+
189
+ except KeyError:
190
+
191
+ for key in columns:
192
+ if key not in df.columns:
193
+ raise KeyError(key)
194
+
195
+ extract_inner(df, "cpus", "number")
196
+ extract_inner(df, "node_count", "number")
197
+ extract_inner(df, "cpus_per_task", "number")
198
+ extract_inner(df, "threads_per_core", "number")
199
+
200
+ extract_time(df, "end_time")
201
+ extract_time(df, "start_time")
202
+ extract_time(df, "submit_time")
203
+ extract_time(df, "time_limit")
204
+
205
+ extract_list(df, "job_state")
206
+
207
+ return df
208
+
209
+ def parse_sacct_json(payload: dict) -> "DataFrame":
210
+
211
+ command = "sacct"
212
+
213
+ global METADATA
214
+
215
+ METADATA.update({
216
+ "cluster_name": payload["meta"]["slurm"]["cluster"],
217
+ "user": payload["meta"]["client"]["user"],
218
+ "group": payload["meta"]["client"]["group"],
219
+ })
220
+
221
+ # parse payload
222
+ df = DataFrame(payload["jobs"])
223
+
224
+ # filter columns
225
+
226
+ columns = COLUMNS[command]
227
+
228
+ try:
229
+ df = df[columns]
230
+
231
+ except KeyError:
232
+
233
+ for key in columns:
234
+ if key not in df.columns:
235
+ raise KeyError(key)
236
+
237
+ df = df.rename(columns={"user":"user_name", "state":"job_state"})
238
+
239
+ extract_inner(df, "job_state", "current")
240
+
241
+ # extract_number(df, "cpus")
242
+ # extract_number(df, "node_count")
243
+ # extract_number(df, "cpus_per_task")
244
+ # extract_number(df, "threads_per_core")
245
+
246
+ # extract_time(df, "end_time")
247
+ # extract_time(df, "start_time")
248
+ # extract_time(df, "submit_time")
249
+ # extract_time(df, "time_limit")
250
+
251
+ extract_list(df, "job_state")
252
+
253
+ df = df[df["job_state"] != "RUNNING"]
254
+
255
+ return df
256
+
257
+ def show_queue(
258
+ command: str,
259
+ user: None | str = None,
260
+ long: bool = False,
261
+ return_table: bool = False,
262
+ box: bool = False,
263
+ ):
264
+
265
+ import subprocess
266
+
267
+ if user == "all":
268
+ user = None
269
+ elif user is None:
270
+ x = subprocess.Popen(["whoami"], shell=True, stdout=subprocess.PIPE)
271
+ output = x.communicate()
272
+ user = output[0].strip().decode("utf-8")
273
+
274
+ if user:
275
+ s_command = f"{command} -u {user} --json"
276
+ else:
277
+ s_command = f"{command} --json"
278
+
279
+ x = subprocess.Popen([s_command], shell=True, stdout=subprocess.PIPE)
280
+ output = x.communicate()
281
+
282
+ payload = json.loads(output[0])
283
+
284
+ parser = PARSERS[command]
285
+
286
+ df = parser(payload)
287
+
288
+ cluster = METADATA["cluster_name"]
289
+
290
+ if command == "sacct":
291
+ title = f"[bold]{user}'s history on {cluster}"
292
+
293
+ elif user:
294
+ df = df[df["user_name"] == user]
295
+ title = f"[bold]{user}'s jobs on {cluster}"
296
+ else:
297
+ title = f"[bold]jobs on {cluster}"
298
+
299
+ return job_table(df, title=title, long=long, return_table=return_table, box=box)
300
+
301
+ def dual_layout(
302
+ user: None | str = None,
303
+ long: bool = False,
304
+ return_table: bool = True,
305
+ box: bool = False,
306
+ ):
307
+
308
+ layout = Layout()
309
+
310
+ panel1 = show_queue(user=user, command="squeue", long=long, return_table=True)
311
+ panel2 = show_queue(user=user, command="sacct", long=long, return_table=True)
312
+
313
+ upper = Layout(renderable=panel1, name="upper")
314
+ lower = Layout(renderable=panel2, name="lower")
315
+
316
+ upper.size = panel1.renderable.row_count+4
317
+ lower.size = panel2.renderable.row_count+4
318
+
319
+ layout.split_column(
320
+ upper,
321
+ lower,
322
+ )
323
+
324
+ if not return_table:
325
+ console.print(layout)
326
+ else:
327
+ return layout
328
+
329
+ @app.command()
330
+ def show(user: None | str = None, long: bool = False):
331
+
332
+ loop = True
333
+
334
+ if loop:
335
+
336
+ from rich.live import Live
337
+ import time
338
+
339
+ layout = dual_layout(user=user, long=long)
340
+
341
+ with Live(layout, refresh_per_second=4, screen=True) as live:
342
+ while True:
343
+
344
+ layout = dual_layout(user=user, long=long)
345
+ live.update(layout)
346
+
347
+ time.sleep(1)
348
+
349
+ else:
350
+ layout = dual_layout(user=user, long=long)
351
+ console.print(layout)
352
+ # show_queue(command="squeue", user=user, long=long)
353
+ # show_queue(command="sacct", user=user, long=long)
354
+
355
+
356
+ def main():
357
+
358
+ squeue = json.load(open("../example_data/squeue.json"))
359
+
360
+ parse_squeue_json(squeue)
361
+
362
+ PARSERS = {"squeue":parse_squeue_json, "sacct":parse_sacct_json}
363
+
364
+ COLUMNS = {
365
+ "sacct":[
366
+ "job_id",
367
+ "state",
368
+ "name",
369
+ "nodes",
370
+ "partition",
371
+ "user",
372
+ ],
373
+
374
+ "squeue":[
375
+ "command",
376
+ "cpus_per_task",
377
+ "dependency",
378
+ "derived_exit_code",
379
+ "end_time",
380
+ "group_name",
381
+ "job_id",
382
+ "job_state",
383
+ "name",
384
+ "nodes",
385
+ "node_count",
386
+ "cpus",
387
+ "tasks",
388
+ "partition",
389
+ "memory_per_cpu",
390
+ "memory_per_node",
391
+ "qos",
392
+ "restart_cnt",
393
+ "requeue",
394
+ "exclusive",
395
+ "start_time",
396
+ "standard_error",
397
+ "standard_output",
398
+ "submit_time",
399
+ "time_limit",
400
+ "threads_per_core",
401
+ "user_name",
402
+ "current_working_directory",
403
+ ]}
404
+
405
+
406
+ if __name__ == "__main__":
407
+ app()
richqueue/tools.py ADDED
@@ -0,0 +1,58 @@
1
+ import datetime
2
+
3
+
4
+ def human_timedelta(delta):
5
+
6
+ bits = []
7
+
8
+ days = delta.days
9
+
10
+ s = delta.seconds
11
+
12
+ m, s = divmod(s, 60)
13
+ h, m = divmod(m, 60)
14
+
15
+ if days:
16
+ bits.append(f"{days}d")
17
+
18
+ if h:
19
+ bits.append(f"{h}h")
20
+
21
+ if m:
22
+ bits.append(f"{m}m")
23
+
24
+ if s:
25
+ bits.append(f"{s}s")
26
+
27
+ bits = (str(b) for b in bits)
28
+
29
+ return " ".join(bits)
30
+
31
+
32
+ def human_datetime(dt):
33
+
34
+ now = datetime.datetime.now()
35
+
36
+ bits = []
37
+
38
+ bits.append(dt.strftime("%b"))
39
+
40
+ day = dt.day
41
+
42
+ match day % 10:
43
+ case 1:
44
+ suffix = "st"
45
+ case 2:
46
+ suffix = "nd"
47
+ case 3:
48
+ suffix = "rd"
49
+ case _:
50
+ suffix = "th"
51
+
52
+ bits.append(f"{day}{suffix}")
53
+
54
+ bits.append(dt.strftime("%H:%M"))
55
+
56
+ bits = (str(b) for b in bits)
57
+
58
+ return " ".join(bits)
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.3
2
+ Name: richqueue
3
+ Version: 0.1
4
+ Summary: RichQueue
5
+ Project-URL: Homepage, https://github.com/mwinokan/RichQueue/issues
6
+ Project-URL: Bug Tracker, https://github.com/mwinokan/RichQueue/issues
7
+ Author-email: Max Winokan <max@winokan.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: pandas
14
+ Requires-Dist: rich
15
+ Requires-Dist: typer
16
+ Description-Content-Type: text/markdown
17
+
18
+ # RichQueue
19
+ 💰 RichQueue: A colourful and pythonic SLURM queue viewer
@@ -0,0 +1,7 @@
1
+ richqueue/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ richqueue/slurm.py,sha256=S18JS3InXuCPnyTjP-4A1nYAJojvwqMoUwy2xt5HOW8,9131
3
+ richqueue/tools.py,sha256=n2MOQWgBykaY3wnhJYqvHsJDKavnyJWx8Pq1SkSTiPU,841
4
+ richqueue-0.1.dist-info/METADATA,sha256=5ypyXOWErOSCYIpp57dZ2NYI2N5-NP9waPgo4FPD4Ew,621
5
+ richqueue-0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
6
+ richqueue-0.1.dist-info/licenses/LICENSE,sha256=IeuPfRcqKv1nyCnVVwJaO9Uratg-K2dnkuOROLgQ4qw,1068
7
+ richqueue-0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Max Winokan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.