Debian Codegraph @

src/sluurp/utils.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import subprocess
4 import platform as _platform_mod
5 from shutil import which
6
7
8 def has_sbatch_available(platform="Linux"):
9 return which("sbatch") is not None
10
11
12 def has_scancel_available():
13 return which("scancel") is not None
14
15
16 def has_scontrol_available():
17 return which("scontrol") is not None
18
19
20 def get_partitions() -> tuple:
21 """
22 return a list of existing partition
23 """
24 # sinfo -O partition
25 process = SubProcessCommand(command="sinfo -O partition")
26 try:
27 res = process.run()
28 except Exception:
29 pass
30 else:
31 return filter(
32 lambda x: x != "",
33 [str(line).replace(" ", "") for line in res.split("\n")],
34 )
35
36
37 def get_partition_gpus(partition: str) -> tuple:
38 """
39 return the available gpus of a partition.
40 Please keep in mind that the GRES synthax might evolve. So this function is
41 not expected to always work.
42 """
43 process = SubProcessCommand(command=f"sinfo --partition={partition} -o '%G'")
44 try:
45 res = process.run()
46 except Exception:
47 res = ()
48
49 gpus = filter(
50 lambda x: x.startswith("gpu:"),
51 res.split("\n"),
52 )
53 try:
54 return tuple([gpu.split(":")[1] for gpu in gpus])
55 except Exception:
56 return tuple()
57
58
59 def get_partition_walltime(partition: str) -> dict[str, str]:
60 """
61 Return for the given partition:
62 * time: walltime limit as HH:MM:SS
63 * default_time: default walltime as HH:MM:SS
64 """
65 process = SubProcessCommand(
66 command=f"sinfo --partition={partition} -O DefaultTime,Time"
67 )
68 try:
69 res = process.run()
70 except Exception:
71 return None, None
72
73 # treat output string
74 res = res.split("\n")
75 if len(res) < 1:
76 return None, None
77 else:
78 times = filter(lambda a: a, res[1].split(" "))
79 default_time, time = times
80 return {
81 "default_time": default_time,
82 "time": time,
83 }
84
85
86 class SubProcessCommand:
87 def __init__(self, command, platform="Linux"):
88 if platform != _platform_mod.system():
89 raise ValueError
90 self._command = command
91 self.raw_stdout = None
92 self.raw_stderr = None
93
94 def run(self):
95 stdout, stderr = self.launch_command()
96 self.raw_stdout = stdout.decode("utf-8")
97 self.raw_stderr = stderr.decode("utf-8")
98 return self.interpret_result(self.raw_stdout, self.raw_stderr)
99
100 def interpret_result(self, stdout, stderr):
101 return stdout
102
103 def launch_command(self):
104 process = subprocess.Popen(
105 self._command,
106 shell=True,
107 stdout=subprocess.PIPE,
108 stderr=subprocess.PIPE,
109 )
110 return process.communicate()
111
112 __call__ = run