| 1 |
"""Data models and enums for con-duct.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
from collections import Counter |
| 5 |
from collections.abc import Iterator |
| 6 |
from dataclasses import asdict, dataclass, field |
| 7 |
from datetime import datetime |
| 8 |
from enum import Enum |
| 9 |
import logging |
| 10 |
import os |
| 11 |
import re |
| 12 |
import string |
| 13 |
from typing import Any, Optional |
| 14 |
from con_duct._constants import SUFFIXES |
| 15 |
from con_duct._utils import assert_num |
| 16 |
|
| 17 |
lgr = logging.getLogger("con-duct") |
| 18 |
|
| 19 |
|
| 20 |
class Outputs(str, Enum): |
| 21 |
ALL = "all" |
| 22 |
NONE = "none" |
| 23 |
STDOUT = "stdout" |
| 24 |
STDERR = "stderr" |
| 25 |
|
| 26 |
def __str__(self) -> str: |
| 27 |
return self.value |
| 28 |
|
| 29 |
def has_stdout(self) -> bool: |
| 30 |
return self is Outputs.ALL or self is Outputs.STDOUT |
| 31 |
|
| 32 |
def has_stderr(self) -> bool: |
| 33 |
return self is Outputs.ALL or self is Outputs.STDERR |
| 34 |
|
| 35 |
|
| 36 |
class RecordTypes(str, Enum): |
| 37 |
ALL = "all" |
| 38 |
SYSTEM_SUMMARY = "system-summary" |
| 39 |
PROCESSES_SAMPLES = "processes-samples" |
| 40 |
|
| 41 |
def __str__(self) -> str: |
| 42 |
return self.value |
| 43 |
|
| 44 |
def has_system_summary(self) -> bool: |
| 45 |
return self is RecordTypes.ALL or self is RecordTypes.SYSTEM_SUMMARY |
| 46 |
|
| 47 |
def has_processes_samples(self) -> bool: |
| 48 |
return self is RecordTypes.ALL or self is RecordTypes.PROCESSES_SAMPLES |
| 49 |
|
| 50 |
|
| 51 |
class SessionMode(str, Enum): |
| 52 |
NEW_SESSION = "new-session" |
| 53 |
CURRENT_SESSION = "current-session" |
| 54 |
|
| 55 |
def __str__(self) -> str: |
| 56 |
return self.value |
| 57 |
|
| 58 |
|
| 59 |
@dataclass |
| 60 |
class SystemInfo: |
| 61 |
cpu_total: int |
| 62 |
memory_total: int |
| 63 |
hostname: str | None |
| 64 |
uid: int |
| 65 |
user: str | None |
| 66 |
|
| 67 |
|
| 68 |
@dataclass |
| 69 |
class ProcessStats: |
| 70 |
pcpu: float |
| 71 |
pmem: float |
| 72 |
rss: int |
| 73 |
vsz: int |
| 74 |
timestamp: str |
| 75 |
etime: str |
| 76 |
stat: Counter |
| 77 |
cmd: str |
| 78 |
|
| 79 |
def aggregate(self, other: ProcessStats) -> ProcessStats: |
| 80 |
cmd = self.cmd |
| 81 |
if self.cmd != other.cmd: |
| 82 |
lgr.debug( |
| 83 |
f"cmd has changed. Previous measurement was {self.cmd}, now {other.cmd}." |
| 84 |
) |
| 85 |
|
| 86 |
surrounded_by_brackets = r"^\[.+\]" |
| 87 |
if re.search(surrounded_by_brackets, self.cmd): |
| 88 |
lgr.debug(f"using {other.cmd}.") |
| 89 |
cmd = other.cmd |
| 90 |
lgr.debug(f"using {self.cmd}.") |
| 91 |
|
| 92 |
new_counter: Counter = Counter() |
| 93 |
new_counter.update(self.stat) |
| 94 |
new_counter.update(other.stat) |
| 95 |
return ProcessStats( |
| 96 |
pcpu=max(self.pcpu, other.pcpu), |
| 97 |
pmem=max(self.pmem, other.pmem), |
| 98 |
rss=max(self.rss, other.rss), |
| 99 |
vsz=max(self.vsz, other.vsz), |
| 100 |
timestamp=max(self.timestamp, other.timestamp), |
| 101 |
etime=other.etime, |
| 102 |
stat=new_counter, |
| 103 |
cmd=cmd, |
| 104 |
) |
| 105 |
|
| 106 |
def for_json(self) -> dict: |
| 107 |
ret = asdict(self) |
| 108 |
ret["stat"] = dict(self.stat) |
| 109 |
return ret |
| 110 |
|
| 111 |
def __post_init__(self) -> None: |
| 112 |
self._validate() |
| 113 |
|
| 114 |
def _validate(self) -> None: |
| 115 |
assert_num(self.pcpu, self.pmem, self.rss, self.vsz) |
| 116 |
|
| 117 |
|
| 118 |
@dataclass |
| 119 |
class LogPaths: |
| 120 |
stdout: str |
| 121 |
stderr: str |
| 122 |
usage: str |
| 123 |
info: str |
| 124 |
prefix: str |
| 125 |
|
| 126 |
def __iter__(self) -> Iterator[tuple[str, str]]: |
| 127 |
for name, path in asdict(self).items(): |
| 128 |
if name != "prefix": |
| 129 |
yield name, path |
| 130 |
|
| 131 |
@classmethod |
| 132 |
def create(cls, output_prefix: str, pid: None | int = None) -> LogPaths: |
| 133 |
if any( |
| 134 |
field_name == "datetime_filesafe" |
| 135 |
for _, field_name, _, _ in string.Formatter().parse(output_prefix) |
| 136 |
): |
| 137 |
lgr.warning( |
| 138 |
"{datetime_filesafe} in --output-prefix is deprecated; use {datetime} instead" |
| 139 |
) |
| 140 |
datetime_filesafe = datetime.now().strftime("%Y.%m.%dT%H.%M.%S") |
| 141 |
formatted_prefix = output_prefix.format( |
| 142 |
pid=pid, |
| 143 |
datetime=datetime_filesafe, |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
datetime_filesafe=datetime_filesafe, |
| 148 |
) |
| 149 |
return cls( |
| 150 |
stdout=f"{formatted_prefix}{SUFFIXES['stdout']}", |
| 151 |
stderr=f"{formatted_prefix}{SUFFIXES['stderr']}", |
| 152 |
usage=f"{formatted_prefix}{SUFFIXES['usage']}", |
| 153 |
info=f"{formatted_prefix}{SUFFIXES['info']}", |
| 154 |
prefix=formatted_prefix, |
| 155 |
) |
| 156 |
|
| 157 |
def prepare_paths(self, clobber: bool, capture_outputs: Outputs) -> None: |
| 158 |
conflicts = [path for _name, path in self if os.path.exists(path)] |
| 159 |
if conflicts and not clobber: |
| 160 |
raise FileExistsError( |
| 161 |
"Conflicting files:\n" |
| 162 |
+ "\n".join(f"- {path}" for path in conflicts) |
| 163 |
+ "\nUse --clobber to overwrite conflicting files." |
| 164 |
) |
| 165 |
|
| 166 |
if self.prefix.endswith(os.sep): |
| 167 |
os.makedirs(self.prefix, exist_ok=True) |
| 168 |
else: |
| 169 |
|
| 170 |
directory = os.path.dirname(self.prefix) |
| 171 |
if directory: |
| 172 |
os.makedirs(directory, exist_ok=True) |
| 173 |
for name, path in self: |
| 174 |
if name == SUFFIXES["stdout"] and not capture_outputs.has_stdout(): |
| 175 |
continue |
| 176 |
elif name == SUFFIXES["stderr"] and not capture_outputs.has_stderr(): |
| 177 |
continue |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
open(path, "w").close() |
| 182 |
|
| 183 |
|
| 184 |
@dataclass |
| 185 |
class Averages: |
| 186 |
rss: Optional[float] = None |
| 187 |
vsz: Optional[float] = None |
| 188 |
pmem: Optional[float] = None |
| 189 |
pcpu: Optional[float] = None |
| 190 |
num_samples: int = 0 |
| 191 |
|
| 192 |
def update(self: Averages, other: Sample) -> None: |
| 193 |
assert_num(other.total_rss, other.total_vsz, other.total_pmem, other.total_pcpu) |
| 194 |
if not self.num_samples: |
| 195 |
self.num_samples += 1 |
| 196 |
self.rss = other.total_rss |
| 197 |
self.vsz = other.total_vsz |
| 198 |
self.pmem = other.total_pmem |
| 199 |
self.pcpu = other.total_pcpu |
| 200 |
else: |
| 201 |
assert self.rss is not None |
| 202 |
assert self.vsz is not None |
| 203 |
assert self.pmem is not None |
| 204 |
assert self.pcpu is not None |
| 205 |
assert other.total_rss is not None |
| 206 |
assert other.total_vsz is not None |
| 207 |
assert other.total_pmem is not None |
| 208 |
assert other.total_pcpu is not None |
| 209 |
self.num_samples += 1 |
| 210 |
self.rss += (other.total_rss - self.rss) / self.num_samples |
| 211 |
self.vsz += (other.total_vsz - self.vsz) / self.num_samples |
| 212 |
self.pmem += (other.total_pmem - self.pmem) / self.num_samples |
| 213 |
self.pcpu += (other.total_pcpu - self.pcpu) / self.num_samples |
| 214 |
|
| 215 |
@classmethod |
| 216 |
def from_sample(cls, sample: Sample) -> Averages: |
| 217 |
assert_num( |
| 218 |
sample.total_rss, sample.total_vsz, sample.total_pmem, sample.total_pcpu |
| 219 |
) |
| 220 |
return cls( |
| 221 |
rss=sample.total_rss, |
| 222 |
vsz=sample.total_vsz, |
| 223 |
pmem=sample.total_pmem, |
| 224 |
pcpu=sample.total_pcpu, |
| 225 |
num_samples=1, |
| 226 |
) |
| 227 |
|
| 228 |
|
| 229 |
@dataclass |
| 230 |
class Sample: |
| 231 |
stats: dict[int, ProcessStats] = field(default_factory=dict) |
| 232 |
averages: Averages = field(default_factory=Averages) |
| 233 |
total_rss: Optional[int] = None |
| 234 |
total_vsz: Optional[int] = None |
| 235 |
total_pmem: Optional[float] = None |
| 236 |
total_pcpu: Optional[float] = None |
| 237 |
timestamp: str = "" |
| 238 |
|
| 239 |
def add_pid(self, pid: int, stats: ProcessStats) -> None: |
| 240 |
|
| 241 |
assert ( |
| 242 |
self.stats.get(pid) is None |
| 243 |
) |
| 244 |
self.total_rss = (self.total_rss or 0) + stats.rss |
| 245 |
self.total_vsz = (self.total_vsz or 0) + stats.vsz |
| 246 |
self.total_pmem = (self.total_pmem or 0.0) + stats.pmem |
| 247 |
self.total_pcpu = (self.total_pcpu or 0.0) + stats.pcpu |
| 248 |
self.stats[pid] = stats |
| 249 |
self.timestamp = max(self.timestamp, stats.timestamp) |
| 250 |
|
| 251 |
def aggregate(self: Sample, other: Sample) -> Sample: |
| 252 |
output = Sample() |
| 253 |
for pid in self.stats.keys() | other.stats.keys(): |
| 254 |
if (mine := self.stats.get(pid)) is not None: |
| 255 |
if (theirs := other.stats.get(pid)) is not None: |
| 256 |
output.add_pid(pid, mine.aggregate(theirs)) |
| 257 |
else: |
| 258 |
output.add_pid(pid, mine) |
| 259 |
else: |
| 260 |
output.add_pid(pid, other.stats[pid]) |
| 261 |
assert other.total_pmem is not None |
| 262 |
assert other.total_pcpu is not None |
| 263 |
assert other.total_rss is not None |
| 264 |
assert other.total_vsz is not None |
| 265 |
output.total_pmem = max(self.total_pmem or 0.0, other.total_pmem) |
| 266 |
output.total_pcpu = max(self.total_pcpu or 0.0, other.total_pcpu) |
| 267 |
output.total_rss = max(self.total_rss or 0, other.total_rss) |
| 268 |
output.total_vsz = max(self.total_vsz or 0, other.total_vsz) |
| 269 |
output.averages = self.averages |
| 270 |
output.averages.update(other) |
| 271 |
return output |
| 272 |
|
| 273 |
def for_json(self) -> dict[str, Any]: |
| 274 |
d = { |
| 275 |
"timestamp": self.timestamp, |
| 276 |
"num_samples": self.averages.num_samples, |
| 277 |
"processes": { |
| 278 |
str(pid): stats.for_json() for pid, stats in self.stats.items() |
| 279 |
}, |
| 280 |
"totals": { |
| 281 |
"pmem": self.total_pmem, |
| 282 |
"pcpu": self.total_pcpu, |
| 283 |
"rss": self.total_rss, |
| 284 |
"vsz": self.total_vsz, |
| 285 |
}, |
| 286 |
"averages": asdict(self.averages) if self.averages.num_samples >= 1 else {}, |
| 287 |
} |
| 288 |
return d |