giwon 0.1.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,326 @@
1
+ """Observe a node's CPUs, GPUs, memory and collecting-process affinity.
2
+
3
+ Slurm sends this file as Python source, so it uses only the standard library and
4
+ must run without the Giwon package. Scheduler GPU selectors are not device
5
+ observations; absent GPU facts do not imply no devices.
6
+ Explicit unavailable markers such as N/A are retained, including in numeric
7
+ fields; absent values are omitted rather than replaced with a marker.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import platform
13
+ import signal
14
+ import socket
15
+ import subprocess
16
+ import sys
17
+ import xml.etree.ElementTree as ET
18
+ from pathlib import Path
19
+
20
+ _NVIDIA_FIELDS = (
21
+ ("uuid", "uuid"),
22
+ ("product_name", "model"),
23
+ ("pci/pci_bus_id", "pci_bus_id"),
24
+ )
25
+ _AMD_FIELDS = (
26
+ ("asic", "market_name", "model"),
27
+ ("bus", "bdf", "pci_bus_id"),
28
+ ("driver", "version", "driver_version"),
29
+ )
30
+ _MAC_GPU_FIELDS = (
31
+ ("sppci_model", "model"),
32
+ ("spdisplays_device-id", "device_id"),
33
+ ("spdisplays_vendor-id", "vendor_id"),
34
+ ("spdisplays_metal", "metal_support"),
35
+ )
36
+
37
+
38
+ def _utility(*command):
39
+ return subprocess.run(
40
+ command,
41
+ stdin=subprocess.DEVNULL,
42
+ capture_output=True,
43
+ text=True,
44
+ timeout=3,
45
+ env=dict(os.environ, LC_ALL="C"),
46
+ check=True,
47
+ ).stdout
48
+
49
+
50
+ def _memory_bytes(value):
51
+ if value in (None, ""):
52
+ return None
53
+ if value == "N/A":
54
+ return value
55
+
56
+ amount, unit = value.split()
57
+ if amount == "N/A":
58
+ return amount
59
+
60
+ return int(float(amount) * {"MiB": 2**20, "MB": 10**6, "GB": 10**9}[unit])
61
+
62
+
63
+ def _nvidia_gpus():
64
+ """Observe NVIDIA devices, nesting MIG instances under their parent.
65
+
66
+ MIG compute instances can share a GPU instance's memory. Keep their reported
67
+ capacities under the parent with both instance IDs, rather than presenting
68
+ overlapping capacities as independent physical GPUs.
69
+ """
70
+ root = ET.fromstring(_utility("nvidia-smi", "--query", "--xml-format"))
71
+ if root.tag != "nvidia_smi_log":
72
+ raise ValueError("unexpected NVIDIA inventory")
73
+
74
+ gpus = []
75
+ for device in root.findall("gpu"):
76
+ gpu = {}
77
+ for source, key in _NVIDIA_FIELDS:
78
+ if (value := device.findtext(source)) not in (None, ""):
79
+ gpu[key] = value
80
+
81
+ if (driver := root.findtext("driver_version")) not in (None, ""):
82
+ gpu["driver_version"] = driver
83
+
84
+ memory = _memory_bytes(device.findtext("fb_memory_usage/total"))
85
+ if memory is not None:
86
+ gpu["memory_bytes"] = memory
87
+ if (mode := device.findtext("mig_mode/current_mig")) not in (None, ""):
88
+ gpu["mig_mode"] = mode
89
+
90
+ partitions = []
91
+ for device_partition in device.findall("mig_devices/mig_device"):
92
+ partition = {"kind": "mig"}
93
+ for key in ("gpu_instance_id", "compute_instance_id"):
94
+ value = device_partition.findtext(key)
95
+ if value not in (None, ""):
96
+ partition[key] = value if value == "N/A" else int(value)
97
+ memory = _memory_bytes(device_partition.findtext("fb_memory_usage/total"))
98
+ if memory is not None:
99
+ partition["memory_bytes"] = memory
100
+ partitions.append(partition)
101
+
102
+ if partitions:
103
+ gpu["partitions"] = partitions
104
+ if gpu:
105
+ gpus.append(gpu)
106
+
107
+ return gpus
108
+
109
+
110
+ def _amd_gpus():
111
+ output = _utility(
112
+ "amd-smi", "static", "--asic", "--bus", "--driver", "--vram", "--json"
113
+ )
114
+ rows = json.loads(output)["gpu_data"]
115
+ gpus = []
116
+ for row in rows:
117
+ gpu = {}
118
+ for section, source, key in _AMD_FIELDS:
119
+ if (value := row.get(section, {}).get(source)) not in (None, ""):
120
+ gpu[key] = value
121
+ size = row.get("vram", {}).get("size")
122
+ if isinstance(size, dict):
123
+ size = f"{size['value']} {size['unit']}"
124
+ memory = _memory_bytes(size)
125
+ if memory is not None:
126
+ gpu["memory_bytes"] = memory
127
+
128
+ if gpu:
129
+ gpus.append(gpu)
130
+
131
+ return gpus
132
+
133
+
134
+ def _mac_gpus():
135
+ """Observe Mac graphics devices without assigning unified RAM as VRAM.
136
+
137
+ Apple silicon shares system memory. System Profiler does not report dedicated
138
+ VRAM for it, so leave GPU capacity absent instead of duplicating system RAM.
139
+ """
140
+ output = _utility("system_profiler", "SPDisplaysDataType", "-json")
141
+ rows = json.loads(output)["SPDisplaysDataType"]
142
+ gpus = []
143
+ for row in rows:
144
+ gpu = {key: row[source] for source, key in _MAC_GPU_FIELDS if row.get(source)}
145
+ if cores := row.get("sppci_cores"):
146
+ gpu["cores"] = cores if cores == "N/A" else int(cores)
147
+ if (memory := _memory_bytes(row.get("spdisplays_vram"))) is not None:
148
+ gpu["memory_bytes"] = memory
149
+ if gpu:
150
+ gpus.append(gpu)
151
+
152
+ return gpus
153
+
154
+
155
+ def _linux_cpus():
156
+ rows = json.loads(
157
+ _utility(
158
+ "lscpu",
159
+ "--json",
160
+ "--extended=CPU,SOCKET,CORE,ONLINE,MODELNAME",
161
+ )
162
+ )["cpus"]
163
+ sockets = {}
164
+ for row in rows:
165
+ if row.get("online") in (False, "no") or row["socket"] in (None, "-"):
166
+ continue
167
+ socket_id = int(row["socket"])
168
+ sockets.setdefault(socket_id, []).append(row)
169
+
170
+ cpus = []
171
+ for socket_id, processors in sorted(sockets.items()):
172
+ cpu = {"socket": socket_id, "logical_cpus": len(processors)}
173
+ if all(row["core"] not in (None, "-") for row in processors):
174
+ cpu["cores"] = len({str(row["core"]) for row in processors})
175
+ models = {row.get("modelname") for row in processors}
176
+ if len(models) == 1 and next(iter(models)) not in (None, ""):
177
+ cpu["model"] = next(iter(models))
178
+ cpus.append(cpu)
179
+ return cpus
180
+
181
+
182
+ def _collect_linux():
183
+ facts: dict = {}
184
+ try:
185
+ for line in Path("/proc/meminfo").read_text().splitlines():
186
+ if line.startswith("MemTotal:"):
187
+ facts["memory_bytes"] = int(line.split()[1]) * 1024
188
+ break
189
+ except (OSError, ValueError, IndexError) as error:
190
+ print(f"giwon: unavailable memory: {error}", file=sys.stderr)
191
+
192
+ try:
193
+ if cpus := _linux_cpus():
194
+ facts["cpus"] = cpus
195
+ except (
196
+ OSError,
197
+ ValueError,
198
+ KeyError,
199
+ AttributeError,
200
+ TypeError,
201
+ subprocess.SubprocessError,
202
+ ) as error:
203
+ print(f"giwon: unavailable CPU topology: {error}", file=sys.stderr)
204
+
205
+ for name, collector in (("NVIDIA", _nvidia_gpus), ("AMD", _amd_gpus)):
206
+ try:
207
+ if gpus := collector():
208
+ facts.setdefault("gpus", []).extend(gpus)
209
+ except FileNotFoundError:
210
+ # Vendor tools need not be installed on nodes without that hardware.
211
+ pass
212
+ except (
213
+ OSError,
214
+ ValueError,
215
+ KeyError,
216
+ TypeError,
217
+ AttributeError,
218
+ ET.ParseError,
219
+ subprocess.SubprocessError,
220
+ ) as error:
221
+ print(f"giwon: unavailable {name} GPUs: {error}", file=sys.stderr)
222
+ return facts
223
+
224
+
225
+ def _collect_mac():
226
+ """Observe Mac hardware with native system utilities.
227
+
228
+ These sysctls report machine-wide counts and one model. Use them for a
229
+ socket only when hw.packages confirms one package; multiple packages need
230
+ per-socket observations rather than an assumed even split of the totals.
231
+ """
232
+ facts = {}
233
+ try:
234
+ if gpus := _mac_gpus():
235
+ facts["gpus"] = gpus
236
+ except (
237
+ OSError,
238
+ ValueError,
239
+ KeyError,
240
+ TypeError,
241
+ AttributeError,
242
+ subprocess.SubprocessError,
243
+ ) as error:
244
+ print(f"giwon: unavailable Mac GPUs: {error}", file=sys.stderr)
245
+
246
+ try:
247
+ output = _utility(
248
+ "sysctl",
249
+ "-i",
250
+ "hw.memsize",
251
+ "hw.packages",
252
+ "hw.physicalcpu",
253
+ "hw.logicalcpu",
254
+ "machdep.cpu.brand_string",
255
+ )
256
+ values = dict(line.split(":", 1) for line in output.splitlines())
257
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
258
+ print(f"giwon: unavailable memory and CPU topology: {error}", file=sys.stderr)
259
+ return facts
260
+
261
+ try:
262
+ facts["memory_bytes"] = int(values["hw.memsize"])
263
+ except (KeyError, ValueError) as error:
264
+ print(f"giwon: unavailable memory: {error}", file=sys.stderr)
265
+
266
+ try:
267
+ if int(values.get("hw.packages", "0")) != 1:
268
+ raise ValueError("sysctl CPU inventory requires one observed package")
269
+
270
+ cpu = {"socket": 0}
271
+ for source, key in (
272
+ ("hw.physicalcpu", "cores"),
273
+ ("hw.logicalcpu", "logical_cpus"),
274
+ ):
275
+ if source in values:
276
+ count = int(values[source])
277
+ if count <= 0:
278
+ raise ValueError(f"invalid CPU count from {source}")
279
+ cpu[key] = count
280
+ if model := values.get("machdep.cpu.brand_string", "").strip():
281
+ cpu["model"] = model
282
+ if len(cpu) > 1:
283
+ facts["cpus"] = [cpu]
284
+ except ValueError as error:
285
+ print(f"giwon: unavailable CPU topology: {error}", file=sys.stderr)
286
+ return facts
287
+
288
+
289
+ def collect() -> dict:
290
+ """Return hardware facts observed in the collecting process's environment.
291
+
292
+ Optional utilities can fail independently. Return the available observations
293
+ and report failures to stderr; omitted fields mean unknown information.
294
+ """
295
+ facts = {"scope": "local_process"}
296
+ try:
297
+ facts["hostname"] = socket.gethostname()
298
+ except OSError as error:
299
+ print(f"giwon: unavailable hostname: {error}", file=sys.stderr)
300
+
301
+ get_affinity = getattr(os, "sched_getaffinity", None)
302
+ if get_affinity is not None:
303
+ try:
304
+ facts["cpu_affinity"] = sorted(get_affinity(0))
305
+ except OSError as error:
306
+ print(f"giwon: unavailable CPU affinity: {error}", file=sys.stderr)
307
+
308
+ try:
309
+ system = platform.system()
310
+ except OSError as error:
311
+ print(f"giwon: unavailable hardware platform: {error}", file=sys.stderr)
312
+ return facts
313
+
314
+ if system == "Linux":
315
+ facts.update(_collect_linux())
316
+ elif system == "Darwin":
317
+ facts.update(_collect_mac())
318
+ return facts
319
+
320
+
321
+ if __name__ == "__main__":
322
+ signal.alarm(15)
323
+ print(
324
+ json.dumps({"node": os.environ.get("SLURMD_NODENAME"), "hardware": collect()}),
325
+ flush=True,
326
+ )
@@ -0,0 +1,119 @@
1
+ """Inspect a supplied image or one inferred from a simple container command.
2
+
3
+ A tag can resolve differently in local storage and a registry. Keep these
4
+ observations separate; neither establishes the image a future launch will use.
5
+ """
6
+
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ from collections.abc import Mapping, Sequence
11
+ from pathlib import Path
12
+
13
+ from giwon import hashing
14
+ from giwon.discovery import docker
15
+
16
+
17
+ def detect(command: Sequence[str], executable: str | None) -> str | None:
18
+ """Best-effort image detection from a direct launch with an obvious operand.
19
+
20
+ Launcher options have different arities. Rather than maintain their parsers,
21
+ recognize bare Docker/Apptainer launches and scan for the Pyxis image option.
22
+ Other forms need --image; shell text remains opaque.
23
+ """
24
+ if not executable:
25
+ return None
26
+
27
+ name = Path(executable).name
28
+ arguments = list(command[1:])
29
+ if name == "docker":
30
+ if arguments[:2] == ["container", "run"]:
31
+ arguments = arguments[1:]
32
+ if arguments[:1] != ["run"]:
33
+ return None
34
+ arguments = arguments[1:]
35
+
36
+ elif name == "apptainer":
37
+ if arguments[:1] not in (["exec"], ["run"]):
38
+ return None
39
+ if arguments[0] == "exec" and len(arguments) < 3:
40
+ return None
41
+ arguments = arguments[1:]
42
+
43
+ elif name == "srun":
44
+ if ":" in arguments:
45
+ return None
46
+ # Ponytail: without --, this scan cannot distinguish payload options;
47
+ # supply --image when that ambiguity matters.
48
+ for index, argument in enumerate(arguments):
49
+ if argument == "--":
50
+ return None
51
+ if argument == "--container-image" and index + 2 < len(arguments):
52
+ arguments = arguments[index + 1 :]
53
+ break
54
+ if argument.startswith("--container-image=") and index + 1 < len(arguments):
55
+ arguments = [argument.split("=", 1)[1]]
56
+ break
57
+ else:
58
+ return None
59
+ else:
60
+ return None
61
+
62
+ if arguments and arguments[0] and not arguments[0].startswith("-"):
63
+ if name == "docker" or (
64
+ name == "srun" and not arguments[0].startswith((".", "/"))
65
+ ):
66
+ return "docker://" + arguments[0]
67
+ return arguments[0]
68
+ return None
69
+
70
+
71
+ def collect(
72
+ reference: str,
73
+ cwd: Path,
74
+ env: Mapping[str, str],
75
+ *,
76
+ forbidden: Path,
77
+ ) -> dict:
78
+ facts: dict = {"reference": reference}
79
+ try:
80
+ path = cwd / Path(reference).expanduser()
81
+ local_path = reference.startswith(("/", "./", "../", "~"))
82
+ local_file = path.suffix in {".sif", ".sqsh", ".squashfs", ".img"}
83
+ local_image = local_path or local_file
84
+
85
+ if "://" not in reference and (local_image or path.exists()):
86
+ facts["hash"] = hashing.fingerprint(path, forbidden=forbidden)
87
+ return facts
88
+
89
+ if "://" in reference and not reference.startswith(("docker://", "oras://")):
90
+ raise ValueError(
91
+ "unsupported image URI; supply a local path or OCI reference"
92
+ )
93
+
94
+ image = reference.removeprefix("docker://").removeprefix("oras://")
95
+ if "#" in image:
96
+ registry, repository = image.split("#", 1)
97
+ image = registry.rsplit("@", 1)[-1] + "/" + repository
98
+
99
+ if not image or image.startswith("-"):
100
+ raise ValueError("invalid image reference")
101
+
102
+ except (OSError, ValueError, RuntimeError) as error:
103
+ print(f"giwon: unavailable image inspection: {error}", file=sys.stderr)
104
+ return facts
105
+
106
+ try:
107
+ facts["local"] = docker.inspect_image(image, cwd, env)
108
+ except (OSError, ValueError, TypeError, subprocess.SubprocessError) as error:
109
+ print(f"giwon: unavailable local image inspection: {error}", file=sys.stderr)
110
+
111
+ # Image IDs identify local Docker content, not a repository to query.
112
+ if re.fullmatch(r"(?:sha256:)?[0-9a-f]{12,64}", image):
113
+ return facts
114
+
115
+ try:
116
+ facts["registry"] = docker.inspect_registry(image, cwd, env)
117
+ except (OSError, ValueError, TypeError, subprocess.SubprocessError) as error:
118
+ print(f"giwon: unavailable registry image inspection: {error}", file=sys.stderr)
119
+ return facts
@@ -0,0 +1,45 @@
1
+ """Detect job-specific Pyxis container roots around Giwon."""
2
+
3
+ import re
4
+ import sys
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+
8
+
9
+ def _runtime(env, slurm):
10
+ """Match the current root mount to Pyxis's unnamed job/step container.
11
+
12
+ SPANK option variables and generic Enroot paths also occur outside containers.
13
+ Require a root mount named by Pyxis for this job and step before reporting
14
+ that the plugin's container is active. The mount name supplies neither the
15
+ imported image identity nor the host plugin/Enroot versions, so omit them.
16
+ """
17
+ if slurm is None:
18
+ return None
19
+
20
+ job = str(slurm["job_id"])
21
+ step = env.get("SLURM_STEP_ID", "")
22
+ if not re.fullmatch(r"[0-9]+", step):
23
+ return None
24
+ # Ponytail: named/overlay roots need stronger evidence tying them to this step.
25
+ names = {f"pyxis_{job}.{step}", f"pyxis_{job}_{job}.{step}"}
26
+
27
+ try:
28
+ lines = Path("/proc/self/mountinfo").read_text().splitlines()
29
+ for line in lines:
30
+ fields = line.split()
31
+ if len(fields) < 10 or fields[4] != "/":
32
+ continue
33
+ name = Path(fields[3]).name
34
+ if name in names:
35
+ return {"name": "pyxis"}
36
+ except FileNotFoundError:
37
+ pass
38
+ except (OSError, UnicodeError) as error:
39
+ print(f"giwon: unavailable Pyxis mount observation: {error}", file=sys.stderr)
40
+ return None
41
+
42
+
43
+ def collect(env: Mapping[str, str], slurm: dict | None) -> dict | None:
44
+ runtime = _runtime(env, slurm)
45
+ return {"runtime": runtime} if runtime is not None else None