| 1 |
"""Process tracking and reporting for con-duct.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
from dataclasses import asdict |
| 5 |
from importlib.metadata import version |
| 6 |
import json |
| 7 |
import logging |
| 8 |
import math |
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import socket |
| 12 |
import subprocess |
| 13 |
import threading |
| 14 |
import time |
| 15 |
from typing import Any, Optional, TextIO |
| 16 |
from con_duct._constants import ENV_PREFIXES, __schema_version__ |
| 17 |
from con_duct._formatter import SummaryFormatter |
| 18 |
from con_duct._models import LogPaths, Sample, SystemInfo |
| 19 |
from con_duct._output import safe_close_files |
| 20 |
from con_duct._sampling import _get_sample |
| 21 |
|
| 22 |
__version__ = version("con-duct") |
| 23 |
|
| 24 |
lgr = logging.getLogger("con-duct") |
| 25 |
|
| 26 |
|
| 27 |
class Report: |
| 28 |
"""Top level report""" |
| 29 |
|
| 30 |
def __init__( |
| 31 |
self, |
| 32 |
command: str, |
| 33 |
arguments: list[str], |
| 34 |
log_paths: LogPaths, |
| 35 |
summary_format: str, |
| 36 |
working_directory: str, |
| 37 |
colors: bool = False, |
| 38 |
clobber: bool = False, |
| 39 |
process: subprocess.Popen | None = None, |
| 40 |
message: str = "", |
| 41 |
) -> None: |
| 42 |
self._command = command |
| 43 |
self.arguments = arguments |
| 44 |
self.log_paths = log_paths |
| 45 |
self.summary_format: str = summary_format |
| 46 |
self.clobber = clobber |
| 47 |
self.colors = colors |
| 48 |
self.message = message |
| 49 |
|
| 50 |
self.start_time: float | None = None |
| 51 |
self.process = process |
| 52 |
self.session_id: int | None = None |
| 53 |
self.gpus: list[dict[str, str]] | None = None |
| 54 |
self.env: dict[str, str] | None = None |
| 55 |
self.number = 1 |
| 56 |
self.system_info: SystemInfo | None = None |
| 57 |
self.full_run_stats = Sample() |
| 58 |
self.current_sample: Optional[Sample] = None |
| 59 |
self.end_time: float | None = None |
| 60 |
self.run_time_seconds: str | None = None |
| 61 |
self.usage_file: TextIO | None = None |
| 62 |
self.working_directory: str = working_directory |
| 63 |
|
| 64 |
def __del__(self) -> None: |
| 65 |
safe_close_files([self.usage_file]) |
| 66 |
|
| 67 |
@property |
| 68 |
def command(self) -> str: |
| 69 |
return " ".join([self._command] + self.arguments) |
| 70 |
|
| 71 |
@property |
| 72 |
def elapsed_time(self) -> float: |
| 73 |
assert self.start_time is not None |
| 74 |
return time.time() - self.start_time |
| 75 |
|
| 76 |
@property |
| 77 |
def wall_clock_time(self) -> Optional[float]: |
| 78 |
if self.start_time is None: |
| 79 |
return math.nan |
| 80 |
if self.end_time is None: |
| 81 |
|
| 82 |
|
| 83 |
return time.time() - self.start_time |
| 84 |
|
| 85 |
return self.end_time - self.start_time |
| 86 |
|
| 87 |
def collect_environment(self) -> None: |
| 88 |
self.env = {k: v for k, v in os.environ.items() if k.startswith(ENV_PREFIXES)} |
| 89 |
|
| 90 |
def get_system_info(self) -> None: |
| 91 |
"""Gathers system information related to CPU, GPU, memory, and environment variables.""" |
| 92 |
self.system_info = SystemInfo( |
| 93 |
cpu_total=os.sysconf("SC_NPROCESSORS_CONF"), |
| 94 |
memory_total=os.sysconf("SC_PAGESIZE") * os.sysconf("SC_PHYS_PAGES"), |
| 95 |
hostname=socket.gethostname(), |
| 96 |
uid=os.getuid(), |
| 97 |
user=os.environ.get("USER"), |
| 98 |
) |
| 99 |
|
| 100 |
if shutil.which("nvidia-smi") is not None: |
| 101 |
lgr.debug("Checking NVIDIA GPU using nvidia-smi") |
| 102 |
try: |
| 103 |
out = subprocess.check_output( |
| 104 |
[ |
| 105 |
"nvidia-smi", |
| 106 |
"--query-gpu=index,name,pci.bus_id,driver_version,memory.total,compute_mode", |
| 107 |
"--format=csv", |
| 108 |
] |
| 109 |
) |
| 110 |
except subprocess.CalledProcessError as e: |
| 111 |
lgr.warning("Error collecting gpu information: %s", str(e)) |
| 112 |
self.gpus = None |
| 113 |
return |
| 114 |
try: |
| 115 |
decoded = out.decode("utf-8") |
| 116 |
lines = decoded.strip().split("\n") |
| 117 |
_ = lines.pop(0) |
| 118 |
self.gpus = [] |
| 119 |
for line in lines: |
| 120 |
cols = line.split(", ") |
| 121 |
self.gpus.append( |
| 122 |
{ |
| 123 |
"index": cols[0], |
| 124 |
"name": cols[1], |
| 125 |
"bus_id": cols[2], |
| 126 |
"driver_version": cols[3], |
| 127 |
"memory.total": cols[4], |
| 128 |
"compute_mode": cols[5], |
| 129 |
} |
| 130 |
) |
| 131 |
except Exception as e: |
| 132 |
lgr.warning("Error parsing gpu information: %s", str(e)) |
| 133 |
self.gpus = None |
| 134 |
|
| 135 |
def collect_sample(self) -> Optional[Sample]: |
| 136 |
assert self.session_id is not None |
| 137 |
try: |
| 138 |
sample = _get_sample(self.session_id) |
| 139 |
return sample |
| 140 |
except subprocess.CalledProcessError as exc: |
| 141 |
lgr.debug("Error collecting sample: %s", str(exc)) |
| 142 |
return None |
| 143 |
|
| 144 |
def update_from_sample(self, sample: Sample) -> None: |
| 145 |
self.full_run_stats = self.full_run_stats.aggregate(sample) |
| 146 |
if self.current_sample is None: |
| 147 |
self.current_sample = Sample().aggregate(sample) |
| 148 |
else: |
| 149 |
assert self.current_sample.averages is not None |
| 150 |
self.current_sample = self.current_sample.aggregate(sample) |
| 151 |
assert self.current_sample is not None |
| 152 |
|
| 153 |
def write_subreport(self) -> None: |
| 154 |
assert self.current_sample is not None |
| 155 |
if self.usage_file is None: |
| 156 |
self.usage_file = open(self.log_paths.usage, "w") |
| 157 |
self.usage_file.write(json.dumps(self.current_sample.for_json()) + "\n") |
| 158 |
self.usage_file.flush() |
| 159 |
|
| 160 |
@property |
| 161 |
def execution_summary(self) -> dict[str, Any]: |
| 162 |
|
| 163 |
|
| 164 |
if self.process and self.process.returncode < 0: |
| 165 |
self.process.returncode = 128 + abs(self.process.returncode) |
| 166 |
|
| 167 |
return { |
| 168 |
"exit_code": self.process.returncode if self.process else None, |
| 169 |
"command": self.command, |
| 170 |
"logs_prefix": self.log_paths.prefix if self.log_paths else "", |
| 171 |
"wall_clock_time": self.wall_clock_time, |
| 172 |
"peak_rss": self.full_run_stats.total_rss, |
| 173 |
"average_rss": self.full_run_stats.averages.rss, |
| 174 |
"peak_vsz": self.full_run_stats.total_vsz, |
| 175 |
"average_vsz": self.full_run_stats.averages.vsz, |
| 176 |
"peak_pmem": self.full_run_stats.total_pmem, |
| 177 |
"average_pmem": self.full_run_stats.averages.pmem, |
| 178 |
"peak_pcpu": self.full_run_stats.total_pcpu, |
| 179 |
"average_pcpu": self.full_run_stats.averages.pcpu, |
| 180 |
"num_samples": self.full_run_stats.averages.num_samples, |
| 181 |
"num_reports": self.number, |
| 182 |
"start_time": self.start_time, |
| 183 |
"end_time": self.end_time, |
| 184 |
"working_directory": self.working_directory, |
| 185 |
} |
| 186 |
|
| 187 |
def dump_json(self) -> str: |
| 188 |
return json.dumps( |
| 189 |
{ |
| 190 |
"command": self.command, |
| 191 |
"system": ( |
| 192 |
None if self.system_info is None else asdict(self.system_info) |
| 193 |
), |
| 194 |
"env": self.env, |
| 195 |
"gpu": self.gpus, |
| 196 |
"duct_version": __version__, |
| 197 |
"schema_version": __schema_version__, |
| 198 |
"execution_summary": self.execution_summary, |
| 199 |
"output_paths": asdict(self.log_paths), |
| 200 |
"working_directory": self.working_directory, |
| 201 |
"message": self.message, |
| 202 |
} |
| 203 |
) |
| 204 |
|
| 205 |
@property |
| 206 |
def execution_summary_formatted(self) -> str: |
| 207 |
formatter = SummaryFormatter(enable_colors=self.colors) |
| 208 |
return formatter.format(self.summary_format, **self.execution_summary) |
| 209 |
|
| 210 |
|
| 211 |
def monitor_process( |
| 212 |
report: Report, |
| 213 |
process: subprocess.Popen, |
| 214 |
report_interval: float, |
| 215 |
sample_interval: float, |
| 216 |
stop_event: threading.Event, |
| 217 |
) -> None: |
| 218 |
lgr.debug( |
| 219 |
"Starting monitoring of the process %s on sample interval %f for report interval %f", |
| 220 |
process, |
| 221 |
sample_interval, |
| 222 |
report_interval, |
| 223 |
) |
| 224 |
while True: |
| 225 |
if process.poll() is not None: |
| 226 |
lgr.debug( |
| 227 |
"Breaking out of the monitor since the passthrough command has finished" |
| 228 |
) |
| 229 |
break |
| 230 |
sample = report.collect_sample() |
| 231 |
|
| 232 |
if ( |
| 233 |
sample is None |
| 234 |
): |
| 235 |
if process.poll() is not None: |
| 236 |
lgr.debug( |
| 237 |
"Breaking out of the monitor since the passthrough command has finished " |
| 238 |
"before we could collect sample" |
| 239 |
) |
| 240 |
break |
| 241 |
|
| 242 |
continue |
| 243 |
report.update_from_sample(sample) |
| 244 |
if ( |
| 245 |
report.start_time |
| 246 |
and report.elapsed_time >= (report.number - 1) * report_interval |
| 247 |
): |
| 248 |
report.write_subreport() |
| 249 |
report.current_sample = None |
| 250 |
report.number += 1 |
| 251 |
if stop_event.wait(timeout=sample_interval): |
| 252 |
lgr.debug("Breaking out because stop event was set") |
| 253 |
break |