ctxflow-otel 0.2.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ctxflow_otel/__init__.py +113 -0
- ctxflow_otel/__main__.py +5 -0
- ctxflow_otel/check.py +538 -0
- ctxflow_otel/cli.py +51 -0
- ctxflow_otel/config.py +50 -0
- ctxflow_otel/conversation.py +85 -0
- ctxflow_otel/distro.py +175 -0
- ctxflow_otel/export.py +82 -0
- ctxflow_otel/identity.py +76 -0
- ctxflow_otel/ingest/__init__.py +286 -0
- ctxflow_otel/ingest/common.py +307 -0
- ctxflow_otel/ingest/docling.py +308 -0
- ctxflow_otel/ingest/llamaindex.py +1137 -0
- ctxflow_otel/ingest/unstructured.py +537 -0
- ctxflow_otel/ingest/unstructured_pipeline.py +269 -0
- ctxflow_otel/instrumentors.py +94 -0
- ctxflow_otel/llamaindex.py +150 -0
- ctxflow_otel/mcp.py +280 -0
- ctxflow_otel/py.typed +0 -0
- ctxflow_otel/retrieval.py +83 -0
- ctxflow_otel/text.py +56 -0
- ctxflow_otel-0.2.2.dist-info/METADATA +174 -0
- ctxflow_otel-0.2.2.dist-info/RECORD +26 -0
- ctxflow_otel-0.2.2.dist-info/WHEEL +4 -0
- ctxflow_otel-0.2.2.dist-info/entry_points.txt +19 -0
- ctxflow_otel-0.2.2.dist-info/licenses/LICENSE +202 -0
ctxflow_otel/__init__.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""ctxflow OpenTelemetry distribution for Python.
|
|
2
|
+
|
|
3
|
+
Three integration levels: `ctxflow-instrument python app.py` (no code), `init()` (one line) and
|
|
4
|
+
`attach(provider)` (processors only, for a provider you own).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import threading
|
|
9
|
+
import weakref
|
|
10
|
+
|
|
11
|
+
from opentelemetry import trace
|
|
12
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
13
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
14
|
+
from opentelemetry.trace import ProxyTracerProvider
|
|
15
|
+
|
|
16
|
+
from ctxflow_otel.config import Config
|
|
17
|
+
from ctxflow_otel.conversation import conversation
|
|
18
|
+
from ctxflow_otel.distro import (
|
|
19
|
+
configure_sdk,
|
|
20
|
+
export_processor_factory,
|
|
21
|
+
installed,
|
|
22
|
+
warn_ignored_custody,
|
|
23
|
+
warn_ignored_usage,
|
|
24
|
+
)
|
|
25
|
+
from ctxflow_otel.identity import IdentityProcessor
|
|
26
|
+
from ctxflow_otel.ingest import instrument_ingest
|
|
27
|
+
from ctxflow_otel.ingest.common import content_hash, source_hash
|
|
28
|
+
from ctxflow_otel.mcp import instrument_mcp
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Config",
|
|
32
|
+
"IdentityProcessor",
|
|
33
|
+
"attach",
|
|
34
|
+
"content_hash",
|
|
35
|
+
"conversation",
|
|
36
|
+
"init",
|
|
37
|
+
"source_hash",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
_log = logging.getLogger(__name__)
|
|
41
|
+
_lock = threading.RLock()
|
|
42
|
+
_provider: TracerProvider | None = None
|
|
43
|
+
_config: Config | None = None
|
|
44
|
+
_attached: weakref.WeakSet[TracerProvider] = weakref.WeakSet()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def attach(provider: TracerProvider, config: Config | None = None) -> None:
|
|
48
|
+
"""Add ctxflow to an existing `TracerProvider` ("processors only"). Idempotent per provider.
|
|
49
|
+
|
|
50
|
+
Adds `IdentityProcessor` and a `BatchSpanProcessor` over an `OTLPSpanExporter` (it reads
|
|
51
|
+
`OTEL_EXPORTER_OTLP_*`): content, ids and hashes leave as they are, and retrieval spans get
|
|
52
|
+
their item identity.
|
|
53
|
+
The other exporters of the same provider are not altered and still see the raw spans.
|
|
54
|
+
`config` has no setting that applies here today; it is kept so callers do not break.
|
|
55
|
+
"""
|
|
56
|
+
with _lock:
|
|
57
|
+
if provider in _attached:
|
|
58
|
+
return
|
|
59
|
+
_attached.add(provider)
|
|
60
|
+
warn_ignored_custody()
|
|
61
|
+
warn_ignored_usage()
|
|
62
|
+
provider.add_span_processor(IdentityProcessor())
|
|
63
|
+
provider.add_span_processor(export_processor_factory()(OTLPSpanExporter()))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def init(config: Config | None = None) -> TracerProvider:
|
|
67
|
+
"""Install the ctxflow tracer provider. Idempotent: returns the provider.
|
|
68
|
+
|
|
69
|
+
Uses the same `CtxflowConfigurator` as `ctxflow-instrument`, so it reads the `OTEL_*`
|
|
70
|
+
variables (exporter, endpoint, service name, propagators...) and the `CTXFLOW_*` ones. If an
|
|
71
|
+
SDK provider is already the global one, ctxflow is attached to it instead of creating a new
|
|
72
|
+
provider; any other provider type is an error. If the `[mcp]` extra is installed, the MCP SDK
|
|
73
|
+
is instrumented so trace context and baggage travel in `params._meta`. The ingestion extras
|
|
74
|
+
installed (`[llamaindex]`) are enabled too (`instrument_ingest()`). LlamaIndex agent spans are
|
|
75
|
+
not: instrument `LlamaIndexInstrumentor` yourself, with your own `TraceConfig`.
|
|
76
|
+
"""
|
|
77
|
+
global _provider, _config
|
|
78
|
+
cfg = config or Config.from_env()
|
|
79
|
+
with _lock:
|
|
80
|
+
if _provider is not None:
|
|
81
|
+
if config is not None and config != _config:
|
|
82
|
+
_log.warning("init() called again with a different config; keeping the first one")
|
|
83
|
+
return _provider
|
|
84
|
+
current = trace.get_tracer_provider()
|
|
85
|
+
ours = installed()
|
|
86
|
+
if ours is not None and ours[0] is current:
|
|
87
|
+
# `ctxflow-instrument` (or an earlier configure) already installed the pipeline.
|
|
88
|
+
provider, used = ours
|
|
89
|
+
if config is not None and config != used:
|
|
90
|
+
_log.warning("init() config differs from the one already in use; keeping that one")
|
|
91
|
+
cfg = used
|
|
92
|
+
elif isinstance(current, TracerProvider):
|
|
93
|
+
_log.warning("A TracerProvider is already set; adding ctxflow processors to it")
|
|
94
|
+
attach(current, cfg)
|
|
95
|
+
provider = current
|
|
96
|
+
elif isinstance(current, ProxyTracerProvider):
|
|
97
|
+
configure_sdk(cfg)
|
|
98
|
+
created = installed()
|
|
99
|
+
if created is None or created[0] is not trace.get_tracer_provider():
|
|
100
|
+
raise RuntimeError(
|
|
101
|
+
"The ctxflow configurator did not install an SDK TracerProvider "
|
|
102
|
+
"(is OTEL_SDK_DISABLED set, or did another provider win a race?)"
|
|
103
|
+
)
|
|
104
|
+
provider = created[0]
|
|
105
|
+
else:
|
|
106
|
+
raise RuntimeError(
|
|
107
|
+
f"A non-SDK tracer provider ({type(current).__name__}) is already set; "
|
|
108
|
+
"ctxflow_otel needs the OpenTelemetry SDK TracerProvider"
|
|
109
|
+
)
|
|
110
|
+
_provider, _config = provider, cfg
|
|
111
|
+
instrument_mcp()
|
|
112
|
+
instrument_ingest(cfg)
|
|
113
|
+
return provider
|
ctxflow_otel/__main__.py
ADDED
ctxflow_otel/check.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""`ctxflow-otel check`: is this process set up to send to ctxflow?
|
|
2
|
+
|
|
3
|
+
One line per check (`ok:`, `warn:` or `FAIL:`), exit code 1 if any check failed:
|
|
4
|
+
|
|
5
|
+
- config: the `CTXFLOW_*` variables parse (`Config.from_env`, the same rules as `init()`).
|
|
6
|
+
- exporter: the OTLP/HTTP traces endpoint the SDK exports to (`OTEL_EXPORTER_OTLP_*`), with its
|
|
7
|
+
headers and TLS files. The ctxflow core is recognized and must accept the API key; another
|
|
8
|
+
endpoint (your collector) must accept an empty OTLP request (2xx); other answers are warnings.
|
|
9
|
+
- core: with `CTXFLOW_CORE_ENDPOINT` and `CTXFLOW_API_KEY` (the collector's settings), the core
|
|
10
|
+
must answer and accept that key. Use it where the collector runs: the collector reports healthy
|
|
11
|
+
while its exporter drops every batch with a 401.
|
|
12
|
+
- identity: where a check above found the core and the key was accepted, `GET /v1/whoami` says
|
|
13
|
+
which project and environment the key targets and when data last arrived there. A core without
|
|
14
|
+
that endpoint (404), or any other answer, is a warning: the key itself was already checked. When
|
|
15
|
+
the environment is Development or Staging (`environment.kind` of the answer; a core that does not
|
|
16
|
+
send it, or a custom environment, gives no warning) it adds a warning that the key is not for
|
|
17
|
+
production data.
|
|
18
|
+
|
|
19
|
+
The probe is the request an OTLP exporter sends, to the same URL with the same headers, but with a
|
|
20
|
+
`text/plain` body. The core checks the key before the content type: a good key gets `415` with the
|
|
21
|
+
core's OTLP error body (nothing is ingested), a bad one `401`. The identity request is a `GET`
|
|
22
|
+
that ingests nothing. A redirect is never followed (the key
|
|
23
|
+
must not reach another host) and fails the check; each probe has a 10 s deadline in total.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import base64
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import socket
|
|
30
|
+
import ssl
|
|
31
|
+
import threading
|
|
32
|
+
import urllib.error
|
|
33
|
+
import urllib.parse
|
|
34
|
+
import urllib.request
|
|
35
|
+
from collections.abc import Callable, Mapping
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from datetime import UTC, datetime
|
|
38
|
+
from enum import StrEnum
|
|
39
|
+
from importlib.metadata import version
|
|
40
|
+
from typing import Final
|
|
41
|
+
from urllib.parse import unquote
|
|
42
|
+
|
|
43
|
+
from ctxflow_otel.config import Config
|
|
44
|
+
|
|
45
|
+
__all__ = ["Level", "Probe", "Result", "Tls", "probe", "redact", "run_check", "traces_target"]
|
|
46
|
+
|
|
47
|
+
_TIMEOUT_S: Final = 5.0 # per socket operation
|
|
48
|
+
_DEADLINE_S: Final = 10.0 # per probe, in total
|
|
49
|
+
_BODY_LIMIT: Final = 4096
|
|
50
|
+
_TRACES_PATH: Final = "v1/traces"
|
|
51
|
+
_WHOAMI_PATH: Final = "v1/whoami"
|
|
52
|
+
_DEFAULT_ENDPOINT: Final = "http://localhost:4318/"
|
|
53
|
+
_RPC_INVALID_ARGUMENT: Final = 3 # google.rpc.Code in the core's OTLP error bodies
|
|
54
|
+
_REJECTED: Final = frozenset({401, 403})
|
|
55
|
+
_REDIRECT: Final = range(300, 400)
|
|
56
|
+
_SUCCESS: Final = range(200, 300)
|
|
57
|
+
_EMPTY_OTLP: Final = b'{"resourceSpans":[]}'
|
|
58
|
+
_HTTP_UNSUPPORTED_MEDIA_TYPE: Final = 415
|
|
59
|
+
_HTTP_NOT_FOUND: Final = 404
|
|
60
|
+
_ENVIRONMENT_KINDS: Final = frozenset({"development", "staging", "production", "other"})
|
|
61
|
+
_NON_PRODUCTION_KINDS: Final = frozenset({"development", "staging"}) # kinds that get a warning
|
|
62
|
+
_BMP_MAX: Final = 0xFFFF # highest code point that `\\uXXXX` can write
|
|
63
|
+
_USER_AGENT: Final = f"ctxflow-otel/{version('ctxflow-otel')}" # not Python-urllib: CDNs block it
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Level(StrEnum):
|
|
67
|
+
"""Outcome of one check."""
|
|
68
|
+
|
|
69
|
+
OK = "ok"
|
|
70
|
+
WARN = "warn"
|
|
71
|
+
FAIL = "FAIL"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class Result:
|
|
76
|
+
"""One check: its level and one line that says what is wrong (or that it is fine)."""
|
|
77
|
+
|
|
78
|
+
level: Level
|
|
79
|
+
message: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True, slots=True)
|
|
83
|
+
class Probe:
|
|
84
|
+
"""What an OTLP/HTTP endpoint answered to the probe: `status` is None if it is unreachable."""
|
|
85
|
+
|
|
86
|
+
url: str
|
|
87
|
+
status: int | None
|
|
88
|
+
is_core: bool
|
|
89
|
+
error: str = ""
|
|
90
|
+
location: str = ""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_headers(raw: str) -> tuple[dict[str, str], list[str]]:
|
|
94
|
+
"""`k=v,k2=v2` (URL-encoded, as `OTEL_EXPORTER_OTLP_HEADERS`) as `(headers, problems)`.
|
|
95
|
+
|
|
96
|
+
Names are lowercased. An entry without a name or `=`, or a value with a control character,
|
|
97
|
+
is left out and reported in `problems` by its position or name only, never by its value.
|
|
98
|
+
"""
|
|
99
|
+
headers: dict[str, str] = {}
|
|
100
|
+
problems: list[str] = []
|
|
101
|
+
for position, entry in enumerate(raw.split(","), 1):
|
|
102
|
+
if not entry.strip():
|
|
103
|
+
continue
|
|
104
|
+
name, sep, value = entry.partition("=")
|
|
105
|
+
name = unquote(name).strip().lower()
|
|
106
|
+
if not sep or not name or not name.isprintable():
|
|
107
|
+
problems.append(f"header entry {position} is not name=value: left out")
|
|
108
|
+
continue
|
|
109
|
+
value = unquote(value).strip()
|
|
110
|
+
if not value.isprintable():
|
|
111
|
+
problems.append(f"header {name!r} has a control character: left out")
|
|
112
|
+
continue
|
|
113
|
+
headers[name] = value
|
|
114
|
+
return headers, problems
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def traces_target(env: Mapping[str, str]) -> tuple[str, dict[str, str], list[str]]:
|
|
118
|
+
"""The traces URL, headers and header problems of the OTLP/HTTP exporter with `env`.
|
|
119
|
+
|
|
120
|
+
`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is used as it is; `OTEL_EXPORTER_OTLP_ENDPOINT` gets
|
|
121
|
+
`/v1/traces` appended; the default is `http://localhost:4318/v1/traces`. Signal headers win over
|
|
122
|
+
the generic ones (see `parse_headers`).
|
|
123
|
+
"""
|
|
124
|
+
url = env.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "").strip()
|
|
125
|
+
if not url:
|
|
126
|
+
base = env.get("OTEL_EXPORTER_OTLP_ENDPOINT", "").strip() or _DEFAULT_ENDPOINT
|
|
127
|
+
url = base if base.endswith("/") else base + "/"
|
|
128
|
+
url += _TRACES_PATH
|
|
129
|
+
raw = env.get("OTEL_EXPORTER_OTLP_TRACES_HEADERS") or env.get("OTEL_EXPORTER_OTLP_HEADERS", "")
|
|
130
|
+
headers, problems = parse_headers(raw)
|
|
131
|
+
return url, headers, problems
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass(frozen=True, slots=True)
|
|
135
|
+
class Tls:
|
|
136
|
+
"""TLS files of the probe, as the OTLP exporter reads them: CA bundle, client cert and key."""
|
|
137
|
+
|
|
138
|
+
ca_file: str | None = None
|
|
139
|
+
client_cert: str | None = None
|
|
140
|
+
client_key: str | None = None
|
|
141
|
+
|
|
142
|
+
@classmethod
|
|
143
|
+
def from_env(cls, env: Mapping[str, str]) -> "Tls":
|
|
144
|
+
"""`OTEL_EXPORTER_OTLP_TRACES_*` wins over `OTEL_EXPORTER_OTLP_*` (CERTIFICATE,
|
|
145
|
+
CLIENT_CERTIFICATE, CLIENT_KEY)."""
|
|
146
|
+
|
|
147
|
+
def get(name: str) -> str | None:
|
|
148
|
+
value = env.get(f"OTEL_EXPORTER_OTLP_TRACES_{name}") or env.get(
|
|
149
|
+
f"OTEL_EXPORTER_OTLP_{name}"
|
|
150
|
+
)
|
|
151
|
+
return value.strip() or None if value else None
|
|
152
|
+
|
|
153
|
+
return cls(get("CERTIFICATE"), get("CLIENT_CERTIFICATE"), get("CLIENT_KEY"))
|
|
154
|
+
|
|
155
|
+
def context(self) -> ssl.SSLContext:
|
|
156
|
+
"""A verifying client context with these files (system CAs without a CA bundle)."""
|
|
157
|
+
context = ssl.create_default_context(cafile=self.ca_file)
|
|
158
|
+
if self.client_cert:
|
|
159
|
+
context.load_cert_chain(self.client_cert, self.client_key)
|
|
160
|
+
return context
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
164
|
+
"""Never follow a redirect: the headers (the API key) must not reach another host."""
|
|
165
|
+
|
|
166
|
+
def redirect_request(self, *args: object, **kwargs: object) -> None:
|
|
167
|
+
"""Refuse every redirect; urllib then raises an `HTTPError` with the 3xx status."""
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _without_userinfo(url: str) -> str:
|
|
172
|
+
"""`url` without `user:password@` (the request URL; credentials go as Basic auth). Only for a
|
|
173
|
+
URL that already parsed."""
|
|
174
|
+
parts = urllib.parse.urlsplit(url)
|
|
175
|
+
return urllib.parse.urlunsplit(parts._replace(netloc=parts.netloc.rpartition("@")[2]))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def redact(url: str) -> str:
|
|
179
|
+
"""`url` for printing: scheme, host, port and path; no `user:password@`, and the query and
|
|
180
|
+
fragment as `?***` / `#***` (they can carry a key)."""
|
|
181
|
+
try:
|
|
182
|
+
parts = urllib.parse.urlsplit(url)
|
|
183
|
+
except ValueError:
|
|
184
|
+
return "<invalid URL>"
|
|
185
|
+
shown = urllib.parse.urlunsplit(
|
|
186
|
+
(parts.scheme, parts.netloc.rpartition("@")[2], parts.path, "", "")
|
|
187
|
+
)
|
|
188
|
+
return shown + ("?***" if parts.query else "") + ("#***" if parts.fragment else "")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _reason(exc: BaseException) -> str:
|
|
192
|
+
"""A fixed description of a probe error: never its message, which can hold a header value."""
|
|
193
|
+
if isinstance(exc, urllib.error.URLError) and isinstance(exc.reason, BaseException):
|
|
194
|
+
return _reason(exc.reason)
|
|
195
|
+
known: tuple[tuple[type[BaseException], str], ...] = (
|
|
196
|
+
(TimeoutError, "timed out"),
|
|
197
|
+
(socket.gaierror, "host not found"),
|
|
198
|
+
(ConnectionRefusedError, "connection refused"),
|
|
199
|
+
(ConnectionResetError, "connection reset"),
|
|
200
|
+
(ssl.SSLCertVerificationError, "TLS certificate not trusted"),
|
|
201
|
+
(ssl.SSLError, "TLS error"),
|
|
202
|
+
(FileNotFoundError, "TLS file not found"),
|
|
203
|
+
(urllib.error.URLError, "invalid URL"),
|
|
204
|
+
(UnicodeError, "invalid URL"),
|
|
205
|
+
(ValueError, "invalid URL or header"),
|
|
206
|
+
)
|
|
207
|
+
for kind, text in known:
|
|
208
|
+
if isinstance(exc, kind):
|
|
209
|
+
return text
|
|
210
|
+
errno = getattr(exc, "errno", None)
|
|
211
|
+
return type(exc).__name__ + (f" (errno {errno})" if isinstance(errno, int) else "")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(frozen=True, slots=True)
|
|
215
|
+
class _Payload:
|
|
216
|
+
"""A request body and its content type."""
|
|
217
|
+
|
|
218
|
+
body: bytes
|
|
219
|
+
content_type: str
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _request(
|
|
223
|
+
url: str, headers: Mapping[str, str], tls: Tls, payload: _Payload | None
|
|
224
|
+
) -> tuple[int, bytes, str]:
|
|
225
|
+
"""One request without redirects: `(status, body, Location)`. Raises on network errors.
|
|
226
|
+
A POST with `payload`, or a GET without.
|
|
227
|
+
|
|
228
|
+
`user:password@` in the URL becomes Basic auth (as the exporter's HTTP client does), unless the
|
|
229
|
+
headers already carry an `Authorization`.
|
|
230
|
+
"""
|
|
231
|
+
try:
|
|
232
|
+
parts = urllib.parse.urlsplit(url)
|
|
233
|
+
user, password = parts.username, parts.password
|
|
234
|
+
except ValueError:
|
|
235
|
+
raise urllib.error.URLError("invalid URL") from None # never the text: it can hold a key
|
|
236
|
+
sent = dict(headers)
|
|
237
|
+
if payload is not None:
|
|
238
|
+
sent["Content-Type"] = payload.content_type
|
|
239
|
+
if not any(k.lower() == "user-agent" for k in headers):
|
|
240
|
+
sent["User-Agent"] = _USER_AGENT
|
|
241
|
+
if user is not None:
|
|
242
|
+
url = _without_userinfo(url)
|
|
243
|
+
if not any(k.lower() == "authorization" for k in headers):
|
|
244
|
+
pair = f"{unquote(user)}:{unquote(password or '')}"
|
|
245
|
+
sent["Authorization"] = "Basic " + base64.b64encode(pair.encode()).decode("ascii")
|
|
246
|
+
request = urllib.request.Request(
|
|
247
|
+
url,
|
|
248
|
+
data=None if payload is None else payload.body,
|
|
249
|
+
method="GET" if payload is None else "POST",
|
|
250
|
+
headers=sent,
|
|
251
|
+
)
|
|
252
|
+
handlers: list[urllib.request.BaseHandler] = [_NoRedirect()]
|
|
253
|
+
if url.lower().startswith("https:"):
|
|
254
|
+
handlers.append(urllib.request.HTTPSHandler(context=tls.context()))
|
|
255
|
+
opener = urllib.request.build_opener(*handlers)
|
|
256
|
+
try:
|
|
257
|
+
with opener.open(request, timeout=_TIMEOUT_S) as response:
|
|
258
|
+
return response.status, response.read(_BODY_LIMIT), ""
|
|
259
|
+
except urllib.error.HTTPError as exc:
|
|
260
|
+
with exc:
|
|
261
|
+
return exc.code, exc.read(_BODY_LIMIT), exc.headers.get("Location", "")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _within_deadline[T](call: Callable[[], T]) -> T | Exception | None:
|
|
265
|
+
"""`call()` in a daemon thread: its result, the exception it raised, or None if it did not
|
|
266
|
+
finish within `_DEADLINE_S` in total (DNS and a slow server included)."""
|
|
267
|
+
outcome: list[T | Exception] = []
|
|
268
|
+
|
|
269
|
+
def run() -> None:
|
|
270
|
+
try:
|
|
271
|
+
outcome.append(call())
|
|
272
|
+
except Exception as exc: # reported as unreachable, never raised
|
|
273
|
+
outcome.append(exc)
|
|
274
|
+
|
|
275
|
+
worker = threading.Thread(target=run, name="ctxflow-check-probe", daemon=True)
|
|
276
|
+
worker.start()
|
|
277
|
+
worker.join(_DEADLINE_S)
|
|
278
|
+
return outcome[0] if outcome else None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def probe(
|
|
282
|
+
url: str,
|
|
283
|
+
headers: Mapping[str, str],
|
|
284
|
+
tls: Tls | None = None,
|
|
285
|
+
body: bytes = b"{}",
|
|
286
|
+
content_type: str = "text/plain",
|
|
287
|
+
) -> Probe:
|
|
288
|
+
"""POST `body` to `url` with `headers`, never following a redirect, within `_DEADLINE_S` in
|
|
289
|
+
total (DNS and a slow server included). The default `text/plain` body is never ingested."""
|
|
290
|
+
result = _within_deadline(
|
|
291
|
+
lambda: _request(url, headers, tls or Tls(), _Payload(body, content_type))
|
|
292
|
+
)
|
|
293
|
+
if result is None:
|
|
294
|
+
return Probe(url, None, False, f"no answer within {_DEADLINE_S:.0f} s")
|
|
295
|
+
if isinstance(result, Exception):
|
|
296
|
+
return Probe(url, None, False, _reason(result))
|
|
297
|
+
status, answer, location = result
|
|
298
|
+
is_core = status == _HTTP_UNSUPPORTED_MEDIA_TYPE and _is_core_body(answer)
|
|
299
|
+
return Probe(url, status, is_core, location=location)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _redirect(found: Probe) -> str:
|
|
303
|
+
"""The redirect, naming only the target host (never the `Location` text)."""
|
|
304
|
+
try:
|
|
305
|
+
host = urllib.parse.urlsplit(urllib.parse.urljoin(found.url, found.location)).hostname
|
|
306
|
+
except ValueError:
|
|
307
|
+
host = None
|
|
308
|
+
return f"redirect ({found.status}) to {host or 'an invalid or unknown host'} not followed"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _is_core_body(body: bytes) -> bool:
|
|
312
|
+
"""True for the core's error body for an unsupported content type: `{"code":3,...}`."""
|
|
313
|
+
try:
|
|
314
|
+
parsed: object = json.loads(body)
|
|
315
|
+
except ValueError:
|
|
316
|
+
return False
|
|
317
|
+
return isinstance(parsed, dict) and parsed.get("code") == _RPC_INVALID_ARGUMENT
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _failure(found: Probe, what: str, shown: str) -> Result | None:
|
|
321
|
+
"""The FAIL of an unreachable endpoint, a rejected key or a redirect; None otherwise."""
|
|
322
|
+
if found.status is None:
|
|
323
|
+
return Result(Level.FAIL, f"{what} unreachable at {shown}: {found.error}")
|
|
324
|
+
if found.status in _REJECTED:
|
|
325
|
+
return Result(Level.FAIL, f"{what} rejected the key ({found.status}) at {shown}")
|
|
326
|
+
if found.status in _REDIRECT:
|
|
327
|
+
return Result(Level.FAIL, f"{what} at {shown}: {_redirect(found)}")
|
|
328
|
+
return None
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _whoami_url(traces_url: str) -> str | None:
|
|
332
|
+
"""The `/v1/whoami` URL next to a `/v1/traces` URL, or None when the URL does not end in it
|
|
333
|
+
(a custom path: the core's layout is not known)."""
|
|
334
|
+
try:
|
|
335
|
+
parts = urllib.parse.urlsplit(traces_url)
|
|
336
|
+
except ValueError:
|
|
337
|
+
return None
|
|
338
|
+
suffix = "/" + _TRACES_PATH
|
|
339
|
+
trimmed = parts.path.rstrip("/")
|
|
340
|
+
if not trimmed.endswith(suffix):
|
|
341
|
+
return None
|
|
342
|
+
path = trimmed.removesuffix(_TRACES_PATH) + _WHOAMI_PATH
|
|
343
|
+
return urllib.parse.urlunsplit(parts._replace(path=path, query="", fragment=""))
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _shown(value: str) -> str:
|
|
347
|
+
"""`value` for the terminal: a character that is not printable (control, zero-width joiner...)
|
|
348
|
+
as `\\uXXXX`, so a name from the core cannot move the cursor or hide text."""
|
|
349
|
+
return "".join(
|
|
350
|
+
c if c.isprintable() else f"\\u{ord(c):04x}" if ord(c) <= _BMP_MAX else f"\\U{ord(c):08x}"
|
|
351
|
+
for c in value
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _ago(moment: str, now: datetime) -> str | None:
|
|
356
|
+
"""`3 min ago` for an ISO 8601 `moment`, or None if it does not parse. Under a minute (or in
|
|
357
|
+
the future, clock skew) is `just now`."""
|
|
358
|
+
try:
|
|
359
|
+
then = datetime.fromisoformat(moment)
|
|
360
|
+
except ValueError:
|
|
361
|
+
return None
|
|
362
|
+
if then.tzinfo is None:
|
|
363
|
+
return None
|
|
364
|
+
seconds = int((now - then).total_seconds())
|
|
365
|
+
for unit, size in (("day", 86400), ("hour", 3600), ("min", 60)):
|
|
366
|
+
if seconds >= size:
|
|
367
|
+
count = seconds // size
|
|
368
|
+
plural = "s" if unit != "min" and count != 1 else ""
|
|
369
|
+
return f"{count} {unit}{plural} ago"
|
|
370
|
+
return "just now"
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _whoami_body(url: str, headers: Mapping[str, str], tls: Tls | None) -> bytes | Result:
|
|
374
|
+
"""The body of a successful `GET` of `url`, or the warning that says why there is none."""
|
|
375
|
+
shown = redact(url)
|
|
376
|
+
got = _within_deadline(lambda: _request(url, headers, tls or Tls(), None))
|
|
377
|
+
if got is None:
|
|
378
|
+
return Result(Level.WARN, f"identity: no answer within {_DEADLINE_S:.0f} s at {shown}")
|
|
379
|
+
if isinstance(got, Exception):
|
|
380
|
+
return Result(Level.WARN, f"identity: unreachable at {shown}: {_reason(got)}")
|
|
381
|
+
status, body, location = got
|
|
382
|
+
if status == _HTTP_NOT_FOUND:
|
|
383
|
+
return Result(
|
|
384
|
+
Level.WARN,
|
|
385
|
+
f"identity: {shown} not found: this core is older, project and environment not shown",
|
|
386
|
+
)
|
|
387
|
+
if status in _REDIRECT:
|
|
388
|
+
redirect = _redirect(Probe(url, status, False, location=location))
|
|
389
|
+
return Result(Level.WARN, f"identity: {redirect}")
|
|
390
|
+
if status not in _SUCCESS:
|
|
391
|
+
return Result(Level.WARN, f"identity: {shown} answered HTTP {status}")
|
|
392
|
+
return body
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _identity(url: str | None, headers: Mapping[str, str], tls: Tls | None = None) -> list[Result]:
|
|
396
|
+
"""Ask the core which project and environment the key targets (`GET /v1/whoami`).
|
|
397
|
+
|
|
398
|
+
Never a FAIL: the key was already accepted by the probe before, so an older core (404) or any
|
|
399
|
+
other answer only means the line cannot be shown. A key of a Development or Staging
|
|
400
|
+
environment adds a second line (a warning).
|
|
401
|
+
"""
|
|
402
|
+
if url is None:
|
|
403
|
+
return [Result(Level.WARN, "identity: the endpoint is not .../v1/traces, not asked")]
|
|
404
|
+
body = _whoami_body(url, headers, tls)
|
|
405
|
+
if isinstance(body, Result):
|
|
406
|
+
return [body]
|
|
407
|
+
try:
|
|
408
|
+
parsed: object = json.loads(body)
|
|
409
|
+
except ValueError:
|
|
410
|
+
parsed = None
|
|
411
|
+
shape = _whoami_fields(parsed)
|
|
412
|
+
if shape is None:
|
|
413
|
+
return [
|
|
414
|
+
Result(Level.WARN, f"identity: {redact(url)} sent an answer that is not the core's")
|
|
415
|
+
]
|
|
416
|
+
project, environment, last, kind = shape
|
|
417
|
+
project, environment = _shown(project), _shown(environment)
|
|
418
|
+
when = "no events yet"
|
|
419
|
+
if last is not None:
|
|
420
|
+
ago = _ago(last, datetime.now(UTC))
|
|
421
|
+
when = f"last event {ago}" if ago else f"last event at {_shown(last)}"
|
|
422
|
+
results = [
|
|
423
|
+
Result(
|
|
424
|
+
Level.OK,
|
|
425
|
+
f'identity: key targets project "{project}", environment "{environment}", {when}',
|
|
426
|
+
)
|
|
427
|
+
]
|
|
428
|
+
if kind in _NON_PRODUCTION_KINDS:
|
|
429
|
+
results.append(
|
|
430
|
+
Result(
|
|
431
|
+
Level.WARN,
|
|
432
|
+
f'identity: key targets environment "{environment}" ({kind}), not production: '
|
|
433
|
+
"data sent with this key shows only there. For production data, create a key in "
|
|
434
|
+
"the project's Production environment.",
|
|
435
|
+
)
|
|
436
|
+
)
|
|
437
|
+
return results
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _whoami_fields(parsed: object) -> tuple[str, str, str | None, str | None] | None:
|
|
441
|
+
"""`(project, environment, lastEventAt, kind)` of a `/v1/whoami` body (`shared/whoami.ts` of
|
|
442
|
+
the core), or None if it does not have that shape. `kind` is None when the core does not send
|
|
443
|
+
`environment.kind` (older core), or sends something that is not one of its four values."""
|
|
444
|
+
if not isinstance(parsed, dict):
|
|
445
|
+
return None
|
|
446
|
+
project, environment = parsed.get("project"), parsed.get("environment")
|
|
447
|
+
if not isinstance(project, dict) or not isinstance(environment, dict):
|
|
448
|
+
return None
|
|
449
|
+
project_name, environment_name = project.get("name"), environment.get("name")
|
|
450
|
+
last = parsed.get("lastEventAt")
|
|
451
|
+
if not isinstance(project_name, str) or not isinstance(environment_name, str):
|
|
452
|
+
return None
|
|
453
|
+
if not (last is None or isinstance(last, str)):
|
|
454
|
+
return None
|
|
455
|
+
kind = environment.get("kind")
|
|
456
|
+
known = kind if isinstance(kind, str) and kind in _ENVIRONMENT_KINDS else None
|
|
457
|
+
return project_name, environment_name, last, known
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _exporter(env: Mapping[str, str], url: str, headers: Mapping[str, str]) -> list[Result]:
|
|
461
|
+
exporter = env.get("OTEL_TRACES_EXPORTER", "").strip().lower() or "otlp_proto_http"
|
|
462
|
+
if exporter != "otlp_proto_http":
|
|
463
|
+
return [Result(Level.WARN, f"OTEL_TRACES_EXPORTER={exporter}: the endpoint is not probed")]
|
|
464
|
+
shown, tls = redact(url), Tls.from_env(env)
|
|
465
|
+
found = probe(url, headers, tls)
|
|
466
|
+
if found.is_core:
|
|
467
|
+
accepted = Result(Level.OK, f"exporter sends to the ctxflow core at {shown}, key accepted")
|
|
468
|
+
return [accepted, *_identity(_whoami_url(url), headers, tls)]
|
|
469
|
+
if found.status == _HTTP_UNSUPPORTED_MEDIA_TYPE:
|
|
470
|
+
# Not the core: an OTLP receiver (your collector) accepts an empty request, which
|
|
471
|
+
# forwards nothing.
|
|
472
|
+
found = probe(url, headers, tls, _EMPTY_OTLP, "application/json")
|
|
473
|
+
failed = _failure(found, "exporter endpoint", shown)
|
|
474
|
+
if failed is not None:
|
|
475
|
+
return [failed]
|
|
476
|
+
if found.status in _SUCCESS:
|
|
477
|
+
return [
|
|
478
|
+
Result(
|
|
479
|
+
Level.OK,
|
|
480
|
+
f"exporter endpoint at {shown} accepts OTLP (HTTP {found.status}, not the "
|
|
481
|
+
"ctxflow core: your collector, which holds the API key)",
|
|
482
|
+
)
|
|
483
|
+
]
|
|
484
|
+
return [Result(Level.WARN, f"exporter endpoint at {shown} answered HTTP {found.status}")]
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _core(endpoint: str, api_key: str) -> list[Result]:
|
|
488
|
+
try:
|
|
489
|
+
parts = urllib.parse.urlsplit(endpoint)
|
|
490
|
+
url = urllib.parse.urlunsplit(
|
|
491
|
+
parts._replace(path=parts.path.rstrip("/") + "/" + _TRACES_PATH)
|
|
492
|
+
)
|
|
493
|
+
except ValueError:
|
|
494
|
+
return [Result(Level.FAIL, "CTXFLOW_CORE_ENDPOINT: invalid URL")]
|
|
495
|
+
shown = redact(url)
|
|
496
|
+
found = probe(url, {"Authorization": f"Bearer {api_key}"})
|
|
497
|
+
failed = _failure(found, "CTXFLOW_CORE_ENDPOINT", shown)
|
|
498
|
+
if failed is not None:
|
|
499
|
+
return [failed]
|
|
500
|
+
if found.is_core:
|
|
501
|
+
accepted = Result(Level.OK, f"core accepts CTXFLOW_API_KEY at {shown}")
|
|
502
|
+
return [accepted, *_identity(_whoami_url(url), {"Authorization": f"Bearer {api_key}"})]
|
|
503
|
+
# 200 is no proof either: the core never answers 200 to this probe, so something else does.
|
|
504
|
+
return [
|
|
505
|
+
Result(
|
|
506
|
+
Level.FAIL,
|
|
507
|
+
f"unexpected answer {found.status} at {shown}: CTXFLOW_CORE_ENDPOINT may not be the "
|
|
508
|
+
"ctxflow core (a proxy or another service)",
|
|
509
|
+
)
|
|
510
|
+
]
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def run_check(env: Mapping[str, str] | None = None) -> int:
|
|
514
|
+
"""Run every check, print one line each, return 0 if none failed, else 1."""
|
|
515
|
+
source = os.environ if env is None else env
|
|
516
|
+
results: list[Result] = []
|
|
517
|
+
url, headers, problems = traces_target(source)
|
|
518
|
+
results.extend(Result(Level.FAIL, f"exporter headers: {p}") for p in problems)
|
|
519
|
+
try:
|
|
520
|
+
Config.from_env(source)
|
|
521
|
+
except ValueError as exc:
|
|
522
|
+
results.append(Result(Level.FAIL, f"config: {exc}"))
|
|
523
|
+
else:
|
|
524
|
+
results.append(Result(Level.OK, "config: ok"))
|
|
525
|
+
results.extend(_exporter(source, url, headers))
|
|
526
|
+
endpoint = source.get("CTXFLOW_CORE_ENDPOINT", "").strip()
|
|
527
|
+
api_key = source.get("CTXFLOW_API_KEY", "").strip()
|
|
528
|
+
if endpoint and api_key and not api_key.isprintable():
|
|
529
|
+
results.append(Result(Level.FAIL, "CTXFLOW_API_KEY has a control character"))
|
|
530
|
+
elif endpoint and api_key:
|
|
531
|
+
results.extend(_core(endpoint, api_key))
|
|
532
|
+
elif endpoint or api_key:
|
|
533
|
+
results.append(
|
|
534
|
+
Result(Level.FAIL, "set both CTXFLOW_CORE_ENDPOINT and CTXFLOW_API_KEY, or neither")
|
|
535
|
+
)
|
|
536
|
+
for result in results:
|
|
537
|
+
print(f"{result.level.value}: {result.message}")
|
|
538
|
+
return 1 if any(r.level is Level.FAIL for r in results) else 0
|