1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
|
#!/usr/bin/env python3
"""Analyze atop history with Claude.
Reads atop's binary logs via `atop -P` (parsable output), builds a compact
digest of CPU behaviour over time, and asks Claude to interpret it.
./atop_analyze.py # today's log
./atop_analyze.py --date 20260920 # a specific day
./atop_analyze.py -b 03:00 -e 05:00 # a window
./atop_analyze.py --digest-only # just the digest, no model call
./atop_analyze.py -q "why the iowait spike at 04:10?"
The model runs through the Claude Code CLI (`claude -p`), so this uses whatever
credential Claude Code is logged in with -- including a Pro/Max subscription --
and needs no ANTHROPIC_API_KEY and no `anthropic` package.
Field layouts come from atop(1) PARSABLE OUTPUT. Every line starts with six
fields -- label host epoch date time interval -- and the rest is label-specific.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
DEFAULT_LOGDIR = "/var/log/atop"
CLAUDE_BIN = "claude"
CLAUDE_MODEL = "opus"
CLICKHOUSE_URL_ENV = "CLICKHOUSE_URL"
CLICKHOUSE_REQUEST_TIMEOUT = 120
CLICKHOUSE_COLD_START_RETRIES = 2
IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
WANTED_LABELS = {"CPU", "CPL", "PRC"}
DATE_RE = re.compile(r"^\d{4}/\d{2}/\d{2}$")
# Offsets into the label-specific fields (i.e. after the 6 common header fields).
# CPU: hertz ncpu sys user nice idle wait irq softirq steal guest freq freqperc ...
CPU_HERTZ, CPU_NCPU = 0, 1
CPU_MODES = { # name -> offset
"sys": 2, "user": 3, "nice": 4, "idle": 5,
"wait": 6, "irq": 7, "softirq": 8, "steal": 9,
}
CPU_GUEST = 10 # overlaps user mode -- excluded from the total on purpose
# CPL: ncpu load1 load5 load15 ctxsw intr
CPL_LOAD1, CPL_LOAD5, CPL_LOAD15, CPL_CTXSW, CPL_INTR = 1, 2, 3, 4, 5
# PRC: pid name state hertz utime stime nice prio rtprio policy curcpu
# sleepavg tgid is_process ...
# atop emits a line per thread as well as per process; only is_process == 'y'
# lines are real processes, and a single-threaded process's thread line
# duplicates it exactly. Counting both double-counts CPU time.
PRC_PID, PRC_NAME, PRC_STATE, PRC_HERTZ, PRC_UTIME, PRC_STIME = 0, 1, 2, 3, 4, 5
PRC_ISPROC = 13
@dataclass
class Sample:
"""One atop interval."""
epoch: int
when: str
interval: int
host: str = ""
ncpu: int = 0
hertz: int = 100
modes: dict[str, int] = field(default_factory=dict)
load1: float = 0.0
load5: float = 0.0
load15: float = 0.0
ctxsw: int = 0
intr: int = 0
procs: list[tuple[str, int, float]] = field(default_factory=list)
@property
def total_ticks(self) -> int:
return sum(self.modes.values())
def pct(self, mode: str) -> float:
total = self.total_ticks
return 100.0 * self.modes.get(mode, 0) / total if total else 0.0
@property
def busy_pct(self) -> float:
return 100.0 - self.pct("idle") - self.pct("wait")
class AtopError(RuntimeError):
pass
def log_path(date: str | None, logdir: str) -> str:
stamp = date or datetime.now().strftime("%Y%m%d")
path = os.path.join(logdir, f"atop_{stamp}")
if not os.path.exists(path):
have = sorted(f for f in os.listdir(logdir)) if os.path.isdir(logdir) else []
raise AtopError(
f"no atop log at {path}."
+ (f" Available: {', '.join(have)}" if have else " Is atop.service running?")
)
return path
def run_atop(path: str, begin: str | None, end: str | None) -> str:
if not shutil.which("atop"):
raise AtopError("atop is not installed (pacman -S atop)")
cmd = ["atop", "-r", path, "-Z", "-P", "CPU,CPL,PRC"]
if begin:
cmd += ["-b", begin]
if end:
cmd += ["-e", end]
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
except subprocess.TimeoutExpired:
raise AtopError("atop took over 180s to read the log; narrow the range with -b/-e")
if proc.returncode != 0:
raise AtopError(f"atop failed ({proc.returncode}): {proc.stderr.strip()}")
return proc.stdout
def parse(raw: str) -> list[Sample]:
"""Turn `atop -P` output into samples, dropping the since-boot RESET sample.
atop reports per-interval deltas for every sample except the first one after
a RESET marker, which holds totals since boot. Mixing the two would make the
first interval dominate everything, so the RESET sample is skipped.
"""
samples: list[Sample] = []
current: Sample | None = None
skip_this = False
for line in raw.splitlines():
if not line:
continue
if line == "RESET":
skip_this = True
continue
if line == "SEP":
if current and not skip_this:
samples.append(current)
current, skip_this = None, False
continue
parts = line.split()
if len(parts) < 7:
continue
label, host, epoch, date, tm = parts[:5]
# With -b/-e, atop interleaves its interactive-format report into
# stdout. Those lines can start with a real label (lowercase "cpu"),
# so also require the date field to actually be a date.
if label not in WANTED_LABELS or not DATE_RE.match(date):
continue
try:
interval = int(parts[5])
rest = parts[6:]
except ValueError:
continue
if current is None:
current = Sample(epoch=int(epoch), when=tm, interval=interval, host=host)
try:
if label == "CPU":
current.hertz = int(rest[CPU_HERTZ])
current.ncpu = int(rest[CPU_NCPU])
current.modes = {n: int(rest[i]) for n, i in CPU_MODES.items()}
elif label == "CPL":
current.load1 = float(rest[CPL_LOAD1])
current.load5 = float(rest[CPL_LOAD5])
current.load15 = float(rest[CPL_LOAD15])
current.ctxsw = int(rest[CPL_CTXSW])
current.intr = int(rest[CPL_INTR])
elif label == "PRC":
if rest[PRC_ISPROC] != "y":
continue # thread line, not a process
hertz = int(rest[PRC_HERTZ])
ticks = int(rest[PRC_UTIME]) + int(rest[PRC_STIME])
if ticks:
capacity = hertz * interval * max(current.ncpu or 1, 1)
pct = 100.0 * ticks / capacity if capacity else 0.0
current.procs.append((rest[PRC_NAME], int(rest[PRC_PID]), pct))
except (IndexError, ValueError):
continue # a label whose layout this atop version changed
if current and not skip_this:
samples.append(current)
for s in samples:
s.procs.sort(key=lambda p: -p[2])
return samples
def clickhouse_identifier(value: str, option: str) -> str:
"""Validate a database or table name before embedding it in SQL."""
if not IDENTIFIER_RE.match(value):
raise AtopError(f"{option} must contain only letters, digits, and underscores")
return value
def ingest_version(row: dict[str, object]) -> int:
"""Return a stable UInt64 version for one immutable source row.
The value is derived from canonical JSON rather than wall-clock time, so a
retried export of the same atop interval has exactly the same version.
"""
encoded = json.dumps(row, sort_keys=True, separators=(",", ":")).encode()
return int.from_bytes(hashlib.blake2b(encoded, digest_size=8).digest(), "big")
def clickhouse_request(
url: str, query: str, body: str, user: str | None, password: str | None,
modal_key: str | None, modal_secret: str | None,
) -> None:
"""Send one query to ClickHouse's HTTP interface."""
separator = "&" if "?" in url else "?"
endpoint = f"{url.rstrip('/')}{separator}{urllib.parse.urlencode({'query': query})}"
request = urllib.request.Request(
endpoint,
data=body.encode(),
headers={"Content-Type": "application/json; charset=utf-8"},
method="POST",
)
if user is not None:
token = base64.b64encode(f"{user}:{password or ''}".encode()).decode()
request.add_header("Authorization", f"Basic {token}")
if modal_key is not None:
request.add_header("Modal-Key", modal_key)
request.add_header("Modal-Secret", modal_secret or "")
for attempt in range(CLICKHOUSE_COLD_START_RETRIES + 1):
try:
logger.info(
"clickhouse_request operation=%s attempt=%d body_bytes=%d",
query.split(None, 1)[0], attempt + 1, len(body.encode()),
)
# A scale-to-zero Modal Web Function can take longer than a normal
# HTTP request to boot ClickHouse and attach its Volume.
with urllib.request.urlopen(request, timeout=CLICKHOUSE_REQUEST_TIMEOUT) as response:
if response.status >= 300:
raise AtopError(f"ClickHouse returned HTTP {response.status}")
logger.info("clickhouse_request_complete operation=%s", query.split(None, 1)[0])
return
except urllib.error.HTTPError as e:
detail = e.read().decode(errors="replace").strip()
raise AtopError(f"ClickHouse returned HTTP {e.code}: {detail}") from e
except (TimeoutError, urllib.error.URLError) as e:
if attempt == CLICKHOUSE_COLD_START_RETRIES:
reason = getattr(e, "reason", str(e))
raise AtopError(f"could not reach ClickHouse at {url}: {reason}") from e
delay = 5 * (attempt + 1)
logger.warning(
"clickhouse_request_retry operation=%s delay_seconds=%d reason=%s",
query.split(None, 1)[0], delay, getattr(e, "reason", str(e)),
)
time.sleep(delay)
def write_clickhouse(
samples: list[Sample], url: str, database: str, sample_table: str,
process_table: str, user: str | None, password: str | None,
modal_key: str | None, modal_secret: str | None, initialize: bool,
) -> None:
"""Store parsed atop samples and per-process CPU attribution in ClickHouse."""
database = clickhouse_identifier(database, "--clickhouse-database")
sample_table = clickhouse_identifier(sample_table, "--clickhouse-sample-table")
process_table = clickhouse_identifier(process_table, "--clickhouse-process-table")
samples_target = f"`{database}`.`{sample_table}`"
processes_target = f"`{database}`.`{process_table}`"
if initialize:
clickhouse_request(url, f"CREATE DATABASE IF NOT EXISTS `{database}`", "", user, password,
modal_key, modal_secret)
clickhouse_request(url, f"""CREATE TABLE IF NOT EXISTS {samples_target} (
host LowCardinality(String), epoch DateTime, interval_seconds UInt32,
ncpu UInt16, user_pct Float32, sys_pct Float32, nice_pct Float32,
idle_pct Float32, wait_pct Float32, irq_pct Float32, softirq_pct Float32,
steal_pct Float32, busy_pct Float32, load1 Float32, load5 Float32,
load15 Float32, ctxsw UInt64, intr UInt64, ingest_version UInt64
) ENGINE = ReplacingMergeTree(ingest_version) ORDER BY (host, epoch)""", "", user, password,
modal_key, modal_secret)
clickhouse_request(url, f"""CREATE TABLE IF NOT EXISTS {processes_target} (
host LowCardinality(String), epoch DateTime, pid UInt32,
name LowCardinality(String), cpu_pct Float32, interval_seconds UInt32,
ingest_version UInt64
) ENGINE = ReplacingMergeTree(ingest_version) ORDER BY (host, epoch, pid, name)""", "", user, password,
modal_key, modal_secret)
# Existing installations used ReplacingMergeTree without a version
# column. Adding it is non-destructive; Grafana's argMax queries below
# make those legacy tables deterministic immediately as well.
clickhouse_request(url, f"ALTER TABLE {samples_target} ADD COLUMN IF NOT EXISTS ingest_version UInt64 DEFAULT 0",
"", user, password, modal_key, modal_secret)
clickhouse_request(url, f"ALTER TABLE {processes_target} ADD COLUMN IF NOT EXISTS ingest_version UInt64 DEFAULT 0",
"", user, password, modal_key, modal_secret)
sample_rows = [
{
"host": s.host, "epoch": s.epoch, "interval_seconds": s.interval,
"ncpu": s.ncpu, "user_pct": s.pct("user"), "sys_pct": s.pct("sys"),
"nice_pct": s.pct("nice"), "idle_pct": s.pct("idle"),
"wait_pct": s.pct("wait"), "irq_pct": s.pct("irq"),
"softirq_pct": s.pct("softirq"), "steal_pct": s.pct("steal"),
"busy_pct": s.busy_pct, "load1": s.load1, "load5": s.load5,
"load15": s.load15, "ctxsw": s.ctxsw, "intr": s.intr,
}
for s in samples
]
for row in sample_rows:
row["ingest_version"] = ingest_version(row)
process_rows = [
{"host": s.host, "epoch": s.epoch, "pid": pid, "name": name,
"cpu_pct": pct, "interval_seconds": s.interval}
for s in samples for name, pid, pct in s.procs
]
for row in process_rows:
row["ingest_version"] = ingest_version(row)
clickhouse_request(url, f"INSERT INTO {samples_target} FORMAT JSONEachRow",
"\n".join(json.dumps(row) for row in sample_rows), user, password,
modal_key, modal_secret)
if process_rows:
clickhouse_request(url, f"INSERT INTO {processes_target} FORMAT JSONEachRow",
"\n".join(json.dumps(row) for row in process_rows), user, password,
modal_key, modal_secret)
def bucket(samples: list[Sample], max_rows: int) -> list[list[Sample]]:
"""Group samples into at most max_rows contiguous buckets."""
if len(samples) <= max_rows:
return [[s] for s in samples]
size = -(-len(samples) // max_rows) # ceil
return [samples[i : i + size] for i in range(0, len(samples), size)]
def digest(samples: list[Sample], top: int, max_rows: int) -> str:
"""Build a compact, token-bounded text summary of the run."""
ncpu = next((s.ncpu for s in samples if s.ncpu), 0)
span = f"{samples[0].when}-{samples[-1].when}"
out: list[str] = [
f"host cores: {ncpu}",
f"window: {span} samples: {len(samples)} interval: {samples[0].interval}s",
"",
"TIMELINE (CPU% of whole machine; load1 = 1-min load average)",
f"{'time':>9} {'busy':>6} {'user':>6} {'sys':>6} {'wait':>6} {'irq':>5} "
f"{'stl':>5} {'load1':>6} top consumers",
]
for group in bucket(samples, max_rows):
n = len(group)
avg = lambda fn: sum(fn(s) for s in group) / n # noqa: E731
label = group[0].when if n == 1 else f"{group[0].when[:5]}+{n}"
merged: dict[str, float] = defaultdict(float)
for s in group:
for name, _pid, pct in s.procs:
merged[name] += pct / n
leaders = sorted(merged.items(), key=lambda kv: -kv[1])[:3]
tops = " ".join(f"{name}:{pct:.0f}%" for name, pct in leaders if pct >= 1.0)
out.append(
f"{label:>9} {avg(lambda s: s.busy_pct):6.1f} "
f"{avg(lambda s: s.pct('user') + s.pct('nice')):6.1f} "
f"{avg(lambda s: s.pct('sys')):6.1f} {avg(lambda s: s.pct('wait')):6.1f} "
f"{avg(lambda s: s.pct('irq') + s.pct('softirq')):5.1f} "
f"{avg(lambda s: s.pct('steal')):5.1f} "
f"{avg(lambda s: s.load1):6.2f} {tops}"
)
# Overall leaders, weighted by interval so uneven samples don't skew it.
total_secs: dict[str, float] = defaultdict(float)
pids: dict[str, set[int]] = defaultdict(set)
for s in samples:
cores = max(s.ncpu or 1, 1)
for name, pid, pct in s.procs:
total_secs[name] += pct / 100.0 * cores * s.interval
pids[name].add(pid)
wall = sum(s.interval for s in samples) or 1
out += ["", f"TOP PROCESSES over the whole window ({wall}s wall clock)",
f"{'process':<24} {'cpu-sec':>9} {'avg-cores':>10} {'pids':>5}"]
for name, secs in sorted(total_secs.items(), key=lambda kv: -kv[1])[:top]:
out.append(f"{name:<24} {secs:9.1f} {secs / wall:10.2f} {len(pids[name]):5d}")
peak = max(samples, key=lambda s: s.busy_pct)
out += ["", f"PEAK SAMPLE {peak.when} busy {peak.busy_pct:.1f}% "
f"wait {peak.pct('wait'):.1f}% load1 {peak.load1:.2f} "
f"ctxsw {peak.ctxsw} intr {peak.intr}"]
for name, pid, pct in peak.procs[:10]:
out.append(f" {name:<24} pid {pid:<8} {pct:5.1f}% of machine")
return "\n".join(out)
SYSTEM = """You are a Linux performance engineer reading atop history.
The digest gives per-interval CPU state plus per-process CPU attribution.
Ground every claim in the numbers shown and cite the timestamps you used.
Interpret carefully:
- Percentages are of the WHOLE machine, so one saturated core on an 8-core box
is ~12.5%, not 100%.
- High 'wait' (iowait) means blocked on I/O, not CPU pressure -- do not call it
a CPU bottleneck.
- Load average counts runnable AND uninterruptible-sleep tasks, so load can be
high while CPU sits idle. Say which one the data supports.
- Sampled intervals average away short spikes. If the interval is coarse
(>= 300s) say so rather than reading precise events into it.
- Per-process rows only cover processes alive at sample time; short-lived
processes may be missing from attribution while still showing in system time.
Structure the answer as: verdict (one or two sentences), then the evidence,
then what to check next as concrete commands. Say plainly when the data is
insufficient instead of speculating."""
def analyze(
text: str, question: str | None, effort: str, model: str, claude_bin: str
) -> int:
"""Pipe the digest through `claude -p`, inheriting Claude Code's own login."""
if not shutil.which(claude_bin):
print(f"error: {claude_bin} not found on PATH. Install Claude Code, or "
f"use --digest-only for the numbers without analysis.",
file=sys.stderr)
return 1
ask = question or (
"Analyze this CPU history. What used the CPU, was the machine actually "
"CPU-bound, and is anything here worth investigating?"
)
# The digest goes in on stdin rather than argv -- a long window can run to
# tens of kilobytes, past the point where argv limits get interesting.
prompt = f"{ask}\n\n<atop_digest>\n{text}\n</atop_digest>"
cmd = [
claude_bin, "-p",
"--model", model,
"--effort", effort,
"--system-prompt", SYSTEM, # replaces the coding-agent prompt wholesale
"--restricted", # this is pure text analysis; no tools needed
]
try:
# stdout/stderr are inherited, so the response streams as it arrives.
proc = subprocess.run(cmd, input=prompt, text=True)
except OSError as e:
print(f"error: could not run {claude_bin}: {e}", file=sys.stderr)
return 1
except KeyboardInterrupt:
return 130
if proc.returncode != 0:
print(f"\nerror: {claude_bin} exited {proc.returncode}. If this is an "
f"auth problem, run `claude` once interactively to log in.",
file=sys.stderr)
return proc.returncode
def main() -> int:
p = argparse.ArgumentParser(description="Analyze atop CPU history with Claude.")
src = p.add_mutually_exclusive_group()
src.add_argument("--date", help="log day as YYYYMMDD (default: today)")
src.add_argument("--file", help="path to a raw atop log")
p.add_argument("--logdir", default=DEFAULT_LOGDIR)
p.add_argument("-b", "--begin", help="start time HH:MM")
p.add_argument("-e", "--end", help="end time HH:MM")
p.add_argument("-q", "--question", help="ask something specific")
p.add_argument("--top", type=int, default=15, help="processes to rank (default 15)")
p.add_argument("--max-rows", type=int, default=60,
help="timeline rows; extra samples are averaged into buckets")
p.add_argument("--effort", default="high",
choices=["low", "medium", "high", "xhigh", "max"])
p.add_argument("--model", default=CLAUDE_MODEL,
help=f"model alias or full name (default: {CLAUDE_MODEL})")
p.add_argument("--claude-bin", default=CLAUDE_BIN,
help="path to the claude CLI")
p.add_argument("--digest-only", action="store_true",
help="print the digest and exit; runs no model")
p.add_argument("--clickhouse-url", default=os.environ.get(CLICKHOUSE_URL_ENV),
help=f"ClickHouse HTTP endpoint (default: ${CLICKHOUSE_URL_ENV})")
p.add_argument("--clickhouse-database", default="default",
help="ClickHouse database (default: default)")
p.add_argument("--clickhouse-sample-table", default="atop_samples",
help="ClickHouse interval table (default: atop_samples)")
p.add_argument("--clickhouse-process-table", default="atop_processes",
help="ClickHouse process-attribution table (default: atop_processes)")
p.add_argument("--clickhouse-user", default=os.environ.get("CLICKHOUSE_USER"),
help="ClickHouse basic-auth user (default: $CLICKHOUSE_USER)")
p.add_argument("--clickhouse-password", default=os.environ.get("CLICKHOUSE_PASSWORD"),
help="ClickHouse basic-auth password (default: $CLICKHOUSE_PASSWORD)")
p.add_argument("--clickhouse-modal-key", default=os.environ.get("MODAL_KEY"),
help="Modal Proxy Token ID for a protected Modal endpoint (default: $MODAL_KEY)")
p.add_argument("--clickhouse-modal-secret", default=os.environ.get("MODAL_SECRET"),
help="Modal Proxy Token secret for a protected Modal endpoint (default: $MODAL_SECRET)")
p.add_argument("--clickhouse-init", action="store_true",
help="create the ClickHouse database and tables if missing")
args = p.parse_args()
try:
path = args.file or log_path(args.date, args.logdir)
samples = parse(run_atop(path, args.begin, args.end))
except AtopError as e:
print(f"error: {e}", file=sys.stderr)
return 1
except PermissionError:
print(f"error: cannot read {args.logdir} -- try run0", file=sys.stderr)
return 1
if not samples:
print("error: no usable samples in range. atop's first sample holds "
"since-boot totals and is skipped, so a freshly started atop has "
"nothing to compare yet -- wait for one more interval.",
file=sys.stderr)
return 1
if args.clickhouse_init and not args.clickhouse_url:
p.error("--clickhouse-init requires --clickhouse-url or $CLICKHOUSE_URL")
if bool(args.clickhouse_modal_key) != bool(args.clickhouse_modal_secret):
p.error("--clickhouse-modal-key and --clickhouse-modal-secret must be supplied together")
if args.clickhouse_url:
try:
write_clickhouse(
samples, args.clickhouse_url, args.clickhouse_database,
args.clickhouse_sample_table, args.clickhouse_process_table,
args.clickhouse_user, args.clickhouse_password,
args.clickhouse_modal_key, args.clickhouse_modal_secret,
args.clickhouse_init,
)
except AtopError as e:
print(f"error: ClickHouse export failed: {e}", file=sys.stderr)
return 1
process_count = sum(len(s.procs) for s in samples)
print(f"# exported {len(samples)} samples and {process_count} process rows to ClickHouse",
file=sys.stderr)
text = digest(samples, args.top, args.max_rows)
if args.digest_only:
print(text)
return 0
print(f"# {len(samples)} samples from {path}\n", file=sys.stderr)
return analyze(text, args.question, args.effort, args.model, args.claude_bin)
if __name__ == "__main__":
sys.exit(main())
|