| 1 |
"""Platform-specific process sampling for con-duct.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
from collections import Counter, deque |
| 5 |
from datetime import datetime |
| 6 |
import logging |
| 7 |
import os |
| 8 |
import platform |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
from typing import Callable, Optional |
| 12 |
from con_duct._models import Averages, ProcessStats, Sample |
| 13 |
|
| 14 |
SYSTEM = platform.system() |
| 15 |
|
| 16 |
_SUPPORTED_SYSTEMS = {"Linux", "Darwin"} |
| 17 |
if SYSTEM not in _SUPPORTED_SYSTEMS: |
| 18 |
sys.tracebacklimit = 0 |
| 19 |
message = ( |
| 20 |
f"`con_duct` does not currently support the detected operating system ({SYSTEM}).\n\n" |
| 21 |
"If you would like to request support, please open an issue at: " |
| 22 |
"https://github.com/con/duct/issues/new" |
| 23 |
) |
| 24 |
raise NotImplementedError(message) |
| 25 |
|
| 26 |
lgr = logging.getLogger("con-duct") |
| 27 |
|
| 28 |
|
| 29 |
def _get_sample_linux(session_id: int) -> Sample: |
| 30 |
sample = Sample() |
| 31 |
|
| 32 |
ps_command = [ |
| 33 |
"ps", |
| 34 |
"-w", |
| 35 |
"-s", |
| 36 |
str(session_id), |
| 37 |
"-o", |
| 38 |
"pid,pcpu,pmem,rss,vsz,etime,stat,cmd", |
| 39 |
] |
| 40 |
output = subprocess.check_output(ps_command, text=True) |
| 41 |
|
| 42 |
for line in output.splitlines()[1:]: |
| 43 |
if not line: |
| 44 |
continue |
| 45 |
|
| 46 |
pid, pcpu, pmem, rss_kib, vsz_kib, etime, stat, cmd = line.split(maxsplit=7) |
| 47 |
|
| 48 |
sample.add_pid( |
| 49 |
pid=int(pid), |
| 50 |
stats=ProcessStats( |
| 51 |
pcpu=float(pcpu), |
| 52 |
pmem=float(pmem), |
| 53 |
rss=int(rss_kib) * 1024, |
| 54 |
vsz=int(vsz_kib) * 1024, |
| 55 |
timestamp=datetime.now().astimezone().isoformat(), |
| 56 |
etime=etime, |
| 57 |
stat=Counter([stat]), |
| 58 |
cmd=cmd, |
| 59 |
), |
| 60 |
) |
| 61 |
sample.averages = Averages.from_sample(sample=sample) |
| 62 |
return sample |
| 63 |
|
| 64 |
|
| 65 |
def _try_to_get_sid(pid: int) -> int: |
| 66 |
""" |
| 67 |
It is possible that the `pid` returned by the top `ps` call no longer exists at time of `getsid` request. |
| 68 |
""" |
| 69 |
try: |
| 70 |
return os.getsid(pid) |
| 71 |
except ProcessLookupError as exc: |
| 72 |
lgr.debug(f"Error fetching session ID for PID {pid}: {str(exc)}") |
| 73 |
return -1 |
| 74 |
|
| 75 |
|
| 76 |
def _get_ps_lines_mac() -> list[str]: |
| 77 |
ps_command = [ |
| 78 |
"ps", |
| 79 |
"-ax", |
| 80 |
"-o", |
| 81 |
"pid,pcpu,pmem,rss,vsz,etime,stat,args", |
| 82 |
] |
| 83 |
output = subprocess.check_output(ps_command, text=True) |
| 84 |
|
| 85 |
lines = [line for line in output.splitlines()[1:] if line] |
| 86 |
return lines |
| 87 |
|
| 88 |
|
| 89 |
def _add_pid_to_sample_from_line_mac( |
| 90 |
line: str, pid_to_matching_sid: dict[int, int], sample: Sample |
| 91 |
) -> None: |
| 92 |
pid, pcpu, pmem, rss_kb, vsz_kb, etime, stat, cmd = line.split(maxsplit=7) |
| 93 |
|
| 94 |
if pid_to_matching_sid.get(int(pid)) is not None: |
| 95 |
sample.add_pid( |
| 96 |
pid=int(pid), |
| 97 |
stats=ProcessStats( |
| 98 |
pcpu=float(pcpu), |
| 99 |
pmem=float(pmem), |
| 100 |
rss=int(rss_kb) * 1024, |
| 101 |
vsz=int(vsz_kb) * 1024, |
| 102 |
timestamp=datetime.now().astimezone().isoformat(), |
| 103 |
etime=etime, |
| 104 |
stat=Counter([stat]), |
| 105 |
cmd=cmd, |
| 106 |
), |
| 107 |
) |
| 108 |
|
| 109 |
|
| 110 |
def _get_sample_mac(session_id: int) -> Optional[Sample]: |
| 111 |
sample = Sample() |
| 112 |
|
| 113 |
lines = _get_ps_lines_mac() |
| 114 |
pid_to_matching_sid = { |
| 115 |
pid: sid |
| 116 |
for line in lines |
| 117 |
if (sid := _try_to_get_sid(pid=(pid := int(line.split(maxsplit=1)[0])))) |
| 118 |
== session_id |
| 119 |
} |
| 120 |
|
| 121 |
if not pid_to_matching_sid: |
| 122 |
lgr.debug(f"No processes found for session ID {session_id}.") |
| 123 |
return None |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
deque( |
| 129 |
( |
| 130 |
_add_pid_to_sample_from_line_mac( |
| 131 |
line=line, pid_to_matching_sid=pid_to_matching_sid, sample=sample |
| 132 |
) |
| 133 |
for line in lines |
| 134 |
), |
| 135 |
maxlen=0, |
| 136 |
) |
| 137 |
|
| 138 |
sample.averages = Averages.from_sample(sample=sample) |
| 139 |
return sample |
| 140 |
|
| 141 |
|
| 142 |
_get_sample_per_system = { |
| 143 |
"Linux": _get_sample_linux, |
| 144 |
"Darwin": _get_sample_mac, |
| 145 |
} |
| 146 |
_get_sample: Callable[[int], Optional[Sample]] = _get_sample_per_system[SYSTEM] |