| 1 |
"""Resource-usage plotting for con-duct. |
| 2 |
|
| 3 |
Renders a per-pid CPU / rss cloud overlaid by envelopes: |
| 4 |
max-across-pids as a lower bound, and either ``totals.*`` from the |
| 5 |
record (RSS, and CPU in ``ps-pcpu`` mode) or sum-across-pids of the |
| 6 |
derived values (CPU in ``ps-cpu-timepoint`` mode) as the upper |
| 7 |
bound. CPU lives on the primary y-axis (percent), rss on a |
| 8 |
secondary y-axis (bytes). |
| 9 |
|
| 10 |
The per-pid overlay is loosely modeled on brainlife's smon task viewer: |
| 11 |
https://github.com/brainlife/warehouse/blob/b833b98e3518181eacef71cc04ae773a7592b1a8/ui/src/modals/taskinfo.vue |
| 12 |
""" |
| 13 |
|
| 14 |
import argparse |
| 15 |
from datetime import datetime |
| 16 |
import json |
| 17 |
import logging |
| 18 |
from pathlib import Path |
| 19 |
from typing import Any, Dict, List, Optional, Tuple |
| 20 |
from con_duct._constants import SUFFIXES |
| 21 |
from con_duct._formatter import FILESIZE_UNITS, SummaryFormatter |
| 22 |
from con_duct._utils import etime_to_etimes, is_same_pid, pdcpu_from_pcpu |
| 23 |
from con_duct.json_utils import is_info_file, load_info_file, load_usage_file |
| 24 |
|
| 25 |
|
| 26 |
PCPU_COLOR = "tab:orange" |
| 27 |
RSS_COLOR = "tab:blue" |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
CPU_MODE_PS_PCPU = "ps-pcpu" |
| 34 |
CPU_MODE_PS_CPU_TIMEPOINT = "ps-cpu-timepoint" |
| 35 |
CPU_MODES = (CPU_MODE_PS_PCPU, CPU_MODE_PS_CPU_TIMEPOINT) |
| 36 |
|
| 37 |
lgr = logging.getLogger(__name__) |
| 38 |
|
| 39 |
_TIME_UNITS = [ |
| 40 |
("s", 1), |
| 41 |
("min", 60), |
| 42 |
("h", 3600), |
| 43 |
("d", 86400), |
| 44 |
] |
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
class HumanizedAxisFormatter: |
| 49 |
"""Format units for human-readable plot axes.""" |
| 50 |
|
| 51 |
def __new__(cls, min_ratio: float, units: list) -> Any: |
| 52 |
from matplotlib.ticker import Formatter |
| 53 |
|
| 54 |
class _HumanizedAxisFormatter(Formatter): |
| 55 |
def __init__(self, min_ratio: float, units: list): |
| 56 |
super().__init__() |
| 57 |
self.min_ratio = min_ratio |
| 58 |
self.units: List[Tuple[str, int]] = units |
| 59 |
|
| 60 |
def pick_unit(self, base_value: float) -> Tuple[str, int]: |
| 61 |
|
| 62 |
if self.min_ratio == -1: |
| 63 |
return self.units[0] |
| 64 |
|
| 65 |
unit: Tuple[str, int] = self.units[0] |
| 66 |
for name, divisor in self.units: |
| 67 |
if base_value / divisor >= self.min_ratio: |
| 68 |
unit = (name, divisor) |
| 69 |
return unit |
| 70 |
|
| 71 |
def __call__(self, x: float, _pos: Optional[int] = 0) -> str: |
| 72 |
"""Called by matplotlib to value for axis tick. |
| 73 |
Args: |
| 74 |
x: value in base unit |
| 75 |
|
| 76 |
Returns: |
| 77 |
Formatted human readable unit string |
| 78 |
""" |
| 79 |
xmin, xmax = self.axis.get_view_interval() |
| 80 |
span_sec = abs(xmax - xmin) or 1.0 |
| 81 |
name, divisor = self.pick_unit(span_sec) |
| 82 |
value = x / divisor |
| 83 |
return f"{value:.1f}{name}" |
| 84 |
|
| 85 |
return _HumanizedAxisFormatter(min_ratio=min_ratio, units=units) |
| 86 |
|
| 87 |
|
| 88 |
def _build_pid_series( |
| 89 |
data: List[Dict[str, Any]], |
| 90 |
cpu_mode: str = CPU_MODE_PS_PCPU, |
| 91 |
) -> Dict[str, Dict[str, Any]]: |
| 92 |
"""Walk usage records once, return per-pid time series. |
| 93 |
|
| 94 |
For each pid present in any record, returns aligned lists of |
| 95 |
``elapsed`` (seconds since first record), ``cpu``, ``pmem``, |
| 96 |
``rss``. |
| 97 |
|
| 98 |
The ``cpu`` field is populated according to ``cpu_mode``: |
| 99 |
|
| 100 |
- ``ps-pcpu``: raw ``pcpu`` from each record, untransformed. Every |
| 101 |
record contributes a value; no entry is dropped. |
| 102 |
- ``ps-cpu-timepoint``: delta-corrected pdcpu computed from |
| 103 |
consecutive (etime, pcpu) pairs. ``None`` for first observation |
| 104 |
per pid, records with ``etime == "00:00"``, sub-quantum |
| 105 |
intervals, pid reuse, and the negative-pdcpu clamp. |
| 106 |
""" |
| 107 |
if not data: |
| 108 |
return {} |
| 109 |
base_ts = datetime.fromisoformat(data[0]["timestamp"]) |
| 110 |
pid_state: Dict[str, Optional[Tuple[float, float, datetime]]] = {} |
| 111 |
series: Dict[str, Dict[str, Any]] = {} |
| 112 |
for entry in data: |
| 113 |
entry_ts = datetime.fromisoformat(entry["timestamp"]) |
| 114 |
elapsed = (entry_ts - base_ts).total_seconds() |
| 115 |
for pid, p in entry.get("processes", {}).items(): |
| 116 |
pcpu = float(p.get("pcpu", 0.0)) |
| 117 |
cpu_value: Optional[float] |
| 118 |
if cpu_mode == CPU_MODE_PS_PCPU: |
| 119 |
cpu_value = pcpu |
| 120 |
else: |
| 121 |
try: |
| 122 |
etime_sec = etime_to_etimes(p.get("etime", "")) |
| 123 |
except ValueError: |
| 124 |
continue |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
rt |
| 130 |
|
| 131 |
|
| 132 |
proc_ts = datetime.fromisoformat(p.get("timestamp", entry["timestamp"])) |
| 133 |
prev = pid_state.get(pid) |
| 134 |
cpu_value = None |
| 135 |
if etime_sec != 0.0 and prev is not None: |
| 136 |
prev_etime, prev_pcpu, prev_proc_ts = prev |
| 137 |
wall_delta = (proc_ts - prev_proc_ts).total_seconds() |
| 138 |
if is_same_pid(prev_etime, etime_sec, wall_delta): |
| 139 |
cpu_value = pdcpu_from_pcpu( |
| 140 |
prev_pcpu, prev_etime, pcpu, etime_sec |
| 141 |
) |
| 142 |
|
| 143 |
|
| 144 |
pid_state[pid] = ( |
| 145 |
None if etime_sec == 0.0 else (etime_sec, pcpu, proc_ts) |
| 146 |
) |
| 147 |
entry_series = series.setdefault( |
| 148 |
pid, |
| 149 |
{ |
| 150 |
"cmd": p.get("cmd", ""), |
| 151 |
"elapsed": [], |
| 152 |
"cpu": [], |
| 153 |
"pmem": [], |
| 154 |
"rss": [], |
| 155 |
}, |
| 156 |
) |
| 157 |
entry_series["elapsed"].append(elapsed) |
| 158 |
entry_series["cpu"].append(cpu_value) |
| 159 |
entry_series["pmem"].append(float(p.get("pmem", 0.0))) |
| 160 |
entry_series["rss"].append(float(p.get("rss", 0.0))) |
| 161 |
return series |
| 162 |
|
| 163 |
|
| 164 |
def _envelopes( |
| 165 |
series: Dict[str, Dict[str, Any]], |
| 166 |
metric: str, |
| 167 |
) -> Tuple[List[float], List[float], List[float]]: |
| 168 |
"""Per-grid-timestamp max and sum across kept pids for ``metric``. |
| 169 |
|
| 170 |
Each pid contributes a value at every entry-elapsed timestamp where it |
| 171 |
appeared *and* its value at that timestamp is not ``None`` (pdcpu can be |
| 172 |
``None`` for first-observation, etime=0, sub-quantum, pid-reuse, or the |
| 173 |
negative-pdcpu clamp). Grid points where no kept pid had a value are |
| 174 |
omitted entirely rather than reported as zero -- a missing measurement |
| 175 |
is not the same as zero load. |
| 176 |
|
| 177 |
The grid is the union of (kept pids') elapsed values; the alternative |
| 178 |
of "every entry timestamp regardless of who appeared" would only add |
| 179 |
grid points that are missing measurements anyway. |
| 180 |
|
| 181 |
:returns: ``(grid_xs, max_ys, sum_ys)`` aligned, sorted by ``grid_xs``. |
| 182 |
""" |
| 183 |
grid: Dict[float, List[float]] = {} |
| 184 |
for s in series.values(): |
| 185 |
for x, v in zip(s["elapsed"], s[metric]): |
| 186 |
if v is None: |
| 187 |
continue |
| 188 |
grid.setdefault(x, []).append(v) |
| 189 |
xs = sorted(grid.keys()) |
| 190 |
return xs, [max(grid[x]) for x in xs], [sum(grid[x]) for x in xs] |
| 191 |
|
| 192 |
|
| 193 |
def _totals_series( |
| 194 |
data: List[Dict[str, Any]], field: str |
| 195 |
) -> Tuple[List[float], List[float]]: |
| 196 |
"""Return ``(elapsed, totals[field])`` per record. |
| 197 |
|
| 198 |
``totals[field]`` is duct's max-of-(sum-per-sample) within each report |
| 199 |
interval -- the highest concurrent value observed at any single sample |
| 200 |
in that interval. Used as the upper-bound line on the chart, replacing |
| 201 |
sum-of-per-pid-peaks (which over-counts pids whose peaks never |
| 202 |
coexisted within the same sample -- "phantom coexistence"). |
| 203 |
""" |
| 204 |
if not data: |
| 205 |
return [], [] |
| 206 |
base = datetime.fromisoformat(data[0]["timestamp"]) |
| 207 |
xs: List[float] = [] |
| 208 |
ys: List[float] = [] |
| 209 |
for entry in data: |
| 210 |
xs.append((datetime.fromisoformat(entry["timestamp"]) - base).total_seconds()) |
| 211 |
ys.append(float(entry["totals"][field])) |
| 212 |
return xs, ys |
| 213 |
|
| 214 |
|
| 215 |
def _load_host_memory_total(file_path: Path) -> Optional[int]: |
| 216 |
"""Best-effort lookup of ``system.memory_total`` (bytes) from info.json. |
| 217 |
|
| 218 |
Accepts either an info.json path or a usage path; for the latter, falls |
| 219 |
back to a sibling info.json named by stripping the usage suffix and |
| 220 |
appending ``info.json``. Returns ``None`` on any failure -- the caller |
| 221 |
treats absence as "host RAM unknown" and renders a plain legend label. |
| 222 |
""" |
| 223 |
try: |
| 224 |
if is_info_file(str(file_path)): |
| 225 |
info_data = load_info_file(str(file_path)) |
| 226 |
else: |
| 227 |
usage_str = str(file_path) |
| 228 |
sibling: Optional[Path] = None |
| 229 |
for suffix in (SUFFIXES["usage"], SUFFIXES["usage_legacy"]): |
| 230 |
if usage_str.endswith(suffix): |
| 231 |
sibling = Path(usage_str[: -len(suffix)] + SUFFIXES["info"]) |
| 232 |
break |
| 233 |
if sibling is None or not sibling.exists(): |
| 234 |
return None |
| 235 |
info_data = load_info_file(str(sibling)) |
| 236 |
value = info_data["system"]["memory_total"] |
| 237 |
return int(value) |
| 238 |
except (FileNotFoundError, KeyError, ValueError, TypeError, json.JSONDecodeError): |
| 239 |
return None |
| 240 |
|
| 241 |
|
| 242 |
def matplotlib_plot(args: argparse.Namespace) -> int: |
| 243 |
try: |
| 244 |
import matplotlib |
| 245 |
|
| 246 |
|
| 247 |
if args.output is not None: |
| 248 |
matplotlib.use("Agg") |
| 249 |
|
| 250 |
from matplotlib.lines import Line2D |
| 251 |
import matplotlib.pyplot as plt |
| 252 |
except ImportError as e: |
| 253 |
lgr.error("con-duct plot failed: missing dependency: %s", e) |
| 254 |
return 1 |
| 255 |
except AttributeError as e: |
| 256 |
lgr.error( |
| 257 |
"con-duct plot failed to initialize display backend: %s. " |
| 258 |
"Try using --output to save the plot to a file instead.", |
| 259 |
e, |
| 260 |
) |
| 261 |
return 1 |
| 262 |
|
| 263 |
|
| 264 |
try: |
| 265 |
from matplotlib.backends import backend_registry |
| 266 |
from matplotlib.backends.registry import BackendFilter |
| 267 |
except (ImportError, AttributeError): |
| 268 |
backend_registry = None |
| 269 |
BackendFilter = None |
| 270 |
|
| 271 |
if args.output is None: |
| 272 |
lgr.warning( |
| 273 |
"Using matplotlib < 3.9 which lacks backend registry. " |
| 274 |
"Cannot verify if your backend supports interactive display. " |
| 275 |
"If plotting fails, use --output to save to a file instead." |
| 276 |
) |
| 277 |
|
| 278 |
|
| 279 |
arg_path = Path(args.file_path) |
| 280 |
file_path = arg_path |
| 281 |
if is_info_file(str(file_path)): |
| 282 |
try: |
| 283 |
info_data = load_info_file(str(file_path)) |
| 284 |
rel_usage_path = Path(info_data["output_paths"]["usage"]) |
| 285 |
file_path = file_path.with_name(rel_usage_path.name) |
| 286 |
except (FileNotFoundError, KeyError, json.JSONDecodeError) as e: |
| 287 |
lgr.error("Error reading info file %s: %s", args.file_path, e) |
| 288 |
return 1 |
| 289 |
host_memory_total = _load_host_memory_total(arg_path) |
| 290 |
|
| 291 |
try: |
| 292 |
data = load_usage_file(str(file_path)) |
| 293 |
except FileNotFoundError: |
| 294 |
lgr.error("File %s was not found.", file_path) |
| 295 |
return 1 |
| 296 |
except json.JSONDecodeError: |
| 297 |
lgr.error("File %s contained invalid JSON.", file_path) |
| 298 |
return 1 |
| 299 |
|
| 300 |
try: |
| 301 |
pid_series = _build_pid_series(data, cpu_mode=args.cpu) |
| 302 |
totals_rss_xs, totals_rss_ys = _totals_series(data, "rss") |
| 303 |
totals_pcpu_xs, totals_pcpu_ys = _totals_series(data, "pcpu") |
| 304 |
except KeyError as e: |
| 305 |
lgr.error("Usage file %s is missing required field: %s", file_path, e) |
| 306 |
return 1 |
| 307 |
except ValueError as e: |
| 308 |
lgr.error("Usage file %s contains invalid data format: %s", file_path, e) |
| 309 |
return 1 |
| 310 |
except Exception as e: |
| 311 |
lgr.error("Error processing usage file %s: %s", file_path, e) |
| 312 |
return 1 |
| 313 |
|
| 314 |
fig, ax = plt.subplots() |
| 315 |
ax2 = ax.twinx() |
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
for s in pid_series.values(): |
| 320 |
pdcpu_xs = [t for t, v in zip(s["elapsed"], s["cpu"]) if v is not None] |
| 321 |
pdcpu_ys = [v for v in s["cpu"] if v is not None] |
| 322 |
if pdcpu_xs: |
| 323 |
ax.plot( |
| 324 |
pdcpu_xs, |
| 325 |
pdcpu_ys, |
| 326 |
color=PCPU_COLOR, |
| 327 |
linestyle=":", |
| 328 |
linewidth=0.8, |
| 329 |
alpha=0.4, |
| 330 |
) |
| 331 |
ax2.plot( |
| 332 |
s["elapsed"], |
| 333 |
s["rss"], |
| 334 |
color=RSS_COLOR, |
| 335 |
linestyle=":", |
| 336 |
linewidth=0.8, |
| 337 |
alpha=0.4, |
| 338 |
) |
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
pcpu_xs, pcpu_max, pcpu_sum = _envelopes(pid_series, "cpu") |
| 357 |
if pcpu_xs: |
| 358 |
ax.plot( |
| 359 |
pcpu_xs, pcpu_max, color=PCPU_COLOR, linestyle="-", linewidth=2.0 |
| 360 |
) |
| 361 |
if args.cpu == CPU_MODE_PS_PCPU: |
| 362 |
if totals_pcpu_xs: |
| 363 |
ax.plot( |
| 364 |
totals_pcpu_xs, |
| 365 |
totals_pcpu_ys, |
| 366 |
color=PCPU_COLOR, |
| 367 |
linestyle="--", |
| 368 |
linewidth=1.5, |
| 369 |
) |
| 370 |
else: |
| 371 |
ax.plot( |
| 372 |
pcpu_xs, pcpu_sum, color=PCPU_COLOR, linestyle="--", linewidth=1.5 |
| 373 |
) |
| 374 |
rss_xs, rss_max, _ = _envelopes(pid_series, "rss") |
| 375 |
if rss_xs: |
| 376 |
ax2.plot( |
| 377 |
rss_xs, rss_max, color=RSS_COLOR, linestyle="-", linewidth=2.0 |
| 378 |
) |
| 379 |
if totals_rss_xs: |
| 380 |
ax2.plot( |
| 381 |
totals_rss_xs, |
| 382 |
totals_rss_ys, |
| 383 |
color=RSS_COLOR, |
| 384 |
linestyle="--", |
| 385 |
linewidth=1.5, |
| 386 |
) |
| 387 |
|
| 388 |
ax.set_xlabel("Elapsed Time") |
| 389 |
ax.set_ylabel(f"{args.cpu} (%)") |
| 390 |
ax2.set_ylabel("rss") |
| 391 |
if pid_series: |
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
style_handles = [ |
| 397 |
Line2D( |
| 398 |
[0], |
| 399 |
[0], |
| 400 |
color="black", |
| 401 |
linestyle="--", |
| 402 |
linewidth=1.5, |
| 403 |
label="upper bound", |
| 404 |
), |
| 405 |
Line2D( |
| 406 |
[0], |
| 407 |
[0], |
| 408 |
color="black", |
| 409 |
linestyle="-", |
| 410 |
linewidth=2.0, |
| 411 |
label="lower bound", |
| 412 |
), |
| 413 |
Line2D( |
| 414 |
[0], [0], color="black", linestyle=":", linewidth=0.8, label="per-pid" |
| 415 |
), |
| 416 |
] |
| 417 |
style_legend = ax.legend( |
| 418 |
handles=style_handles, loc="upper right", fontsize=9 |
| 419 |
) |
| 420 |
ax.add_artist(style_legend) |
| 421 |
rss_label = "rss" |
| 422 |
if host_memory_total is not None: |
| 423 |
rss_label = ( |
| 424 |
f"rss (host: {SummaryFormatter().naturalsize(host_memory_total)})" |
| 425 |
) |
| 426 |
color_handles = [ |
| 427 |
Line2D([0], [0], color=PCPU_COLOR, linewidth=2.0, label=args.cpu), |
| 428 |
Line2D([0], [0], color=RSS_COLOR, linewidth=2.0, label=rss_label), |
| 429 |
] |
| 430 |
ax.legend(handles=color_handles, loc="upper left", fontsize=9) |
| 431 |
|
| 432 |
ax.xaxis.set_major_formatter( |
| 433 |
HumanizedAxisFormatter(min_ratio=args.min_ratio, units=_TIME_UNITS) |
| 434 |
) |
| 435 |
ax2.yaxis.set_major_formatter( |
| 436 |
HumanizedAxisFormatter(min_ratio=args.min_ratio, units=FILESIZE_UNITS) |
| 437 |
) |
| 438 |
|
| 439 |
plt.title("Resource Usage Over Time (per pid)") |
| 440 |
|
| 441 |
if args.output is not None: |
| 442 |
plt.savefig(args.output) |
| 443 |
lgr.info( |
| 444 |
"Successfully rendered input file: %s to output %s", file_path, args.output |
| 445 |
) |
| 446 |
else: |
| 447 |
|
| 448 |
if backend_registry is not None: |
| 449 |
|
| 450 |
try: |
| 451 |
|
| 452 |
current_backend = matplotlib.get_backend() |
| 453 |
except AttributeError: |
| 454 |
|
| 455 |
current_backend = matplotlib.rcParams["backend"] |
| 456 |
interactive_backends = backend_registry.list_builtin( |
| 457 |
BackendFilter.INTERACTIVE |
| 458 |
) |
| 459 |
|
| 460 |
if current_backend in interactive_backends: |
| 461 |
plt.show() |
| 462 |
else: |
| 463 |
lgr.error( |
| 464 |
"Cannot display plot: your current matplotlib backend is %s " |
| 465 |
"which is a not a known interactive backend.", |
| 466 |
current_backend, |
| 467 |
) |
| 468 |
lgr.error( |
| 469 |
"Either set environment variable MPLBACKEND to an interactive backend or " |
| 470 |
"use --output to save the plot to a file instead." |
| 471 |
) |
| 472 |
lgr.error( |
| 473 |
"For more info: https://matplotlib.org/stable/users/explain/figure/backends.html" |
| 474 |
) |
| 475 |
return 1 |
| 476 |
else: |
| 477 |
|
| 478 |
|
| 479 |
plt.show() |
| 480 |
|
| 481 |
return 0 |