Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
498 lines (437 loc) · 16.2 KB
/
Copy pathcli.py
File metadata and controls
498 lines (437 loc) · 16.2 KB
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
"""The `cgr trace` command group: runtime call-trace ingestion."""
from __future__ import annotations
import sys
from pathlib import Path
import click
from loguru import logger
from .. import cli_help as ch
@click.group(
help=ch.CMD_TRACE_GROUP,
short_help=ch.CMD_TRACE_GROUP,
epilog=ch.EPILOG_TRACE,
no_args_is_help=True,
)
def cli() -> None:
"""Group callback: subcommands carry the behaviour."""
@cli.command(
"ingest",
help=ch.CMD_TRACE_INGEST,
short_help=ch.CMD_TRACE_INGEST,
epilog=ch.EXAMPLES_TRACE_INGEST,
)
@click.argument(
"trace_file",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
)
@click.option(
"--repo-path",
type=click.Path(exists=True, file_okay=False, path_type=Path),
required=True,
help=ch.HELP_TRACE_REPO_PATH,
)
@click.option("--project-name", default=None, help=ch.HELP_TRACE_PROJECT_NAME)
def ingest_cmd(trace_file: Path, repo_path: Path, project_name: str | None) -> None:
from ..config import settings
from ..main import connect_memgraph
from ..utils.path_utils import derive_project_name
from .ingest import ingest_trace
from .records import TraceFormatError
resolved_project = project_name or derive_project_name(repo_path)
try:
with connect_memgraph(batch_size=settings.resolve_batch_size(None)) as ingestor:
summary = ingest_trace(
trace_path=trace_file,
ingestor=ingestor,
repo_path=repo_path,
project_name=resolved_project,
)
except TraceFormatError as e:
logger.error(str(e))
click.secho(str(e), fg="red", err=True)
sys.exit(1)
click.echo(
f"records: {summary.records}\n"
f"edges written: {summary.edges}\n"
f"confirmed static: {summary.confirmed_static}\n"
f"static missed: {summary.static_missed}\n"
f"unresolved: {summary.unresolved}"
)
for reason, count in sorted(summary.resolution.unresolved.items()):
click.echo(f" unresolved[{reason}]: {count}")
class _ConvertUsageError(Exception):
"""A convert invocation missing an option the detected format requires."""
def _convert_for_language(
profile_file: Path,
repo_path: Path | None,
resolved_output: Path,
workload: str | None,
language: str,
) -> int:
"""Convert with an explicit ``--language`` override, bypassing sniffing.
Rust pprof profiles are gzipped protobufs indistinguishable from Go's by
magic bytes, so an explicit override is the only way to select the Rust
demangler.
"""
from .. import constants as cs
if language == cs.TRACE_LANGUAGE_RUST:
from .rust_pprof import convert_rust_pprof
return convert_rust_pprof(
profile_file,
repo_root=_require_repo(repo_path),
output=resolved_output,
workload=workload,
)
raise _ConvertUsageError(
ch.ERR_TRACE_CONVERT_BAD_LANGUAGE.format(
language=language, supported=cs.TRACE_LANGUAGE_RUST
)
)
def _require_repo(repo_path: Path | None) -> Path:
"""Return ``repo_path`` or raise the usage error when a format needs it."""
if repo_path is None:
raise _ConvertUsageError(ch.ERR_TRACE_CONVERT_NEEDS_REPO)
return repo_path
def _parse_key_value(value: str, error_template: str) -> tuple[str, str]:
"""Split a ``KEY=VALUE`` option; a usage error when it lacks ``=`` or a key.
An empty key (``=value``) would re-anchor every path or select no label, so
it is rejected rather than silently matching everything.
"""
key, sep, val = value.partition("=")
if not sep or not key:
raise _ConvertUsageError(error_template.format(value=value))
return key, val
def _warn_commit_mismatch(commit: str | None, repo_path: Path) -> None:
"""Warn when the profiled binary's commit differs from the repo HEAD."""
if commit is None:
return
import subprocess
from .. import constants as cs
try:
result = subprocess.run(
["git", "-C", str(repo_path), "rev-parse", "HEAD"],
capture_output=True,
text=True,
encoding=cs.ENCODING_UTF8,
check=False,
)
except OSError:
return
head = result.stdout.strip()
if head and not head.startswith(commit) and not commit.startswith(head):
message = ch.MSG_TRACE_COMMIT_MISMATCH.format(profiled=commit, head=head)
logger.warning(message)
click.secho(message, fg="yellow", err=True)
def _convert_ebpf(
profile_file: Path,
repo_path: Path | None,
resolved_output: Path,
workload: str | None,
language: str | None,
path_map: tuple[str, ...],
build_id: str | None,
service: str | None,
label: str | None,
commit: str | None,
) -> int:
"""Convert an eBPF-profiler pprof profile with re-anchoring and filtering."""
from .. import constants as cs
from .ebpf_pprof import convert_ebpf_pprof
repo = _require_repo(repo_path)
mappings = [
_parse_key_value(entry, ch.ERR_TRACE_CONVERT_BAD_PATH_MAP) for entry in path_map
]
service_pair = (
_parse_key_value(service, ch.ERR_TRACE_CONVERT_BAD_SERVICE) if service else None
)
_warn_commit_mismatch(commit, repo)
return convert_ebpf_pprof(
profile_file,
repo_root=repo,
output=resolved_output,
workload=workload,
path_map=mappings,
build_id=build_id,
service=service_pair,
workload_label=label,
language=language or cs.TRACE_LANGUAGE_GO,
)
# A merged fleet pprof profile is aggregated and small; cap the download so a
# malicious or runaway endpoint cannot exhaust memory or run unattended forever.
_MAX_PROFILE_BYTES = 256 * 1024 * 1024
def _redact_url(url: str) -> str:
"""A log-safe form of a URL: scheme, host, and path, without userinfo/query."""
import urllib.parse
parts = urllib.parse.urlsplit(url)
return urllib.parse.urlunsplit(
(parts.scheme, parts.hostname or "", parts.path, "", "")
)
def _download_pprof(url: str, headers: tuple[str, ...], timeout: float) -> bytes:
"""GET a pprof profile over HTTP(S); a usage error on a bad URL or failure.
Redirects are followed but never carry credentials across them and must stay
on http(s); the body is read under a size cap. ``urllib.error.URLError`` is
an ``OSError`` subclass, so one ``except OSError`` covers both.
"""
import urllib.parse
import urllib.request
if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
raise _ConvertUsageError(ch.ERR_TRACE_PULL_BAD_URL.format(url=_redact_url(url)))
request = urllib.request.Request(url) # noqa: S310 - scheme checked above
for header in headers:
key, value = _parse_key_value(header, ch.ERR_TRACE_PULL_BAD_HEADER)
# Every caller-supplied header goes in unredirected: it was meant for this
# endpoint, and any of them (Authorization, X-Api-Key, X-Scope-OrgID, ...)
# may be a credential, so urllib must not resend it to a redirect target.
request.add_unredirected_header(key, value)
# An opener with only HTTP(S) handlers: a redirect to file:// or ftp:// has no
# handler and fails, so a redirect cannot bypass the scheme check above.
opener = urllib.request.OpenerDirector()
for handler in (
urllib.request.HTTPHandler,
urllib.request.HTTPSHandler,
urllib.request.HTTPRedirectHandler,
urllib.request.HTTPErrorProcessor,
urllib.request.HTTPDefaultErrorHandler,
):
opener.add_handler(handler())
try:
with opener.open(request, timeout=timeout) as response: # noqa: S310
data = response.read(_MAX_PROFILE_BYTES + 1)
except OSError as e:
raise _ConvertUsageError(
ch.ERR_TRACE_PULL_FAILED.format(url=_redact_url(url), error=e)
) from e
if len(data) > _MAX_PROFILE_BYTES:
raise _ConvertUsageError(
ch.ERR_TRACE_PULL_TOO_LARGE.format(url=_redact_url(url))
)
return data
def _convert_profile(
profile_file: Path,
repo_path: Path | None,
resolved_output: Path,
include: str | None,
workload: str | None,
language: str | None = None,
) -> int:
"""Dispatch by profile format and write records; returns the record count.
Raises ``_ConvertUsageError`` when the format needs an option the caller
did not supply, and ``TraceFormatError``/``OSError``/``JSONDecodeError``
for unreadable or malformed profiles.
"""
import json
if language is not None:
return _convert_for_language(
profile_file, repo_path, resolved_output, workload, language
)
if profile_file.suffix == ".addrs":
# C/C++ instrumented address traces need symbolisation plus the repo.
from .instrumented import convert_instrumented
return convert_instrumented(
profile_file,
repo_root=_require_repo(repo_path),
output=resolved_output,
workload=workload,
)
with profile_file.open("rb") as fh:
magic = fh.read(2)
if magic == b"\x1f\x8b" or profile_file.suffix == ".pprof":
# Go pprof CPU profiles are gzipped protobufs.
from .pprof import convert_pprof
return convert_pprof(
profile_file,
repo_root=_require_repo(repo_path),
output=resolved_output,
workload=workload,
)
if profile_file.suffix == ".xt":
from .xdebug import convert_xdebug_trace
return convert_xdebug_trace(
profile_file, output=resolved_output, workload=workload
)
raw = json.loads(profile_file.read_text(encoding="utf-8"))
looks_like_cpuprofile = (isinstance(raw, dict) and "nodes" in raw) or (
profile_file.suffix == ".cpuprofile"
)
if looks_like_cpuprofile:
# V8 cpuprofile: frames carry file URLs, so scoping needs the repo.
from .cpuprofile import convert_cpuprofile
return convert_cpuprofile(
profile_file,
repo_root=_require_repo(repo_path),
output=resolved_output,
workload=workload,
)
# dotnet-trace speedscope: frames carry no paths, so scoping needs
# namespace prefixes.
from .speedscope import convert_speedscope
prefixes = tuple(p.strip() for p in (include or "").split(",") if p.strip())
if not prefixes:
raise _ConvertUsageError(ch.ERR_TRACE_CONVERT_NEEDS_INCLUDE)
return convert_speedscope(
profile_file, output=resolved_output, include=prefixes, workload=workload
)
@cli.command(
"convert",
help=ch.CMD_TRACE_CONVERT,
short_help=ch.CMD_TRACE_CONVERT,
epilog=ch.EXAMPLES_TRACE_CONVERT,
)
@click.argument(
"profile_file",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
)
@click.option(
"--repo-path",
type=click.Path(exists=True, file_okay=False, path_type=Path),
default=None,
help=ch.HELP_TRACE_REPO_PATH,
)
@click.option(
"--output",
"-o",
type=click.Path(dir_okay=False, path_type=Path),
default=None,
help=ch.HELP_TRACE_OUTPUT,
)
@click.option("--include", default=None, help=ch.HELP_TRACE_INCLUDE)
@click.option("--workload", default=None, help=ch.HELP_TRACE_WORKLOAD)
@click.option("--language", default=None, help=ch.HELP_TRACE_LANGUAGE)
@click.option("--format", "fmt", default=None, help=ch.HELP_TRACE_FORMAT)
@click.option("--path-map", "path_map", multiple=True, help=ch.HELP_TRACE_PATH_MAP)
@click.option("--build-id", default=None, help=ch.HELP_TRACE_BUILD_ID)
@click.option("--service", default=None, help=ch.HELP_TRACE_SERVICE)
@click.option("--label", default=None, help=ch.HELP_TRACE_LABEL)
@click.option("--commit", default=None, help=ch.HELP_TRACE_COMMIT)
def convert_cmd(
profile_file: Path,
repo_path: Path | None,
output: Path | None,
include: str | None,
workload: str | None,
language: str | None,
fmt: str | None,
path_map: tuple[str, ...],
build_id: str | None,
service: str | None,
label: str | None,
commit: str | None,
) -> None:
from .. import constants as cs
resolved_output = output or Path(cs.TRACE_DEFAULT_OUTPUT)
try:
if fmt == "ebpf":
count = _convert_ebpf(
profile_file,
repo_path,
resolved_output,
workload,
language,
path_map,
build_id,
service,
label,
commit,
)
elif fmt is not None:
raise _ConvertUsageError(ch.ERR_TRACE_CONVERT_BAD_FORMAT.format(format=fmt))
else:
count = _convert_profile(
profile_file, repo_path, resolved_output, include, workload, language
)
# TraceFormatError subclasses ValueError, so ValueError covers it (and the
# malformed-number / non-UTF-8 cases) without listing it redundantly.
except (OSError, ValueError, _ConvertUsageError) as e:
logger.error(str(e))
click.secho(str(e), fg="red", err=True)
sys.exit(1)
click.echo(f"call records written: {count} -> {resolved_output}")
@cli.command(
"pull",
help=ch.CMD_TRACE_PULL,
short_help=ch.CMD_TRACE_PULL,
epilog=ch.EXAMPLES_TRACE_PULL,
)
@click.argument("url")
@click.option(
"--repo-path",
type=click.Path(exists=True, file_okay=False, path_type=Path),
default=None,
help=ch.HELP_TRACE_REPO_PATH,
)
@click.option(
"--output",
"-o",
type=click.Path(dir_okay=False, path_type=Path),
default=None,
help=ch.HELP_TRACE_OUTPUT,
)
@click.option(
"--save",
type=click.Path(dir_okay=False, path_type=Path),
default=None,
help=ch.HELP_TRACE_PULL_SAVE,
)
@click.option("--header", "headers", multiple=True, help=ch.HELP_TRACE_PULL_HEADER)
@click.option("--timeout", default=60.0, type=float, help=ch.HELP_TRACE_PULL_TIMEOUT)
@click.option("--workload", default=None, help=ch.HELP_TRACE_WORKLOAD)
@click.option("--language", default=None, help=ch.HELP_TRACE_LANGUAGE)
@click.option("--path-map", "path_map", multiple=True, help=ch.HELP_TRACE_PATH_MAP)
@click.option("--build-id", default=None, help=ch.HELP_TRACE_BUILD_ID)
@click.option("--service", default=None, help=ch.HELP_TRACE_SERVICE)
@click.option("--label", default=None, help=ch.HELP_TRACE_LABEL)
@click.option("--commit", default=None, help=ch.HELP_TRACE_COMMIT)
def pull_cmd(
url: str,
repo_path: Path | None,
output: Path | None,
save: Path | None,
headers: tuple[str, ...],
timeout: float,
workload: str | None,
language: str | None,
path_map: tuple[str, ...],
build_id: str | None,
service: str | None,
label: str | None,
commit: str | None,
) -> None:
import os
import tempfile
from .. import constants as cs
resolved_output = output or Path(cs.TRACE_DEFAULT_OUTPUT)
try:
if save is not None and save.resolve() == resolved_output.resolve():
raise _ConvertUsageError(ch.ERR_TRACE_PULL_SAVE_EQUALS_OUTPUT)
data = _download_pprof(url, headers, timeout)
# Persist the profile where the caller asked, else in a temp file that is
# removed after conversion (a cron overlay does not need to keep it).
# mkstemp returns an open fd; close it so Windows does not lock the file
# against the write below.
if save is not None:
profile_path = save
else:
handle, temp_name = tempfile.mkstemp(suffix=".pb.gz", prefix="cgr-ebpf-")
os.close(handle)
profile_path = Path(temp_name)
try:
profile_path.write_bytes(data)
count = _convert_ebpf(
profile_path,
repo_path,
resolved_output,
workload,
language,
path_map,
build_id,
service,
label,
commit,
)
finally:
if save is None:
profile_path.unlink(missing_ok=True)
except (OSError, ValueError, _ConvertUsageError) as e:
logger.error(str(e))
click.secho(str(e), fg="red", err=True)
sys.exit(1)
click.echo(f"call records written: {count} -> {resolved_output}")