slurme 0.1.0__tar.gz
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.
- slurme-0.1.0/.github/workflows/publish.yml +54 -0
- slurme-0.1.0/.gitignore +4 -0
- slurme-0.1.0/PKG-INFO +77 -0
- slurme-0.1.0/README.md +64 -0
- slurme-0.1.0/pyproject.toml +25 -0
- slurme-0.1.0/slurme/__init__.py +3 -0
- slurme-0.1.0/slurme/__main__.py +3 -0
- slurme-0.1.0/slurme/cli.py +40 -0
- slurme-0.1.0/slurme/data.py +218 -0
- slurme-0.1.0/slurme/ui.py +590 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.x"
|
|
17
|
+
|
|
18
|
+
- name: Check that the tag matches the package version
|
|
19
|
+
run: |
|
|
20
|
+
version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
|
|
21
|
+
if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
|
|
22
|
+
echo "Tag ${GITHUB_REF_NAME} does not match the version ${version} in pyproject.toml"
|
|
23
|
+
exit 1
|
|
24
|
+
fi
|
|
25
|
+
|
|
26
|
+
- name: Build distributions
|
|
27
|
+
run: |
|
|
28
|
+
pip install build
|
|
29
|
+
python -m build
|
|
30
|
+
|
|
31
|
+
- name: Upload distributions as artifact
|
|
32
|
+
uses: actions/upload-artifact@v4
|
|
33
|
+
with:
|
|
34
|
+
name: dist
|
|
35
|
+
path: dist/
|
|
36
|
+
|
|
37
|
+
publish:
|
|
38
|
+
needs: build
|
|
39
|
+
runs-on: ubuntu-latest
|
|
40
|
+
environment: pypi
|
|
41
|
+
permissions:
|
|
42
|
+
id-token: write # required for Trusted Publishing
|
|
43
|
+
|
|
44
|
+
steps:
|
|
45
|
+
- name: Download distributions
|
|
46
|
+
uses: actions/download-artifact@v4
|
|
47
|
+
with:
|
|
48
|
+
name: dist
|
|
49
|
+
path: dist/
|
|
50
|
+
|
|
51
|
+
- name: Publish to PyPI
|
|
52
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
53
|
+
with:
|
|
54
|
+
verbose: true
|
slurme-0.1.0/.gitignore
ADDED
slurme-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: slurme
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Terminal UI for Slurm: jobs, GPUs, history and logs
|
|
5
|
+
Author-email: Shenhan Qian <shenhan.qian@tum.de>
|
|
6
|
+
License: MIT
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
Requires-Dist: gpustat
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Slurme
|
|
15
|
+
|
|
16
|
+
A fast terminal UI for Slurm: jobs in the queue, GPUs per node, job history, and the logs of current
|
|
17
|
+
and past jobs. Slurme is a curses port of [Slurman](https://github.com/ShenhanQian/slurman), itself
|
|
18
|
+
derived from [SlurmUI](https://github.com/SirWyver/slurmui). It runs on Python 3.8+ with nothing but
|
|
19
|
+
the standard library; `gpustat` is only needed for the per-job GPU view.
|
|
20
|
+
|
|
21
|
+
On LRZ AI it shows your jobs about 0.15–0.4 s after starting (Slurman: 0.7–2.9 s).
|
|
22
|
+
|
|
23
|
+
## Install and run
|
|
24
|
+
|
|
25
|
+
```shell
|
|
26
|
+
pip install -e . # from a clone of this repository
|
|
27
|
+
slurme # or, without installing: PYTHONPATH=/path/to/slurme python3 -m slurme
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Options:
|
|
31
|
+
|
|
32
|
+
- `-i SECONDS` refresh interval (default 10; 0 disables auto refresh)
|
|
33
|
+
- `-r RANGE` history range to load: `1 week` (default), `1 month`, `4 months`, `1 year`
|
|
34
|
+
- `-t THEME` colour theme: `classic` (default), `slate`, `frost`, `light` (light terminals), `mono`;
|
|
35
|
+
also read from `$SLURME_THEME`
|
|
36
|
+
- `-v` verbose: print every Slurm command to the info panel
|
|
37
|
+
|
|
38
|
+
## Keys
|
|
39
|
+
|
|
40
|
+
| Key | Action |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `j` / `g` / `h` | Jobs / GPUs / History tab; pressed again, toggles its filter (running jobs, available nodes, completed jobs) |
|
|
43
|
+
| `J` | Jobs: my jobs or all users |
|
|
44
|
+
| `H` | History: cycle the time range |
|
|
45
|
+
| arrows, `PgUp` `PgDn`, `Home` `End` | move the cursor; left and right pick the column to sort by |
|
|
46
|
+
| `s` | sort by the column under the cursor (again: reverse) |
|
|
47
|
+
| `space` / `v` | select a job / invert the selection (selected rows are highlighted across the full width) |
|
|
48
|
+
| `d`, then `Enter` | cancel the selected job(s); `q` aborts |
|
|
49
|
+
| `l` | open the job's log in `less` (`F` follows new output, `q` returns) |
|
|
50
|
+
| `G` | `gpustat` on the job's nodes |
|
|
51
|
+
| `S` | shell on the job's node (`srun --overlap --pty`) |
|
|
52
|
+
| `r` | refresh |
|
|
53
|
+
| `T` | cycle the colour theme |
|
|
54
|
+
| `q` | back; on the Jobs tab, quit (`Ctrl-C` quits anywhere) |
|
|
55
|
+
|
|
56
|
+
The footer lists the keys that work in the current view.
|
|
57
|
+
|
|
58
|
+
## How it works
|
|
59
|
+
|
|
60
|
+
Slurme reads three Slurm commands; check that they give sensible output on your cluster first:
|
|
61
|
+
|
|
62
|
+
- `squeue` for jobs in the queue
|
|
63
|
+
- `sinfo` for nodes and GPUs
|
|
64
|
+
- `sacct` for past jobs
|
|
65
|
+
|
|
66
|
+
Queries run in background threads, so the keys stay responsive while Slurm answers, and only the rows
|
|
67
|
+
that fit on screen are drawn. `slurme -i 0 -v` disables auto refresh and prints every command it runs
|
|
68
|
+
to the info panel. Errors appear in the info panel and are also written to `~/.slurme_error.log`.
|
|
69
|
+
|
|
70
|
+
## Differences from Slurman
|
|
71
|
+
|
|
72
|
+
- curses instead of Textual, and no pandas: no dependencies, much faster startup and table updates.
|
|
73
|
+
- Sorting is natural: durations by length, numbers by value (job IDs, priorities, `18/20`), empty
|
|
74
|
+
values last.
|
|
75
|
+
- Empty fields show empty instead of `nan`, and spaces inside job names are kept.
|
|
76
|
+
- `q` on the Jobs tab quits; errors from `srun`/`scancel` go to the info panel instead of the screen.
|
|
77
|
+
- No mouse support.
|
slurme-0.1.0/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Slurme
|
|
2
|
+
|
|
3
|
+
A fast terminal UI for Slurm: jobs in the queue, GPUs per node, job history, and the logs of current
|
|
4
|
+
and past jobs. Slurme is a curses port of [Slurman](https://github.com/ShenhanQian/slurman), itself
|
|
5
|
+
derived from [SlurmUI](https://github.com/SirWyver/slurmui). It runs on Python 3.8+ with nothing but
|
|
6
|
+
the standard library; `gpustat` is only needed for the per-job GPU view.
|
|
7
|
+
|
|
8
|
+
On LRZ AI it shows your jobs about 0.15–0.4 s after starting (Slurman: 0.7–2.9 s).
|
|
9
|
+
|
|
10
|
+
## Install and run
|
|
11
|
+
|
|
12
|
+
```shell
|
|
13
|
+
pip install -e . # from a clone of this repository
|
|
14
|
+
slurme # or, without installing: PYTHONPATH=/path/to/slurme python3 -m slurme
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Options:
|
|
18
|
+
|
|
19
|
+
- `-i SECONDS` refresh interval (default 10; 0 disables auto refresh)
|
|
20
|
+
- `-r RANGE` history range to load: `1 week` (default), `1 month`, `4 months`, `1 year`
|
|
21
|
+
- `-t THEME` colour theme: `classic` (default), `slate`, `frost`, `light` (light terminals), `mono`;
|
|
22
|
+
also read from `$SLURME_THEME`
|
|
23
|
+
- `-v` verbose: print every Slurm command to the info panel
|
|
24
|
+
|
|
25
|
+
## Keys
|
|
26
|
+
|
|
27
|
+
| Key | Action |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `j` / `g` / `h` | Jobs / GPUs / History tab; pressed again, toggles its filter (running jobs, available nodes, completed jobs) |
|
|
30
|
+
| `J` | Jobs: my jobs or all users |
|
|
31
|
+
| `H` | History: cycle the time range |
|
|
32
|
+
| arrows, `PgUp` `PgDn`, `Home` `End` | move the cursor; left and right pick the column to sort by |
|
|
33
|
+
| `s` | sort by the column under the cursor (again: reverse) |
|
|
34
|
+
| `space` / `v` | select a job / invert the selection (selected rows are highlighted across the full width) |
|
|
35
|
+
| `d`, then `Enter` | cancel the selected job(s); `q` aborts |
|
|
36
|
+
| `l` | open the job's log in `less` (`F` follows new output, `q` returns) |
|
|
37
|
+
| `G` | `gpustat` on the job's nodes |
|
|
38
|
+
| `S` | shell on the job's node (`srun --overlap --pty`) |
|
|
39
|
+
| `r` | refresh |
|
|
40
|
+
| `T` | cycle the colour theme |
|
|
41
|
+
| `q` | back; on the Jobs tab, quit (`Ctrl-C` quits anywhere) |
|
|
42
|
+
|
|
43
|
+
The footer lists the keys that work in the current view.
|
|
44
|
+
|
|
45
|
+
## How it works
|
|
46
|
+
|
|
47
|
+
Slurme reads three Slurm commands; check that they give sensible output on your cluster first:
|
|
48
|
+
|
|
49
|
+
- `squeue` for jobs in the queue
|
|
50
|
+
- `sinfo` for nodes and GPUs
|
|
51
|
+
- `sacct` for past jobs
|
|
52
|
+
|
|
53
|
+
Queries run in background threads, so the keys stay responsive while Slurm answers, and only the rows
|
|
54
|
+
that fit on screen are drawn. `slurme -i 0 -v` disables auto refresh and prints every command it runs
|
|
55
|
+
to the info panel. Errors appear in the info panel and are also written to `~/.slurme_error.log`.
|
|
56
|
+
|
|
57
|
+
## Differences from Slurman
|
|
58
|
+
|
|
59
|
+
- curses instead of Textual, and no pandas: no dependencies, much faster startup and table updates.
|
|
60
|
+
- Sorting is natural: durations by length, numbers by value (job IDs, priorities, `18/20`), empty
|
|
61
|
+
values last.
|
|
62
|
+
- Empty fields show empty instead of `nan`, and spaces inside job names are kept.
|
|
63
|
+
- `q` on the Jobs tab quits; errors from `srun`/`scancel` go to the info panel instead of the screen.
|
|
64
|
+
- No mouse support.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "slurme"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Terminal UI for Slurm: jobs, GPUs, history and logs"
|
|
5
|
+
readme = {file = "README.md", content-type = "text/markdown"}
|
|
6
|
+
authors = [
|
|
7
|
+
{name = "Shenhan Qian", email = "shenhan.qian@tum.de"}
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.8"
|
|
10
|
+
license = {text = "MIT"}
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"License :: OSI Approved :: MIT License",
|
|
14
|
+
"Operating System :: OS Independent"
|
|
15
|
+
]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"gpustat",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
slurme = "slurme.cli:main"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["hatchling"]
|
|
25
|
+
build-backend = "hatchling.build"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from argparse import ArgumentParser
|
|
2
|
+
|
|
3
|
+
from . import run_ui
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main():
|
|
7
|
+
parser = ArgumentParser("slurme", description="Terminal UI for Slurm: jobs, GPUs, history and logs")
|
|
8
|
+
parser.add_argument("-v", "--verbose", action="store_true",
|
|
9
|
+
help="print the Slurm commands and internal events to the info panel")
|
|
10
|
+
parser.add_argument(
|
|
11
|
+
"-i",
|
|
12
|
+
"--interval",
|
|
13
|
+
help="Specify the interval in seconds to refresh the UI (0 disables auto refresh)",
|
|
14
|
+
type=int,
|
|
15
|
+
default=10,
|
|
16
|
+
)
|
|
17
|
+
parser.add_argument(
|
|
18
|
+
"-r",
|
|
19
|
+
"--history-range",
|
|
20
|
+
help="Specify the time range of history jobs to load: 1 week, 1 month, 4 months or 1 year",
|
|
21
|
+
type=str,
|
|
22
|
+
default="1 week",
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"-t",
|
|
26
|
+
"--theme",
|
|
27
|
+
choices=["slate", "frost", "classic", "light", "mono"],
|
|
28
|
+
help="colour theme (default: $SLURME_THEME or classic); press T in the UI to try them",
|
|
29
|
+
)
|
|
30
|
+
args = parser.parse_args()
|
|
31
|
+
run_ui(
|
|
32
|
+
verbose=args.verbose,
|
|
33
|
+
interval=args.interval,
|
|
34
|
+
history_range=args.history_range,
|
|
35
|
+
theme=args.theme,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
main()
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Slurm queries and parsing: squeue (jobs), sinfo (GPUs per node) and sacct (history)."""
|
|
2
|
+
import re
|
|
3
|
+
import subprocess
|
|
4
|
+
from datetime import datetime, timedelta
|
|
5
|
+
|
|
6
|
+
HISTORY_RANGES = {"1 week": 7, "1 month": 30, "4 months": 120, "1 year": 365}
|
|
7
|
+
MISSING = ("", "N/A", "None", "nan", "(null)") # always sorted last, in either direction
|
|
8
|
+
DURATION = re.compile(r"(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)") # Slurm times: [D-][HH:]MM:SS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def run(cmd):
|
|
12
|
+
return subprocess.check_output(cmd, text=True)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_squeue(only_mine=True, only_running=False, run=run):
|
|
16
|
+
fields = [
|
|
17
|
+
"JOBID:18",
|
|
18
|
+
"USERNAME:10",
|
|
19
|
+
"PRIORITY:8",
|
|
20
|
+
"PARTITION:80",
|
|
21
|
+
"NAME:200",
|
|
22
|
+
"STATE:8",
|
|
23
|
+
"TimeUsed:10",
|
|
24
|
+
"StartTime:30",
|
|
25
|
+
"TimeLimit:15",
|
|
26
|
+
"tres-alloc:100",
|
|
27
|
+
"ReasonList:100",
|
|
28
|
+
]
|
|
29
|
+
cmd = ["squeue", f"--Format={'|,'.join(fields)}", "-S", "T"]
|
|
30
|
+
if only_mine:
|
|
31
|
+
cmd.append("--me")
|
|
32
|
+
if only_running:
|
|
33
|
+
cmd.append("--state=RUNNING")
|
|
34
|
+
columns, rows = parse_table(run(cmd), sep="|")
|
|
35
|
+
if rows:
|
|
36
|
+
width = max(len(row["TIME"]) for row in rows) # right-align the elapsed time
|
|
37
|
+
for row in rows:
|
|
38
|
+
row["TIME"] = row["TIME"].rjust(width)
|
|
39
|
+
row["START_TIME"] = simplify_start_time(row["START_TIME"])
|
|
40
|
+
return columns, rows
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_sinfo(run=run):
|
|
44
|
+
fields = [
|
|
45
|
+
"Partition:25",
|
|
46
|
+
"NodeHost",
|
|
47
|
+
"Gres:500",
|
|
48
|
+
"GresUsed:500",
|
|
49
|
+
"StateCompact",
|
|
50
|
+
"FreeMem",
|
|
51
|
+
"Memory",
|
|
52
|
+
"CPUsState",
|
|
53
|
+
"Features:200",
|
|
54
|
+
]
|
|
55
|
+
_, table = parse_table(run(["sinfo", "-O", ",".join(fields)]), sep=None)
|
|
56
|
+
|
|
57
|
+
records, hosts = [], set()
|
|
58
|
+
for row in table:
|
|
59
|
+
if row["GRES"] == "(null)":
|
|
60
|
+
continue
|
|
61
|
+
device, ngpus = parse_gres(row["GRES"])
|
|
62
|
+
gpu_avail_idx = parse_gres_used(row["GRES_USED"], ngpus) if row["STATE"] in ["mix", "idle", "alloc"] else []
|
|
63
|
+
_, ncpus_avail, _, ncpus_total = row["CPUS(A/I/O/T)"].split("/")
|
|
64
|
+
host_info = {
|
|
65
|
+
"Partition": row["PARTITION"],
|
|
66
|
+
"Host": row["HOSTNAMES"],
|
|
67
|
+
"Device": str(device),
|
|
68
|
+
"State": row["STATE"],
|
|
69
|
+
"Mem (GB)": f"{mem_gb(row['FREE_MEM'])}/{mem_gb(row['MEMORY'])}",
|
|
70
|
+
"CPUs": f"{ncpus_avail}/{ncpus_total}",
|
|
71
|
+
"GPUs (Total)": ngpus,
|
|
72
|
+
"GPUs (Avail)": len(gpu_avail_idx),
|
|
73
|
+
"GPUs": f"{len(gpu_avail_idx)}/{ngpus}",
|
|
74
|
+
"GPUs (Avail IDX)": f"[{','.join(map(str, gpu_avail_idx))}]",
|
|
75
|
+
}
|
|
76
|
+
# named features ("name:value") get their own column
|
|
77
|
+
unnamed_features = []
|
|
78
|
+
for feature in row["AVAIL_FEATURES"].split(","):
|
|
79
|
+
name, sep, value = feature.partition(":")
|
|
80
|
+
if sep:
|
|
81
|
+
host_info[name] = value
|
|
82
|
+
else:
|
|
83
|
+
unnamed_features.append(feature)
|
|
84
|
+
host_info["Feature"] = ",".join(unnamed_features)
|
|
85
|
+
if host_info["Host"] not in hosts: # a node listed in several partitions appears once
|
|
86
|
+
hosts.add(host_info["Host"])
|
|
87
|
+
records.append(host_info)
|
|
88
|
+
|
|
89
|
+
# columns in order of first appearance; a node without a named feature shows it empty
|
|
90
|
+
columns = list(dict.fromkeys(key for record in records for key in record))
|
|
91
|
+
for record in records:
|
|
92
|
+
for column in columns:
|
|
93
|
+
record.setdefault(column, "")
|
|
94
|
+
return columns, records
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_sacct(history_range="1 week", endtime="now", run=run):
|
|
98
|
+
days = HISTORY_RANGES.get(history_range)
|
|
99
|
+
starttime = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d") if days else "2024-11-26"
|
|
100
|
+
fields = "JobID,JobName,State,Start,Elapsed,NodeList,AllocTRES,Partition,StdOut"
|
|
101
|
+
output = run(["sacct", f"--format={fields}", "-P", "-X", f"--starttime={starttime}", f"--endtime={endtime}"])
|
|
102
|
+
return parse_table(output, sep="|")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def query(table, options, run=run):
|
|
106
|
+
"""Rows for one tab: returns (columns, rows as dicts, stats)."""
|
|
107
|
+
if table == "job":
|
|
108
|
+
columns, rows = get_squeue(options["only_my_jobs"], options["only_running_jobs"], run=run)
|
|
109
|
+
stats = {"njobs": len(rows), "njobs_running": sum(row["STATE"] == "RUNNING" for row in rows)}
|
|
110
|
+
elif table == "node":
|
|
111
|
+
columns, rows = get_sinfo(run=run)
|
|
112
|
+
stats = {"ngpus": sum(row["GPUs (Total)"] for row in rows),
|
|
113
|
+
"ngpus_avail": sum(row["GPUs (Avail)"] for row in rows)}
|
|
114
|
+
if options["only_available_nodes"]:
|
|
115
|
+
rows = [row for row in rows if row["GPUs (Avail)"] > 0]
|
|
116
|
+
columns = [c for c in columns if c not in ("GPUs (Total)", "GPUs (Avail)")] # hide for simplicity
|
|
117
|
+
else:
|
|
118
|
+
columns, rows = get_sacct(options["history_range"], run=run)
|
|
119
|
+
stats = {"nhistory": len(rows)}
|
|
120
|
+
if options["only_completed_history"]:
|
|
121
|
+
rows = [row for row in rows if row["State"] == "COMPLETED"]
|
|
122
|
+
stats["nhistory_completed"] = len(rows)
|
|
123
|
+
return columns, rows, stats
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def log_path(job_id, from_history, run=run):
|
|
127
|
+
"""Where a job writes its standard output."""
|
|
128
|
+
if from_history:
|
|
129
|
+
output = run(["sacct", "-j", job_id, "--format=StdOut", "-P"])
|
|
130
|
+
return output.split("\n")[1].strip().replace("%j", job_id)
|
|
131
|
+
match = re.search(r"StdOut=(\S+)", run(["scontrol", "show", "job", job_id]))
|
|
132
|
+
if not match:
|
|
133
|
+
raise RuntimeError(f"StdOut not found for job {job_id}")
|
|
134
|
+
return match.group(1)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_table(text, sep="|"):
|
|
138
|
+
"""Parse command output with a header line into (columns, rows as dicts of stripped strings).
|
|
139
|
+
|
|
140
|
+
`sep=None` splits on runs of whitespace. A trailing separator on every line does not create an
|
|
141
|
+
extra column.
|
|
142
|
+
"""
|
|
143
|
+
lines = [line for line in text.splitlines() if line.strip()]
|
|
144
|
+
if not lines:
|
|
145
|
+
return [], []
|
|
146
|
+
split = (lambda line: line.split()) if sep is None else (lambda line: [f.strip() for f in line.split(sep)])
|
|
147
|
+
columns = split(lines[0])
|
|
148
|
+
while columns and columns[-1] == "":
|
|
149
|
+
columns.pop()
|
|
150
|
+
rows = []
|
|
151
|
+
for line in lines[1:]:
|
|
152
|
+
values = split(line)
|
|
153
|
+
values += [""] * (len(columns) - len(values))
|
|
154
|
+
rows.append(dict(zip(columns, values)))
|
|
155
|
+
return columns, rows
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def sort_key(value):
|
|
159
|
+
"""Durations by length, numbers by value (job IDs, priorities, '18/20'), then text; numbers first."""
|
|
160
|
+
text = str(value).strip()
|
|
161
|
+
duration = DURATION.fullmatch(text)
|
|
162
|
+
if duration:
|
|
163
|
+
days, hours, minutes, seconds = (int(g or 0) for g in duration.groups())
|
|
164
|
+
return (0, ((days * 24 + hours) * 60 + minutes) * 60 + seconds, text)
|
|
165
|
+
try:
|
|
166
|
+
return (0, float(text), text)
|
|
167
|
+
except ValueError:
|
|
168
|
+
pass
|
|
169
|
+
match = re.match(r"\d+(\.\d+)?", text)
|
|
170
|
+
return (0, float(match.group()), text) if match else (1, 0.0, text)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def sort_rows(rows, column, ascending):
|
|
174
|
+
"""Sort rows (dicts, or lists with an integer `column`); values in MISSING go last either way."""
|
|
175
|
+
present = [row for row in rows if str(row[column]).strip() not in MISSING]
|
|
176
|
+
missing = [row for row in rows if str(row[column]).strip() in MISSING]
|
|
177
|
+
return sorted(present, key=lambda row: sort_key(row[column]), reverse=not ascending) + missing
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def parse_gres(gres_str):
|
|
181
|
+
match = re.match(r"([^:]+)(?::([^:()]+))?:([^:(,]+)(?:\(S:([^)]+)\))?", gres_str)
|
|
182
|
+
if not match:
|
|
183
|
+
raise ValueError(f"Error parsing gres: {gres_str}")
|
|
184
|
+
_, device, ngpus, _ = match.groups()
|
|
185
|
+
return device, int(ngpus)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def parse_gres_used(gres_used_str, num_total):
|
|
189
|
+
"""Return the indices of the GPUs that are not in use."""
|
|
190
|
+
match = re.match(r"([^:]+)(?::([^:]+))?:([^:(,]+)(?:\(IDX:([^)]+)\))?", gres_used_str)
|
|
191
|
+
if not match:
|
|
192
|
+
raise ValueError(f"Error parsing gres_used: {gres_used_str}")
|
|
193
|
+
_, _, ngpus_used, alloc_str = match.groups()
|
|
194
|
+
gpu_used_idx = set()
|
|
195
|
+
if alloc_str:
|
|
196
|
+
for gpu_ids in alloc_str.split(","):
|
|
197
|
+
if gpu_ids == "N/A":
|
|
198
|
+
continue
|
|
199
|
+
start, _, end = gpu_ids.partition("-")
|
|
200
|
+
gpu_used_idx.update(range(int(start), int(end or start) + 1))
|
|
201
|
+
assert int(ngpus_used) == len(gpu_used_idx), \
|
|
202
|
+
f"Number of used GPUs {ngpus_used} does not match parsed indices {gpu_used_idx} in gres_used: {gres_used_str}"
|
|
203
|
+
return [idx for idx in range(num_total) if idx not in gpu_used_idx]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def mem_gb(mem_mb):
|
|
207
|
+
try:
|
|
208
|
+
return int(mem_mb) // 1024
|
|
209
|
+
except (TypeError, ValueError):
|
|
210
|
+
return mem_mb
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def simplify_start_time(start_time):
|
|
214
|
+
"""Remove the year from a start time"""
|
|
215
|
+
try:
|
|
216
|
+
return datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S").strftime("%m-%d %H:%M")
|
|
217
|
+
except (TypeError, ValueError):
|
|
218
|
+
return start_time
|
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
"""Curses terminal UI for Slurm: jobs, GPUs and history; logs open in less."""
|
|
2
|
+
import curses
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import locale
|
|
5
|
+
import os
|
|
6
|
+
import signal
|
|
7
|
+
import socket
|
|
8
|
+
import subprocess
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import traceback
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
|
|
14
|
+
from . import data
|
|
15
|
+
|
|
16
|
+
ERROR_LOG_PATH = os.path.expanduser("~/.slurme_error.log")
|
|
17
|
+
HOSTNAME = socket.gethostname()
|
|
18
|
+
TABLES = ("job", "node", "history")
|
|
19
|
+
TAB_ORDER = ("node", "history", "job")
|
|
20
|
+
MAX_COL_WIDTH = 60
|
|
21
|
+
|
|
22
|
+
# Colour themes. Each element: (fg, bg) in the 256-colour palette, (fg, bg) for 8-colour terminals,
|
|
23
|
+
# and extra attributes. -1 is the terminal's default colour.
|
|
24
|
+
B, U, R = curses.A_BOLD, curses.A_UNDERLINE, curses.A_REVERSE
|
|
25
|
+
K8, R8, G8, Y8, BL8, M8, C8, W8 = range(8)
|
|
26
|
+
THEMES = {
|
|
27
|
+
"slate": {
|
|
28
|
+
"title": ((255, 24), (W8, BL8), B), "tab": ((250, -1), (-1, -1), 0), "tab_active": ((16, 110), (K8, C8), B),
|
|
29
|
+
"header": ((110, -1), (C8, -1), B | U), "header_cursor": ((16, 110), (K8, C8), B),
|
|
30
|
+
"cursor": ((255, 238), (-1, -1), R), "selected": ((16, 179), (K8, Y8), 0),
|
|
31
|
+
"selected_cursor": ((16, 214), (K8, Y8), B | U), "key": ((16, 110), (K8, C8), B),
|
|
32
|
+
"label": ((250, 236), (-1, -1), 0), "border": ((240, -1), (BL8, -1), 0), "error": ((203, -1), (R8, -1), B),
|
|
33
|
+
},
|
|
34
|
+
"frost": {
|
|
35
|
+
"title": ((236, 152), (K8, C8), B), "tab": ((250, -1), (-1, -1), 0), "tab_active": ((236, 109), (K8, C8), B),
|
|
36
|
+
"header": ((109, -1), (C8, -1), B | U), "header_cursor": ((236, 109), (K8, C8), B),
|
|
37
|
+
"cursor": ((255, 60), (W8, BL8), 0), "selected": ((236, 151), (K8, G8), 0),
|
|
38
|
+
"selected_cursor": ((236, 115), (K8, G8), B | U), "key": ((236, 109), (K8, C8), B),
|
|
39
|
+
"label": ((250, 237), (-1, -1), 0), "border": ((60, -1), (BL8, -1), 0), "error": ((174, -1), (R8, -1), B),
|
|
40
|
+
},
|
|
41
|
+
"classic": {
|
|
42
|
+
"title": ((231, 238), (W8, K8), B), "tab": ((248, -1), (-1, -1), 0), "tab_active": ((231, 25), (W8, BL8), B | U),
|
|
43
|
+
"header": ((222, -1), (Y8, -1), B), "header_cursor": ((16, 222), (K8, Y8), B),
|
|
44
|
+
"cursor": ((231, 25), (W8, BL8), 0), "selected": ((16, 172), (K8, Y8), B),
|
|
45
|
+
"selected_cursor": ((16, 208), (K8, Y8), B | U), "key": ((16, 222), (K8, Y8), B),
|
|
46
|
+
"label": ((252, 236), (-1, -1), 0), "border": ((242, -1), (-1, -1), 0), "error": ((196, -1), (R8, -1), B),
|
|
47
|
+
},
|
|
48
|
+
"light": {
|
|
49
|
+
"title": ((255, 25), (W8, BL8), B), "tab": ((240, -1), (-1, -1), 0), "tab_active": ((255, 25), (W8, BL8), B),
|
|
50
|
+
"header": ((25, -1), (BL8, -1), B | U), "header_cursor": ((255, 25), (W8, BL8), B),
|
|
51
|
+
"cursor": ((16, 153), (K8, C8), 0), "selected": ((16, 222), (K8, Y8), 0),
|
|
52
|
+
"selected_cursor": ((16, 214), (K8, Y8), B | U), "key": ((255, 25), (W8, BL8), B),
|
|
53
|
+
"label": ((238, 254), (-1, -1), 0), "border": ((245, -1), (-1, -1), 0), "error": ((160, -1), (R8, -1), B),
|
|
54
|
+
},
|
|
55
|
+
"mono": {
|
|
56
|
+
"title": (None, None, R | B), "tab": (None, None, 0), "tab_active": (None, None, R | B),
|
|
57
|
+
"header": (None, None, B | U), "header_cursor": (None, None, R | B), "cursor": (None, None, R),
|
|
58
|
+
"selected": (None, None, B | U), "selected_cursor": (None, None, R | B | U), "key": (None, None, R | B),
|
|
59
|
+
"label": (None, None, 0), "border": (None, None, curses.A_DIM), "error": (None, None, B),
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
DEFAULT_THEME = "classic"
|
|
63
|
+
|
|
64
|
+
# stages in which each action is allowed (actions not listed are always allowed)
|
|
65
|
+
ACTION_STAGES = {
|
|
66
|
+
"display_nodes": TABLES,
|
|
67
|
+
"display_history_jobs": TABLES,
|
|
68
|
+
"display_jobs": TABLES,
|
|
69
|
+
"select": ("job", "select"),
|
|
70
|
+
"select_inverse": ("job", "select"),
|
|
71
|
+
"refresh": TABLES,
|
|
72
|
+
"confirm": ("delete",),
|
|
73
|
+
"sort": TABLES,
|
|
74
|
+
"delete": ("job", "select"),
|
|
75
|
+
"print_gpustat": ("job",),
|
|
76
|
+
"open_shell": ("job",),
|
|
77
|
+
"open_log": ("job", "history"),
|
|
78
|
+
"toggle_user_range": ("job",),
|
|
79
|
+
"toggle_history_range": ("history",),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
# (key, action, label) as shown in the footer
|
|
83
|
+
BINDINGS = [
|
|
84
|
+
("g", "display_nodes", "GPUs"),
|
|
85
|
+
("h", "display_history_jobs", "History"),
|
|
86
|
+
("j", "display_jobs", "Jobs"),
|
|
87
|
+
("q", "abort", "Back/Quit"),
|
|
88
|
+
("space", "select", "Select"),
|
|
89
|
+
("v", "select_inverse", "Inverse"),
|
|
90
|
+
("r", "refresh", "Refresh"),
|
|
91
|
+
("enter", "confirm", "Confirm"),
|
|
92
|
+
("s", "sort", "Sort"),
|
|
93
|
+
("d", "delete", "Delete"),
|
|
94
|
+
("l", "open_log", "Log"),
|
|
95
|
+
("G", "print_gpustat", "GPU"),
|
|
96
|
+
("S", "open_shell", "Shell"),
|
|
97
|
+
("J", "toggle_user_range", "Users"),
|
|
98
|
+
("H", "toggle_history_range", "Range"),
|
|
99
|
+
("T", "cycle_theme", "Theme"),
|
|
100
|
+
]
|
|
101
|
+
KEYS = {(" " if key == "space" else "\n" if key == "enter" else key): action for key, action, _ in BINDINGS}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def version():
|
|
105
|
+
try:
|
|
106
|
+
return importlib.metadata.version("slurme")
|
|
107
|
+
except importlib.metadata.PackageNotFoundError:
|
|
108
|
+
return "dev"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Slurme:
|
|
112
|
+
def __init__(self, scr, verbose=False, interval=10, history_range="1 week", theme=None):
|
|
113
|
+
self.scr, self.verbose, self.interval = scr, verbose, interval
|
|
114
|
+
self.options = {"only_my_jobs": True, "only_running_jobs": False, "only_available_nodes": True,
|
|
115
|
+
"only_completed_history": False, "history_range": history_range}
|
|
116
|
+
self.action, self.active = "job", "job" # current stage, and the tab on screen
|
|
117
|
+
self.sort = {"job": None, "node": None, "history": (0, False)} # (column, ascending)
|
|
118
|
+
self.data = {t: ([], []) for t in TABLES} # columns, rows as lists of strings (unsorted)
|
|
119
|
+
self.view = {t: [] for t in TABLES} # rows in display order
|
|
120
|
+
self.loaded = set()
|
|
121
|
+
self.cursor = {t: [0, 0] for t in TABLES} # row, column
|
|
122
|
+
self.top = {t: 0 for t in TABLES}
|
|
123
|
+
self.left = {t: 0 for t in TABLES}
|
|
124
|
+
self.stats = {}
|
|
125
|
+
self.selected, self.delete_ids = [], ""
|
|
126
|
+
self.info, self.info_lock = [], threading.Lock()
|
|
127
|
+
self.lock, self.busy, self.again, self.incoming = threading.Lock(), set(), set(), {}
|
|
128
|
+
self.last_auto = time.time()
|
|
129
|
+
self.theme = theme if theme in THEMES else DEFAULT_THEME
|
|
130
|
+
self.style = {}
|
|
131
|
+
self.version = version()
|
|
132
|
+
|
|
133
|
+
# ------------------------------------------------------------------ messages and errors
|
|
134
|
+
def write(self, message):
|
|
135
|
+
with self.info_lock:
|
|
136
|
+
self.info.extend(str(message).splitlines() or [""])
|
|
137
|
+
del self.info[:-500]
|
|
138
|
+
|
|
139
|
+
def error(self, where, exc):
|
|
140
|
+
message = f"[{datetime.now():%Y-%m-%d %H:%M:%S}] Error ({where}): {exc}"
|
|
141
|
+
self.write(message)
|
|
142
|
+
try:
|
|
143
|
+
with open(ERROR_LOG_PATH, "a", encoding="utf-8") as f:
|
|
144
|
+
f.write(message + "\n" + traceback.format_exc() + "\n")
|
|
145
|
+
except OSError:
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
def run(self, cmd, timeout=None):
|
|
149
|
+
"""Run a command; its error output goes to the info panel, never onto the screen."""
|
|
150
|
+
if self.verbose:
|
|
151
|
+
self.write(" ".join(cmd))
|
|
152
|
+
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
153
|
+
if p.returncode:
|
|
154
|
+
detail = p.stderr.strip().splitlines()[-1] if p.stderr.strip() else f"exit code {p.returncode}"
|
|
155
|
+
raise RuntimeError(f"{' '.join(cmd[:3])} ...: {detail}")
|
|
156
|
+
return p.stdout
|
|
157
|
+
|
|
158
|
+
# ------------------------------------------------------------------ data
|
|
159
|
+
def fetch(self, table):
|
|
160
|
+
"""Query a table in a background thread; the main loop applies the result."""
|
|
161
|
+
with self.lock:
|
|
162
|
+
if table in self.busy:
|
|
163
|
+
self.again.add(table) # filters changed while a query runs: query once more after it
|
|
164
|
+
return
|
|
165
|
+
self.busy.add(table)
|
|
166
|
+
threading.Thread(target=self._fetch, args=(table,), daemon=True).start()
|
|
167
|
+
|
|
168
|
+
def _fetch(self, table):
|
|
169
|
+
try:
|
|
170
|
+
columns, rows, stats = data.query(table, dict(self.options), run=self.run)
|
|
171
|
+
cells = [[str(row[c]) for c in columns] for row in rows]
|
|
172
|
+
with self.lock:
|
|
173
|
+
self.incoming[table] = (columns, cells)
|
|
174
|
+
self.stats.update(stats)
|
|
175
|
+
except Exception as e: # keep the UI alive
|
|
176
|
+
self.error(f"query {table}", e)
|
|
177
|
+
finally:
|
|
178
|
+
with self.lock:
|
|
179
|
+
self.busy.discard(table)
|
|
180
|
+
again = table in self.again
|
|
181
|
+
self.again.discard(table)
|
|
182
|
+
if again:
|
|
183
|
+
self.fetch(table)
|
|
184
|
+
|
|
185
|
+
def apply_incoming(self):
|
|
186
|
+
with self.lock:
|
|
187
|
+
incoming, self.incoming = self.incoming, {}
|
|
188
|
+
for table, (columns, cells) in incoming.items():
|
|
189
|
+
key = self.current_key(table)
|
|
190
|
+
self.data[table] = (columns, cells)
|
|
191
|
+
self.loaded.add(table)
|
|
192
|
+
self.resort(table, keep=key)
|
|
193
|
+
return bool(incoming)
|
|
194
|
+
|
|
195
|
+
def resort(self, table, keep=None):
|
|
196
|
+
columns, cells = self.data[table]
|
|
197
|
+
order = self.sort[table]
|
|
198
|
+
if order and columns:
|
|
199
|
+
cells = data.sort_rows(cells, min(order[0], len(columns) - 1), order[1])
|
|
200
|
+
self.view[table] = cells
|
|
201
|
+
cur = self.cursor[table]
|
|
202
|
+
if keep is not None: # stay on the same job/node when rows move
|
|
203
|
+
for i, row in enumerate(cells):
|
|
204
|
+
if row and row[0] == keep:
|
|
205
|
+
cur[0] = i
|
|
206
|
+
break
|
|
207
|
+
cur[0] = max(0, min(cur[0], len(cells) - 1))
|
|
208
|
+
cur[1] = max(0, min(cur[1], len(columns) - 1))
|
|
209
|
+
|
|
210
|
+
def current_key(self, table):
|
|
211
|
+
rows = self.view[table]
|
|
212
|
+
row = self.cursor[table][0]
|
|
213
|
+
return rows[row][0] if 0 <= row < len(rows) and rows[row] else None
|
|
214
|
+
|
|
215
|
+
def current_job(self):
|
|
216
|
+
job = self.current_key(self.active)
|
|
217
|
+
if job is None:
|
|
218
|
+
raise RuntimeError("no job under the cursor")
|
|
219
|
+
return job
|
|
220
|
+
|
|
221
|
+
# ------------------------------------------------------------------ drawing
|
|
222
|
+
def setup_colors(self):
|
|
223
|
+
theme = THEMES[self.theme]
|
|
224
|
+
colors = curses.has_colors() and self.theme != "mono"
|
|
225
|
+
if colors:
|
|
226
|
+
curses.start_color()
|
|
227
|
+
try:
|
|
228
|
+
curses.use_default_colors()
|
|
229
|
+
default = -1
|
|
230
|
+
except curses.error:
|
|
231
|
+
default = curses.COLOR_BLACK
|
|
232
|
+
rich = curses.COLORS >= 256
|
|
233
|
+
for i, (name, (c256, c8, extra)) in enumerate(theme.items(), 1):
|
|
234
|
+
if colors and c256 is not None:
|
|
235
|
+
fg, bg = c256 if rich else c8
|
|
236
|
+
curses.init_pair(i, default if fg == -1 else fg, default if bg == -1 else bg)
|
|
237
|
+
self.style[name] = curses.color_pair(i) | extra
|
|
238
|
+
else: # no colours: every theme looks like mono, so cursor and selection stay visible
|
|
239
|
+
self.style[name] = THEMES["mono"][name][2]
|
|
240
|
+
|
|
241
|
+
def put(self, y, x, text, attr=0):
|
|
242
|
+
H, W = self.scr.getmaxyx()
|
|
243
|
+
if 0 <= y < H and 0 <= x < W:
|
|
244
|
+
try:
|
|
245
|
+
self.scr.addnstr(y, x, text, W - x - (1 if y == H - 1 else 0), attr)
|
|
246
|
+
except curses.error:
|
|
247
|
+
pass
|
|
248
|
+
|
|
249
|
+
def bar(self, y, attr):
|
|
250
|
+
"""Paint a full-width background line."""
|
|
251
|
+
W = self.scr.getmaxyx()[1]
|
|
252
|
+
self.put(y, 0, " " * W, attr)
|
|
253
|
+
|
|
254
|
+
def draw(self):
|
|
255
|
+
scr = self.scr
|
|
256
|
+
scr.erase()
|
|
257
|
+
H, W = scr.getmaxyx()
|
|
258
|
+
st = self.style
|
|
259
|
+
# title bar: name centred, host and clock on the right
|
|
260
|
+
self.bar(0, st["title"])
|
|
261
|
+
title = f"Slurme v{self.version}"
|
|
262
|
+
self.put(0, max(0, (W - len(title)) // 2), title, st["title"])
|
|
263
|
+
clock = f"{HOSTNAME} | {datetime.now():%H:%M:%S} "
|
|
264
|
+
if len(clock) + len(title) + 4 < W:
|
|
265
|
+
self.put(0, W - len(clock), clock, st["title"])
|
|
266
|
+
# tabs, centred
|
|
267
|
+
s = self.stats
|
|
268
|
+
labels = {"node": f"GPUs: {s.get('ngpus_avail', 0)}/{s.get('ngpus', 0)}",
|
|
269
|
+
"history": f"History: {s.get('nhistory_completed', 0)}/{s.get('nhistory', 0)}",
|
|
270
|
+
"job": f"Jobs: {s.get('njobs_running', 0)}/{s.get('njobs', 0)}"}
|
|
271
|
+
parts = [f" {labels[tab]} " for tab in TAB_ORDER]
|
|
272
|
+
x = max(0, (W - sum(len(p) for p in parts) - 2 * (len(parts) - 1)) // 2)
|
|
273
|
+
for tab, part in zip(TAB_ORDER, parts):
|
|
274
|
+
self.put(1, x, part, st["tab_active"] if tab == self.active else st["tab"])
|
|
275
|
+
x += len(part) + 2
|
|
276
|
+
# table, info panel, footer
|
|
277
|
+
footer_y = H - 1
|
|
278
|
+
info_h = max(3, H // 5)
|
|
279
|
+
info_y = footer_y - info_h - 1
|
|
280
|
+
position = self.draw_table(self.active, 3, info_y - 1) or ""
|
|
281
|
+
border = "-- Info " + "-" * max(0, W - 9 - len(position) - 2) + position + "--"
|
|
282
|
+
self.put(info_y, 0, border, st["border"])
|
|
283
|
+
with self.info_lock:
|
|
284
|
+
lines = self.info[-info_h:]
|
|
285
|
+
for i, line in enumerate(lines):
|
|
286
|
+
self.put(info_y + 1 + i, 1, line, st["error"] if "Error (" in line else 0)
|
|
287
|
+
self.draw_footer(footer_y)
|
|
288
|
+
scr.refresh()
|
|
289
|
+
|
|
290
|
+
def draw_table(self, table, y0, y1):
|
|
291
|
+
"""Header at y0, rows from y0+1 to y1 (inclusive). Returns a 'row n/N' label."""
|
|
292
|
+
H, W = self.scr.getmaxyx()
|
|
293
|
+
st = self.style
|
|
294
|
+
columns, _ = self.data[table]
|
|
295
|
+
rows = self.view[table]
|
|
296
|
+
if not columns:
|
|
297
|
+
self.put(y0 + 1, 2, "loading..." if table not in self.loaded else "(nothing to show)", curses.A_DIM)
|
|
298
|
+
return ""
|
|
299
|
+
widths = [min(MAX_COL_WIDTH, max([len(c)] + [len(r[i]) for r in rows])) for i, c in enumerate(columns)]
|
|
300
|
+
row_cur, col_cur = self.cursor[table]
|
|
301
|
+
# horizontal scroll: keep the cursor column on screen
|
|
302
|
+
left = min(self.left[table], col_cur)
|
|
303
|
+
while left < col_cur and sum(w + 2 for w in widths[left:col_cur + 1]) > W - 1:
|
|
304
|
+
left += 1
|
|
305
|
+
self.left[table] = left
|
|
306
|
+
# vertical scroll
|
|
307
|
+
n = max(1, y1 - y0)
|
|
308
|
+
self.top[table] = max(0, min(max(self.top[table], row_cur - n + 1), row_cur))
|
|
309
|
+
|
|
310
|
+
def cell(text, width):
|
|
311
|
+
return text[:width - 1] + "~" if len(text) > width else text.ljust(width)
|
|
312
|
+
|
|
313
|
+
x = 1
|
|
314
|
+
for j in range(left, len(columns)):
|
|
315
|
+
self.put(y0, x, cell(columns[j], widths[j]), st["header_cursor"] if j == col_cur else st["header"])
|
|
316
|
+
x += widths[j] + 2
|
|
317
|
+
selected = set(self.selected) if table == "job" else set()
|
|
318
|
+
for i in range(self.top[table], min(len(rows), self.top[table] + n)):
|
|
319
|
+
y = y0 + 1 + i - self.top[table]
|
|
320
|
+
row = rows[i]
|
|
321
|
+
is_cur, is_sel = i == row_cur, row[0] in selected
|
|
322
|
+
style = (st["selected_cursor"] if is_sel and is_cur else st["selected"] if is_sel
|
|
323
|
+
else st["cursor"] if is_cur else 0)
|
|
324
|
+
if style:
|
|
325
|
+
self.bar(y, style) # the whole row, edge to edge
|
|
326
|
+
x = 1
|
|
327
|
+
for j in range(left, len(columns)):
|
|
328
|
+
self.put(y, x, cell(row[j], widths[j]), style | (curses.A_BOLD if is_cur and j == col_cur else 0))
|
|
329
|
+
x += widths[j] + 2
|
|
330
|
+
if not rows:
|
|
331
|
+
self.put(y0 + 1, 2, "(nothing to show)", curses.A_DIM)
|
|
332
|
+
return f" row {row_cur + 1}/{len(rows)} " if rows else ""
|
|
333
|
+
|
|
334
|
+
def draw_footer(self, y):
|
|
335
|
+
st = self.style
|
|
336
|
+
W = self.scr.getmaxyx()[1]
|
|
337
|
+
self.bar(y, st["label"])
|
|
338
|
+
x = 0
|
|
339
|
+
for key, action, label in BINDINGS:
|
|
340
|
+
if not self.allowed(action):
|
|
341
|
+
continue
|
|
342
|
+
if x + len(key) + len(label) + 4 >= W:
|
|
343
|
+
break
|
|
344
|
+
self.put(y, x, f" {key} ", st["key"])
|
|
345
|
+
self.put(y, x + len(key) + 2, f" {label} ", st["label"])
|
|
346
|
+
x += len(key) + len(label) + 4
|
|
347
|
+
theme = f" theme: {self.theme} "
|
|
348
|
+
if x + len(theme) < W - 1:
|
|
349
|
+
self.put(y, W - len(theme) - 1, theme, st["label"])
|
|
350
|
+
|
|
351
|
+
# ------------------------------------------------------------------ actions
|
|
352
|
+
def allowed(self, action):
|
|
353
|
+
stages = ACTION_STAGES.get(action)
|
|
354
|
+
return stages is None or self.action in stages
|
|
355
|
+
|
|
356
|
+
def tab_prompt(self, tab):
|
|
357
|
+
if not self.verbose:
|
|
358
|
+
with self.info_lock:
|
|
359
|
+
self.info.clear()
|
|
360
|
+
o = self.options
|
|
361
|
+
if tab == "node":
|
|
362
|
+
info = f"Press 'g' to toggle nodes: {'Available' if o['only_available_nodes'] else 'All'}"
|
|
363
|
+
elif tab == "history":
|
|
364
|
+
info = (f"Press 'h' to toggle job states: {'Completed' if o['only_completed_history'] else 'All'} | "
|
|
365
|
+
f"Press 'H' to toggle history range: {o['history_range']}")
|
|
366
|
+
else:
|
|
367
|
+
info = (f"Press 'j' to toggle job states: {'Running' if o['only_running_jobs'] else 'All'} | "
|
|
368
|
+
f"Press 'J' to toggle user range: {'Me' if o['only_my_jobs'] else 'All'}")
|
|
369
|
+
self.write(info)
|
|
370
|
+
|
|
371
|
+
def show_tab(self, tab, option):
|
|
372
|
+
if self.action == tab:
|
|
373
|
+
self.options[option] = not self.options[option]
|
|
374
|
+
self.action = self.active = tab
|
|
375
|
+
self.fetch(tab)
|
|
376
|
+
self.tab_prompt(tab)
|
|
377
|
+
|
|
378
|
+
def action_display_nodes(self):
|
|
379
|
+
self.show_tab("node", "only_available_nodes")
|
|
380
|
+
|
|
381
|
+
def action_display_history_jobs(self):
|
|
382
|
+
self.show_tab("history", "only_completed_history")
|
|
383
|
+
|
|
384
|
+
def action_display_jobs(self):
|
|
385
|
+
self.show_tab("job", "only_running_jobs")
|
|
386
|
+
|
|
387
|
+
def action_abort(self):
|
|
388
|
+
a = self.action
|
|
389
|
+
if a == "delete":
|
|
390
|
+
self.write("Delete: aborted")
|
|
391
|
+
self.selected, self.delete_ids = [], ""
|
|
392
|
+
elif a == "select":
|
|
393
|
+
self.write("Select: none")
|
|
394
|
+
self.selected = []
|
|
395
|
+
elif a in ("node", "history"):
|
|
396
|
+
self.active = "job"
|
|
397
|
+
self.tab_prompt("job")
|
|
398
|
+
elif a == "job":
|
|
399
|
+
raise SystemExit
|
|
400
|
+
self.action = self.active
|
|
401
|
+
self.fetch(self.active)
|
|
402
|
+
|
|
403
|
+
def report_selection(self):
|
|
404
|
+
if self.selected:
|
|
405
|
+
self.action = "select"
|
|
406
|
+
self.write(f"Select: {' '.join(self.selected)}")
|
|
407
|
+
else:
|
|
408
|
+
self.action = "job"
|
|
409
|
+
self.write("Select: none")
|
|
410
|
+
|
|
411
|
+
def toggle(self, job):
|
|
412
|
+
if job in self.selected:
|
|
413
|
+
self.selected.remove(job)
|
|
414
|
+
return False
|
|
415
|
+
self.selected.append(job)
|
|
416
|
+
return True
|
|
417
|
+
|
|
418
|
+
def action_select(self):
|
|
419
|
+
self.toggle(self.current_job())
|
|
420
|
+
self.report_selection()
|
|
421
|
+
self.move(1, 0)
|
|
422
|
+
|
|
423
|
+
def action_select_inverse(self):
|
|
424
|
+
for i, row in enumerate(self.view["job"]):
|
|
425
|
+
if self.toggle(row[0]):
|
|
426
|
+
self.cursor["job"][0] = i
|
|
427
|
+
self.report_selection()
|
|
428
|
+
|
|
429
|
+
def action_refresh(self):
|
|
430
|
+
self.fetch(self.action)
|
|
431
|
+
|
|
432
|
+
def action_confirm(self):
|
|
433
|
+
result = subprocess.run(["scancel", *self.delete_ids.split()], capture_output=True, text=True)
|
|
434
|
+
self.write(f"Delete: {self.delete_ids}? {'succeeded' if result.returncode == 0 else 'failed'}")
|
|
435
|
+
if result.stderr.strip():
|
|
436
|
+
self.write(result.stderr.strip())
|
|
437
|
+
self.selected, self.delete_ids = [], ""
|
|
438
|
+
self.action = "job"
|
|
439
|
+
self.fetch("job")
|
|
440
|
+
|
|
441
|
+
def action_sort(self):
|
|
442
|
+
table = self.action
|
|
443
|
+
column = self.cursor[table][1]
|
|
444
|
+
order = self.sort[table]
|
|
445
|
+
ascending = False if not order or order[0] != column else not order[1]
|
|
446
|
+
self.sort[table] = (column, ascending)
|
|
447
|
+
self.resort(table)
|
|
448
|
+
self.cursor[table][0] = 0
|
|
449
|
+
columns = self.data[table][0]
|
|
450
|
+
if columns:
|
|
451
|
+
self.write(f"Sort: {columns[column]} {'ascending' if ascending else 'descending'}")
|
|
452
|
+
|
|
453
|
+
def action_delete(self):
|
|
454
|
+
self.delete_ids = self.current_job() if self.action == "job" else " ".join(self.selected)
|
|
455
|
+
self.write(f"Delete: {self.delete_ids}? press <<ENTER>> to confirm, q to abort")
|
|
456
|
+
self.action = "delete"
|
|
457
|
+
|
|
458
|
+
def action_print_gpustat(self):
|
|
459
|
+
job = self.current_job()
|
|
460
|
+
|
|
461
|
+
def work():
|
|
462
|
+
try:
|
|
463
|
+
self.write(self.run(["srun", "--jobid", job, "--overlap", "gpustat"], timeout=3).rstrip())
|
|
464
|
+
except Exception as e:
|
|
465
|
+
self.error("gpustat", e)
|
|
466
|
+
threading.Thread(target=work, daemon=True).start()
|
|
467
|
+
self.write(f"gpustat on job {job} ...")
|
|
468
|
+
|
|
469
|
+
def outside(self, cmd):
|
|
470
|
+
"""Run an interactive command on the terminal, then return to the UI."""
|
|
471
|
+
curses.def_prog_mode()
|
|
472
|
+
curses.endwin()
|
|
473
|
+
original = signal.signal(signal.SIGINT, signal.SIG_IGN) # Ctrl-C goes to the command
|
|
474
|
+
try:
|
|
475
|
+
subprocess.run(cmd, preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_DFL))
|
|
476
|
+
finally:
|
|
477
|
+
signal.signal(signal.SIGINT, original)
|
|
478
|
+
curses.reset_prog_mode()
|
|
479
|
+
curses.curs_set(0)
|
|
480
|
+
self.scr.clear()
|
|
481
|
+
|
|
482
|
+
def action_open_shell(self):
|
|
483
|
+
self.outside(["srun", "--jobid", self.current_job(), "--overlap", "--pty", os.environ.get("SHELL", "bash")])
|
|
484
|
+
|
|
485
|
+
def action_open_log(self):
|
|
486
|
+
path = data.log_path(self.current_job(), self.action == "history", run=self.run)
|
|
487
|
+
if not os.path.exists(path):
|
|
488
|
+
raise FileNotFoundError(f"Log file not found: {path}")
|
|
489
|
+
self.outside(["less", "+G", path]) # in less: F follows new output, q returns
|
|
490
|
+
self.write(f"Log: {path}")
|
|
491
|
+
|
|
492
|
+
def action_toggle_user_range(self):
|
|
493
|
+
self.options["only_my_jobs"] = not self.options["only_my_jobs"]
|
|
494
|
+
self.fetch("job")
|
|
495
|
+
self.tab_prompt("job")
|
|
496
|
+
|
|
497
|
+
def action_toggle_history_range(self):
|
|
498
|
+
ranges = list(data.HISTORY_RANGES)
|
|
499
|
+
r = self.options["history_range"]
|
|
500
|
+
self.options["history_range"] = ranges[(ranges.index(r) + 1) % len(ranges) if r in ranges else 0]
|
|
501
|
+
self.fetch("history")
|
|
502
|
+
self.tab_prompt("history")
|
|
503
|
+
|
|
504
|
+
def action_cycle_theme(self):
|
|
505
|
+
names = list(THEMES)
|
|
506
|
+
self.theme = names[(names.index(self.theme) + 1) % len(names)]
|
|
507
|
+
self.setup_colors()
|
|
508
|
+
self.write(f"Theme: {self.theme} (start with it: slurme --theme {self.theme})")
|
|
509
|
+
|
|
510
|
+
# ------------------------------------------------------------------ input
|
|
511
|
+
def move(self, drow, dcol, absolute_row=None):
|
|
512
|
+
table = self.active
|
|
513
|
+
rows = self.view[table]
|
|
514
|
+
cur = self.cursor[table]
|
|
515
|
+
if absolute_row is not None:
|
|
516
|
+
cur[0] = absolute_row
|
|
517
|
+
cur[0] = max(0, min(cur[0] + drow, len(rows) - 1))
|
|
518
|
+
cur[1] = max(0, min(cur[1] + dcol, len(self.data[table][0]) - 1))
|
|
519
|
+
|
|
520
|
+
def navigate(self, k):
|
|
521
|
+
H, _ = self.scr.getmaxyx()
|
|
522
|
+
page = max(1, H - H // 5 - 8)
|
|
523
|
+
moves = {curses.KEY_UP: (-1, 0), curses.KEY_DOWN: (1, 0), curses.KEY_LEFT: (0, -1), curses.KEY_RIGHT: (0, 1),
|
|
524
|
+
curses.KEY_PPAGE: (-page, 0), curses.KEY_NPAGE: (page, 0)}
|
|
525
|
+
if k in moves:
|
|
526
|
+
self.move(*moves[k])
|
|
527
|
+
elif k == curses.KEY_HOME:
|
|
528
|
+
self.move(0, 0, absolute_row=0)
|
|
529
|
+
elif k == curses.KEY_END:
|
|
530
|
+
self.move(0, 0, absolute_row=len(self.view[self.active]) - 1)
|
|
531
|
+
else:
|
|
532
|
+
return False
|
|
533
|
+
return True
|
|
534
|
+
|
|
535
|
+
def handle(self, k):
|
|
536
|
+
if k in (3, 17): # Ctrl-C, Ctrl-Q
|
|
537
|
+
raise SystemExit
|
|
538
|
+
if k == curses.KEY_RESIZE or self.navigate(k):
|
|
539
|
+
return
|
|
540
|
+
key = "\n" if k in (curses.KEY_ENTER, 10, 13) else chr(k) if 0 <= k < 256 else None
|
|
541
|
+
action = KEYS.get(key)
|
|
542
|
+
if action and self.allowed(action):
|
|
543
|
+
try:
|
|
544
|
+
getattr(self, f"action_{action}")()
|
|
545
|
+
except SystemExit:
|
|
546
|
+
raise
|
|
547
|
+
except Exception as e:
|
|
548
|
+
self.error(action, e)
|
|
549
|
+
|
|
550
|
+
def loop(self):
|
|
551
|
+
curses.curs_set(0)
|
|
552
|
+
self.scr.keypad(True)
|
|
553
|
+
self.scr.timeout(100)
|
|
554
|
+
self.setup_colors()
|
|
555
|
+
for table in TABLES:
|
|
556
|
+
self.fetch(table)
|
|
557
|
+
self.tab_prompt("job")
|
|
558
|
+
last_draw = 0
|
|
559
|
+
while True:
|
|
560
|
+
changed = self.apply_incoming()
|
|
561
|
+
if changed or time.time() - last_draw > 1:
|
|
562
|
+
self.draw()
|
|
563
|
+
last_draw = time.time()
|
|
564
|
+
k = self.scr.getch()
|
|
565
|
+
if self.interval > 0 and time.time() - self.last_auto >= self.interval:
|
|
566
|
+
self.last_auto = time.time()
|
|
567
|
+
if self.action in ("job", "node"):
|
|
568
|
+
self.fetch(self.action)
|
|
569
|
+
if k == -1:
|
|
570
|
+
continue
|
|
571
|
+
try:
|
|
572
|
+
self.handle(k)
|
|
573
|
+
except SystemExit:
|
|
574
|
+
return
|
|
575
|
+
self.apply_incoming()
|
|
576
|
+
self.draw()
|
|
577
|
+
last_draw = time.time()
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def run_ui(verbose=False, interval=10, history_range="1 week", theme=None):
|
|
581
|
+
try:
|
|
582
|
+
locale.setlocale(locale.LC_ALL, "")
|
|
583
|
+
except locale.Error:
|
|
584
|
+
pass
|
|
585
|
+
os.environ.setdefault("ESCDELAY", "25")
|
|
586
|
+
theme = theme or os.environ.get("SLURME_THEME")
|
|
587
|
+
try:
|
|
588
|
+
curses.wrapper(lambda scr: Slurme(scr, verbose, interval, history_range, theme).loop())
|
|
589
|
+
except KeyboardInterrupt:
|
|
590
|
+
pass
|