Skip to content

eBPF-based security platform

testing: cover timer serialization across map exports

John Fastabend52e29d679f4d
diff --git a/builtin-status.c b/builtin-status.c
index ccce56a0..7cfefbc6 100644
--- a/builtin-status.c
+++ b/builtin-status.c
@@ -472,21 +472,6 @@ static const char *roles_str(int is_target, int is_operator)
return "none";
}
-static int status_otel_severity(const char *status, const char **text)
-{
- if (strcmp(status, "ok") == 0) {
- *text = "INFO";
- return 9;
- }
- if (strcmp(status, "degraded") == 0 ||
- strcmp(status, "init-pending") == 0) {
- *text = "WARN";
- return 13;
- }
- *text = "ERROR";
- return 17;
-}
-
/*
* Unlike the general OTLP exporter, the periodic status keepalive must not
* silently turn an absent configuration into a request to localhost. Keep
@@ -1021,15 +1006,16 @@ int cmd_status(int argc, const char **argv)
int severity_number;
int rc;
- severity_number = status_otel_severity(otel_status,
- &severity_text);
- rc = otel_send_log_json(&otel_opts,
- "shirudo.keepalive",
- "shirudo.keepalive",
- severity_number,
- severity_text,
- otel_status,
- shirudo_version_id,
+ severity_number =
+ shirudo_status_otel_severity(otel_status,
+ &severity_text);
+ rc = shirudo_otel_send_log_json(&otel_opts,
+ "shirudo.keepalive",
+ "shirudo.keepalive",
+ severity_number,
+ severity_text,
+ otel_status,
+ shirudo_version_id,
refused, json_buf,
strlen(json_buf));
if (rc) {
diff --git a/builtin-upatch.c b/builtin-upatch.c
index 3acea912..5e03965c 100644
--- a/builtin-upatch.c
+++ b/builtin-upatch.c
@@ -2879,8 +2879,8 @@ static int export_one_map(const char *upatch, const char *map,
rc = upatch_decode_map_signal(&v, &decoder_signal);
if (!rc)
- rc = upatch_maps_otel_send_decoded(&v, decoder_signal,
- otel_opts);
+ rc = shirudo_upatch_maps_otel_send_decoded(&v, decoder_signal,
+ otel_opts);
if (rc) {
pr_err("upatch map: OTLP export %s/%s: %s", upatch, map,
strerror(-rc));
diff --git a/testing/fixtures/decoders/counters.lua b/testing/fixtures/decoders/counters.lua
index 70668925..4dc55e94 100644
--- a/testing/fixtures/decoders/counters.lua
+++ b/testing/fixtures/decoders/counters.lua
@@ -2,7 +2,8 @@
-- Copyright (c) 2026 Authors of shirudo
function decode(input)
- if not input.data.serialized or input.data.serialized_bytes ~= 48 then
+ if not input.data.serialized or input.data.serialized_pages ~= 2 or
+ input.data.serialized_bytes ~= 48 then
error("unexpected serialized counter payload")
end
local records = shirudo.fixed_records(input.data.pages, 24)
diff --git a/testing/fixtures/serialized-metric.bpf.c b/testing/fixtures/serialized-metric.bpf.c
index e35c8cb8..60eae0b6 100644
--- a/testing/fixtures/serialized-metric.bpf.c
+++ b/testing/fixtures/serialized-metric.bpf.c
@@ -30,6 +30,13 @@ struct {
__type(value, struct shirudo_serial_chunk);
} shirudo_ser SEC(".maps");
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, __u32);
+} counter_state SEC(".maps");
+
const struct shirudo_decoder_manifest counters_decoder SEC(".rodata") = {
.magic = SHIRUDO_DECODER_MANIFEST_MAGIC,
.version = SHIRUDO_UPATCH_DECODER_VERSION,
@@ -47,50 +54,61 @@ SEC("syscall")
int shirudo_serialize__counters(struct shirudo_serialize_ctx *ctx)
{
struct shirudo_serial_chunk *chunk;
- struct counter_value *value;
struct counter_record record = {};
- __u32 key, output_key = 0;
+ struct counter_value *value;
+ __u32 *initialized;
+ __u32 state_key = 0;
+ __u32 key;
if (!ctx || ctx->magic != SHIRUDO_SERIAL_MAGIC ||
ctx->version != SHIRUDO_SERIAL_VERSION || ctx->max_chunks < 1 ||
ctx->chunk_payload_size != SHIRUDO_SERIAL_CHUNK_PAYLOAD ||
- ctx->page_index != 0 || ctx->cursor != 0 || ctx->invocation_id == 0)
+ ctx->page_index > 1 || ctx->cursor != ctx->page_index ||
+ ctx->invocation_id == 0)
return -EINVAL;
- chunk = bpf_map_lookup_elem(&shirudo_ser, &output_key);
- if (!chunk)
+ chunk = bpf_map_lookup_elem(&shirudo_ser, &state_key);
+ initialized = bpf_map_lookup_elem(&counter_state, &state_key);
+ if (!chunk || !initialized)
return -EINVAL;
- key = 0;
+ if (!*initialized) {
+ key = 0;
+ value = bpf_map_lookup_elem(&counters, &key);
+ if (!value)
+ return -EINVAL;
+ value->packets = 7;
+ value->bytes = 100;
+ key = 1;
+ value = bpf_map_lookup_elem(&counters, &key);
+ if (!value)
+ return -EINVAL;
+ value->packets = 3;
+ value->bytes = 50;
+ *initialized = 1;
+ }
+ key = ctx->page_index;
value = bpf_map_lookup_elem(&counters, &key);
if (!value)
return -EINVAL;
- value->packets = 7;
- value->bytes = 100;
record.key = key;
record.packets = value->packets;
record.bytes = value->bytes;
__builtin_memcpy(&chunk->data[0], &record, sizeof(record));
- key = 1;
- value = bpf_map_lookup_elem(&counters, &key);
- if (!value)
- return -EINVAL;
- value->packets = 3;
- value->bytes = 50;
- record.key = key;
- record.packets = value->packets;
- record.bytes = value->bytes;
- __builtin_memcpy(&chunk->data[sizeof(record)], &record, sizeof(record));
+ if (!(ctx->flags & SHIRUDO_SERIAL_CTX_F_PEEK)) {
+ value->packets = 0;
+ value->bytes = 0;
+ }
chunk->magic = SHIRUDO_SERIAL_MAGIC;
chunk->version = SHIRUDO_SERIAL_VERSION;
- chunk->flags = SHIRUDO_SERIAL_F_DONE;
+ chunk->flags = ctx->page_index == 1 ? SHIRUDO_SERIAL_F_DONE : 0;
chunk->status = 0;
chunk->chunk_index = 0;
chunk->total_chunks = 1;
- chunk->bytes_total = 2 * sizeof(record);
- chunk->bytes_in_chunk = 2 * sizeof(record);
+ chunk->bytes_total = sizeof(record);
+ chunk->bytes_in_chunk = sizeof(record);
chunk->page_index = ctx->page_index;
chunk->reserved = 0;
chunk->cursor = ctx->cursor;
- chunk->next_cursor = 2;
+ chunk->next_cursor = ctx->cursor + 1;
chunk->invocation_id = ctx->invocation_id;
return 0;
}
diff --git a/testing/helper/otel-mock.py b/testing/helper/otel-mock.py
index df54ebe1..bd355962 100644
--- a/testing/helper/otel-mock.py
+++ b/testing/helper/otel-mock.py
@@ -27,12 +27,14 @@ import json
import pathlib
import ssl
import sys
+import time
mode, port_file, body_file, meta_file = sys.argv[1:5]
tls = sys.argv[5:7]
attempts = 0
meta = {}
+request_times = []
class Handler(http.server.BaseHTTPRequestHandler):
@@ -41,23 +43,35 @@ class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
- def reply(self, status, body):
- payload = json.dumps(body).encode()
+ def reply(self, status, body, headers=None):
+ payload = body if isinstance(body, bytes) else json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
+ for name, value in (headers or {}).items():
+ self.send_header(name, value)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
- self.wfile.write(payload)
+ try:
+ self.wfile.write(payload)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
def do_POST(self):
global attempts, meta
attempts += 1
+ request_times.append(time.monotonic())
raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
if self.headers.get("Content-Encoding", "").lower() == "gzip":
raw = gzip.decompress(raw)
- meta = {"attempts": attempts, "path": self.path}
+ meta = {"attempts": attempts, "path": self.path,
+ "raw_bytes": len(raw)}
+ if len(request_times) > 1:
+ meta["interval_ms"] = round(
+ (request_times[-1] - request_times[-2]) * 1000)
if self.headers.get("Authorization"):
meta["authorization"] = self.headers["Authorization"]
+ if self.headers.get("Content-Type"):
+ meta["content_type"] = self.headers["Content-Type"]
if self.headers.get("Content-Encoding"):
meta["content_encoding"] = self.headers["Content-Encoding"]
try:
@@ -70,7 +84,37 @@ class Handler(http.server.BaseHTTPRequestHandler):
if mode == "retry" and attempts < 3:
self.reply(503, {"message": "try again"})
return
- if mode == "partial":
+ if mode.startswith("retry-") and mode not in {
+ "retry-after", "retry-exhaust-503"}:
+ status = int(mode.split("-")[1])
+ if attempts == 1:
+ self.reply(status, {"message": "try again"})
+ return
+ if mode == "retry-after" and attempts == 1:
+ self.reply(503, {"message": "try again"}, {"Retry-After": "1"})
+ return
+ if mode == "retry-exhaust-503":
+ self.reply(503, {"message": "try again"})
+ self.server.done = attempts >= 3
+ return
+ if mode.startswith("fatal-"):
+ self.reply(int(mode.split("-")[1]), {"message": "not retryable"})
+ self.server.done = True
+ return
+ if mode == "disconnect":
+ self.close_connection = True
+ self.server.done = True
+ return
+ if mode == "timeout":
+ time.sleep(0.3)
+ self.reply(200, {})
+ self.server.done = True
+ return
+ if mode == "partial-zero":
+ self.reply(200, {"partialSuccess": {"rejectedLogRecords": "0"}})
+ elif mode == "malformed":
+ self.reply(200, b"not-json")
+ elif mode == "partial":
self.reply(200, {"partialSuccess": {"rejectedLogRecords": 1,
"errorMessage": "rejected by mock"}})
else:
@@ -85,6 +129,11 @@ if tls:
context.load_cert_chain(tls[0], tls[1])
server.socket = context.wrap_socket(server.socket, server_side=True)
pathlib.Path(port_file).write_text(f"{server.server_address[1]}\n")
+server.timeout = 0.25
while not server.done:
server.handle_request()
+ if mode == "no-request" and attempts == 0:
+ server.done = True
+if mode == "no-request":
+ pathlib.Path(meta_file).write_text(json.dumps({"attempts": attempts}))
server.server_close()
diff --git a/testing/helper/otel-s3-mock.py b/testing/helper/otel-s3-mock.py
index 1b1afef8..59e5321f 100644
--- a/testing/helper/otel-s3-mock.py
+++ b/testing/helper/otel-s3-mock.py
@@ -55,7 +55,7 @@ def sigv4_valid(handler):
signature = hmac.new(key, string_to_sign.encode(),
hashlib.sha256).hexdigest()
return (algorithm == "AWS4-HMAC-SHA256" and access == "test" and
- region == "us-east-1" and service == "s3" and
+ bool(region) and service == "s3" and
terminal == "aws4_request" and
hmac.compare_digest(signature, fields["Signature"]))
except (KeyError, ValueError):
@@ -100,6 +100,9 @@ class Handler(http.server.BaseHTTPRequestHandler):
"security_token": self.headers.get("x-amz-security-token", ""),
"tenant_id": self.headers.get("X-Tenant-ID", ""),
"sigv4_valid": sigv4_valid(self),
+ "region": self.headers["Authorization"].split(
+ "Credential=", 1)[1].split("/", 3)[2]
+ if "Credential=" in self.headers.get("Authorization", "") else "",
})
save_meta()
if mode == "s3-fail":
@@ -107,6 +110,11 @@ class Handler(http.server.BaseHTTPRequestHandler):
self.server.done = True
elif mode == "s3-retry" and put_attempts == 1:
self.reply(503)
+ elif mode.startswith("s3-retry-") and put_attempts == 1:
+ self.reply(int(mode.rsplit("-", 1)[1]))
+ elif mode == "s3-exhaust":
+ self.reply(503)
+ self.server.done = put_attempts >= 2
elif mode == "exists":
self.reply(412)
else:
@@ -124,11 +132,14 @@ class Handler(http.server.BaseHTTPRequestHandler):
"tenant_id": self.headers.get("X-Tenant-ID", ""),
})
save_meta()
- if mode == "otel-fail":
+ if mode in {"otel-fail", "otel-retry"} and len(
+ [request for request in requests if request["method"] == "POST"]
+ ) == 1:
self.reply(503)
+ self.server.done = mode == "otel-fail"
else:
self.reply(200)
- self.server.done = True
+ self.server.done = True
def log_message(self, *args):
pass
diff --git a/testing/helper/test-otel-map.c b/testing/helper/test-otel-map.c
index 17585cd8..298902e1 100644
--- a/testing/helper/test-otel-map.c
+++ b/testing/helper/test-otel-map.c
@@ -22,6 +22,7 @@
#include "json.h"
#include "io.h"
#include "malloc.h"
+#include "upatch_decode.h"
#include "upatch_maps.h"
#include "upatch_maps_otel.h"
#include "version.h"
@@ -214,8 +215,8 @@ static int print_classification(__u32 type, bool is_signed, bool with_btf,
if (rc)
return 1;
f.view.serialized = serialized;
- rc = upatch_maps_otel_classify(&f.view, &signal, reason,
- sizeof(reason));
+ rc = shirudo_upatch_maps_otel_classify(&f.view, &signal, reason,
+ sizeof(reason));
if (!rc)
printf("%s:%s\n", signal == SHIRUDO_OTEL_METRIC ?
"metric" : "log", reason);
@@ -245,13 +246,13 @@ static int print_payload(bool metric, bool counter, bool with_location)
rc = make_decoder(metric, counter, false, decoder_path,
sizeof(decoder_path));
if (!rc && metric)
- rc = upatch_maps_otel_build_metric_file(decoder_path,
- &f.view, &opts,
- &buf, &len);
+ rc = shirudo_upatch_maps_otel_build_metric_file(decoder_path,
+ &f.view, &opts,
+ &buf, &len);
else if (!rc)
- rc = upatch_maps_otel_build_log_file(decoder_path,
- &f.view, &buf,
- &len);
+ rc = shirudo_upatch_maps_otel_build_log_file(decoder_path,
+ &f.view, &buf,
+ &len);
if (!rc && buf)
fwrite(buf, 1, len, stdout);
if (buf)
@@ -281,6 +282,33 @@ static int print_local_json(void)
return e.err != 0;
}
+static int send_log_limits(const char *url, __u32 retries, __u32 record_max,
+ __u32 request_max, bool use_environment)
+{
+ struct shirudo_otel_opts opts = {
+ .endpoint = use_environment ? NULL : url,
+ .retries = retries,
+ .log_record_max_bytes = record_max,
+ .otlp_max_bytes = request_max,
+ };
+ struct fixture f;
+ char decoder_path[128] = {};
+ int rc;
+
+ rc = fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true);
+ if (rc)
+ return 1;
+ rc = make_decoder(false, false, false, decoder_path,
+ sizeof(decoder_path));
+ if (!rc)
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_FORCE_LOG, &opts);
+ if (decoder_path[0])
+ unlink(decoder_path);
+ fixture_destroy(&f);
+ return rc ? 1 : 0;
+}
+
static int send_log(const char *url, __u32 retries, bool insecure)
{
struct shirudo_otel_opts opts = {
@@ -298,14 +326,40 @@ static int send_log(const char *url, __u32 retries, bool insecure)
rc = make_decoder(false, false, false, decoder_path,
sizeof(decoder_path));
if (!rc)
- rc = upatch_maps_otel_send_file(decoder_path, &f.view,
- SHIRUDO_OTEL_FORCE_LOG, &opts);
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_FORCE_LOG, &opts);
if (decoder_path[0])
unlink(decoder_path);
fixture_destroy(&f);
return rc ? 1 : 0;
}
+static int print_record_size(void)
+{
+ struct fixture f;
+ char decoder_path[128] = {};
+ char *decoded = NULL;
+ size_t decoded_len = 0;
+ int rc;
+
+ rc = fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true);
+ if (rc)
+ return 1;
+ rc = make_decoder(false, false, false, decoder_path,
+ sizeof(decoder_path));
+ if (!rc)
+ rc = upatch_decode_map_file_otel(decoder_path, &f.view,
+ &decoded, &decoded_len);
+ if (!rc)
+ printf("%zu\n", decoded_len);
+ if (decoded)
+ xfree(decoded, decoded_len + 1);
+ if (decoder_path[0])
+ unlink(decoder_path);
+ fixture_destroy(&f);
+ return rc != 0;
+}
+
static int send_auto(const char *base, bool is_signed)
{
struct shirudo_otel_opts opts = { .endpoint = base, .retries = 0 };
@@ -318,8 +372,8 @@ static int send_auto(const char *base, bool is_signed)
rc = make_decoder(!is_signed, !is_signed, false, decoder_path,
sizeof(decoder_path));
if (!rc)
- rc = upatch_maps_otel_send_file(decoder_path, &f.view,
- SHIRUDO_OTEL_AUTO, &opts);
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_AUTO, &opts);
if (decoder_path[0])
unlink(decoder_path);
fixture_destroy(&f);
@@ -343,14 +397,61 @@ static int send_metric(const char *url)
rc = make_decoder(true, false, false, decoder_path,
sizeof(decoder_path));
if (!rc)
- rc = upatch_maps_otel_send_file(decoder_path, &f.view,
- SHIRUDO_OTEL_FORCE_METRIC, &opts);
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_FORCE_METRIC, &opts);
if (decoder_path[0])
unlink(decoder_path);
fixture_destroy(&f);
return rc ? 1 : 0;
}
+static int send_status(const char *url, const char *status)
+{
+ struct shirudo_otel_opts opts = {
+ .endpoint = url,
+ .retries = 0,
+ };
+ const char *severity_text;
+ char body[256];
+ int severity, n;
+
+ severity = shirudo_status_otel_severity(status, &severity_text);
+ n = snprintf(body, sizeof(body),
+ "{\"schema\":1,\"status\":\"%s\",\"conditions\":[],\"tpm\":{}}",
+ status);
+ if (n < 0 || (size_t)n >= sizeof(body))
+ return 1;
+ return shirudo_otel_send_log_json(&opts, "shirudo.keepalive",
+ "shirudo.keepalive", severity,
+ severity_text, status, "test-version", 2,
+ body, (size_t)n) != 0;
+}
+
+static int send_metric_env(void)
+{
+ struct shirudo_otel_opts opts = {
+ .retries = 0,
+ .metric_kind = SHIRUDO_OTEL_METRIC_GAUGE,
+ .metric_kind_set = true,
+ };
+ struct fixture f;
+ char decoder_path[128] = {};
+ int rc;
+
+ rc = fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true);
+ if (rc)
+ return 1;
+ rc = make_decoder(true, false, false, decoder_path,
+ sizeof(decoder_path));
+ if (!rc)
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_FORCE_METRIC, &opts);
+ if (decoder_path[0])
+ unlink(decoder_path);
+ fixture_destroy(&f);
+ return rc != 0;
+}
+
static bool large_serialized_fixture(struct fixture *f)
{
const __u32 pages = 1;
@@ -396,7 +497,8 @@ static void large_serialized_destroy(struct fixture *f)
static int send_s3(const char *endpoint, __u32 retries, bool large)
{
struct shirudo_otel_opts opts = {
- .s3_uri = "s3://test-bucket/prefix",
+ .s3_uri = getenv("SHIRUDO_TEST_S3_URI") ?
+ getenv("SHIRUDO_TEST_S3_URI") : "s3://test-bucket/prefix",
.tenant_id = large ? NULL : "tenant-uuid-1234",
.otlp_max_bytes = large ? 1024 : 0,
.retries = retries,
@@ -420,8 +522,8 @@ static int send_s3(const char *endpoint, __u32 retries, bool large)
rc = make_decoder(false, false, true, decoder_path,
sizeof(decoder_path));
if (!rc)
- rc = upatch_maps_otel_send_file(decoder_path, &f.view,
- SHIRUDO_OTEL_S3, &opts);
+ rc = shirudo_upatch_maps_otel_send_file(decoder_path, &f.view,
+ SHIRUDO_OTEL_S3, &opts);
if (decoder_path[0])
unlink(decoder_path);
large_serialized_destroy(&f);
@@ -441,25 +543,25 @@ static int tenant_validation(void)
if (fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true))
return 1;
opts.tenant_id = "bad tenant";
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
- &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
+ &opts);
failed += rc != -EINVAL;
opts.tenant_id = NULL;
setenv("OTEL_EXPORTER_OTLP_LOGS_HEADERS",
"X-Tenant-ID=bad%20tenant", 1);
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
- &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
+ &opts);
failed += rc != -EINVAL;
setenv("OTEL_EXPORTER_OTLP_LOGS_HEADERS",
"X-Tenant-ID=one,x-tenant-id=two", 1);
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
- &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
+ &opts);
failed += rc != -EINVAL;
opts.tenant_id = "tenant-cli-1234";
setenv("OTEL_EXPORTER_OTLP_LOGS_HEADERS",
"X-Tenant-ID=ignored%20invalid", 1);
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
- &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
+ &opts);
failed += rc == -EINVAL;
unsetenv("OTEL_EXPORTER_OTLP_LOGS_HEADERS");
fixture_destroy(&f);
@@ -478,30 +580,56 @@ static int s3_validation(void)
if (fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true))
return 1;
setenv("AWS_ENDPOINT_URL_S3", "http://127.0.0.1:1", 1);
+ unsetenv("AWS_REGION");
+ unsetenv("AWS_DEFAULT_REGION");
unsetenv("AWS_ACCESS_KEY_ID");
unsetenv("AWS_SECRET_ACCESS_KEY");
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ unsetenv("AWS_SESSION_TOKEN");
+ unsetenv("AWS_CA_BUNDLE");
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
if (rc != -EACCES)
goto fail;
setenv("AWS_ACCESS_KEY_ID", "test", 1);
+ setenv("AWS_SECRET_ACCESS_KEY", "bad\nsecret", 1);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ if (rc != -EACCES)
+ goto fail;
setenv("AWS_SECRET_ACCESS_KEY", "secret", 1);
+ setenv("AWS_ACCESS_KEY_ID", "bad:key", 1);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ if (rc != -EACCES)
+ goto fail;
+ setenv("AWS_ACCESS_KEY_ID", "test", 1);
+ setenv("AWS_REGION", "not_a_region", 1);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ if (rc != -EINVAL)
+ goto fail;
+ unsetenv("AWS_REGION");
+ opts.s3_uri = "s3://test-bucket/../escape";
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ if (rc != -EINVAL)
+ goto fail;
+ opts.s3_uri = "s3://test-bucket/prefix?query";
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ if (rc != -EINVAL)
+ goto fail;
opts.s3_uri = "s3://BAD_BUCKET/prefix";
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
if (rc != -EINVAL)
goto fail;
opts.s3_uri = "s3://test-bucket/prefix";
f.view.truncated = true;
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
f.view.truncated = false;
if (rc != -E2BIG)
goto fail;
f.view.skipped = true;
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
f.view.skipped = false;
if (rc != -EOPNOTSUPP)
goto fail;
setenv("AWS_ENDPOINT_URL_S3", "http://storage.example", 1);
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_S3, &opts);
if (rc != -EPERM)
goto fail;
fixture_destroy(&f);
@@ -522,14 +650,36 @@ static int security_check(void)
if (fixture_init(&f, BPF_MAP_TYPE_PERCPU_ARRAY, false, true))
return 1;
- rc = upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
- &opts);
+ rc = shirudo_upatch_maps_otel_send(&f.view, SHIRUDO_OTEL_FORCE_LOG,
+ &opts);
fixture_destroy(&f);
return rc != -EPERM;
}
int main(int argc, char **argv)
{
+ if (argc == 2 && strcmp(argv[1], "record-size") == 0)
+ return print_record_size();
+ if (argc == 6 && strcmp(argv[1], "send-log-limits") == 0)
+ return send_log_limits(argv[2], (__u32)strtoul(argv[3], NULL, 10),
+ (__u32)strtoul(argv[4], NULL, 10),
+ (__u32)strtoul(argv[5], NULL, 10), false);
+ if (argc == 3 && strcmp(argv[1], "send-log-env") == 0)
+ return send_log_limits(NULL, (__u32)strtoul(argv[2], NULL, 10),
+ 0, 0, true);
+ if (argc == 2 && strcmp(argv[1], "send-metric-env") == 0)
+ return send_metric_env();
+ if (argc == 4 && strcmp(argv[1], "send-status") == 0)
+ return send_status(argv[2], argv[3]);
+ if (argc == 4 && strcmp(argv[1], "retry-after") == 0) {
+ __u64 seconds;
+ time_t now = (time_t)strtoll(argv[3], NULL, 10);
+ int rc = shirudo_otel_retry_after(argv[2], now, &seconds);
+
+ if (!rc)
+ printf("%llu\n", seconds);
+ return rc != 0;
+ }
if (argc < 2)
return 2;
if (strcmp(argv[1], "classify-unsigned") == 0)
diff --git a/testing/otel/t1116-otel-backend.sh b/testing/otel/t1116-otel-backend.sh
index a4dec736..c15e9f0a 100644
--- a/testing/otel/t1116-otel-backend.sh
+++ b/testing/otel/t1116-otel-backend.sh
@@ -78,4 +78,56 @@ test_expect_success 'map-export service delivers both decoder-backed maps' '
python3 "$WORK/check-otel.py" "$WORK/otel.meta"
'
+test_expect_success 'map-export timer does not overlap a running export' '
+ systemctl stop shirudo-map-export.timer >/dev/null 2>&1 || true
+ systemctl stop shirudo-map-export.service >/dev/null 2>&1 || true
+ cat >"$WORK/slow-otel.py" <<'PY'
+import http.server, json, pathlib, sys, threading, time
+port_file, meta_file = map(pathlib.Path, sys.argv[1:3])
+state = {"active": 0, "max_active": 0, "paths": [], "times": [], "completed": 0}
+lock = threading.Lock()
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_POST(self):
+ self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ with lock:
+ state["active"] += 1
+ state["max_active"] = max(state["max_active"], state["active"])
+ state["paths"].append(self.path)
+ state["times"].append(time.monotonic())
+ time.sleep(3)
+ payload = b"{}"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ with lock:
+ state["active"] -= 1
+ state["completed"] += 1
+ meta_file.write_text(json.dumps(state))
+ def log_message(self, *args): pass
+server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+server.daemon_threads = True
+port_file.write_text(str(server.server_port))
+while state["completed"] < 4:
+ server.handle_request()
+PY
+ python3 "$WORK/slow-otel.py" "$WORK/slow.port" "$WORK/slow.meta" & SERVER=$!;
+ i=0; while test ! -s "$WORK/slow.port" && test "$i" -lt 100; do i=$((i+1)); sleep .1; done;
+ port=$(cat "$WORK/slow.port") && test -n "$port" &&
+ printf "%s\n" "map_export.otel_endpoint = http://127.0.0.1:$port" "map_export.otel_insecure = true" "map_export.otel_retries = 0" >"$CONFIG" || return 1;
+ (systemctl start shirudo-map-export.service >/dev/null 2>&1) & service_start=$!;
+ systemctl start shirudo-map-export.timer && wait "$service_start";
+ i=0; while { test ! -s "$WORK/slow.meta" || test "$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['completed'])" "$WORK/slow.meta" 2>/dev/null || echo 0)" -lt 4; } && test "$i" -lt 300; do i=$((i+1)); sleep .1; done;
+ kill "$SERVER" >/dev/null 2>&1 || true; wait "$SERVER" 2>/dev/null || true; SERVER="";
+ python3 - "$WORK/slow.meta" <<'\''PY'\''
+import json, sys
+state = json.load(open(sys.argv[1], encoding="utf-8"))
+assert state["completed"] == 4
+assert state["max_active"] == 1
+assert sum(path.endswith("/v1/logs") for path in state["paths"]) == 2
+assert sum(path.endswith("/v1/metrics") for path in state["paths"]) == 2
+assert state["times"][2] - state["times"][1] >= 7
+PY
+'
+
test_done
diff --git a/testing/otel/t1117-otel-serialized-metric.sh b/testing/otel/t1117-otel-serialized-metric.sh
index 5457e942..8ac1f2d4 100644
--- a/testing/otel/t1117-otel-serialized-metric.sh
+++ b/testing/otel/t1117-otel-serialized-metric.sh
@@ -37,39 +37,76 @@ restore() {
trap restore EXIT
systemctl stop shirudo-map-export.timer >/dev/null 2>&1 || true
systemctl stop shirudo-map-export.service >/dev/null 2>&1 || true
-cat >"$WORK/check.py" <<'PY'
+cat >"$WORK/check-batch.py" <<'PY'
+import json, sys
+bodies = json.load(open(sys.argv[1], encoding="utf-8"))
+assert len(bodies) == 4
+for index, expected in enumerate((10, 10, 10, 0)):
+ metrics = {m["name"]: m for m in bodies[index]["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]}
+ assert metrics["shirudo.serialized.packets"]["sum"]["dataPoints"][0]["asInt"] == str(expected)
+ byte_count = 150 if expected else 0
+ assert metrics["shirudo.serialized.bytes"]["sum"]["dataPoints"][0]["asInt"] == str(byte_count)
+PY
+
+cat >"$WORK/otel-batch.py" <<'PY'
+import http.server, json, pathlib, sys
+port_file, body_file = map(pathlib.Path, sys.argv[1:3])
+bodies = []
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_POST(self):
+ bodies.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
+ body_file.write_text(json.dumps(bodies))
+ payload = b"{}"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ def log_message(self, *args): pass
+server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
+server.timeout = 1
+port_file.write_text(str(server.server_port))
+while len(bodies) < 4:
+ server.handle_request()
+PY
+
+cat >"$WORK/check-service.py" <<'PY'
import json, sys
meta = json.load(open(sys.argv[1], encoding="utf-8"))
doc = json.load(open(sys.argv[2], encoding="utf-8"))
assert meta["path"] == "/v1/metrics"
metrics = {m["name"]: m for m in doc["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]}
-assert set(metrics) == {"shirudo.serialized.packets", "shirudo.serialized.bytes"}
-assert metrics["shirudo.serialized.packets"]["unit"] == "1"
-assert metrics["shirudo.serialized.bytes"]["unit"] == "By"
-for metric in metrics.values():
- series = metric["sum"]
- assert series["aggregationTemporality"] == 2
- assert series["isMonotonic"] is True
- point = series["dataPoints"][0]
- assert point["startTimeUnixNano"] == "1699999990000000000"
- assert point["timeUnixNano"] == "1700000000000000000"
assert metrics["shirudo.serialized.packets"]["sum"]["dataPoints"][0]["asInt"] == "10"
assert metrics["shirudo.serialized.bytes"]["sum"]["dataPoints"][0]["asInt"] == "150"
PY
-test_expect_success 'serialized counters become cumulative OTLP metrics' '
- python3 ../helper/otel-mock.py success "$WORK/otel.port" "$WORK/otel.body" "$WORK/otel.meta" &
+test_expect_success 'serialized multi-page metrics preserve peek and drain intervals' '
+ python3 "$WORK/otel-batch.py" "$WORK/otel.port" "$WORK/bodies.json" &
SERVER=$!;
i=0; while test ! -s "$WORK/otel.port" && test "$i" -lt 100; do i=$((i+1)); sleep .1; done;
test -s "$WORK/otel.port" &&
port=$(cat "$WORK/otel.port") &&
- printf "%s\n" "map_export.otel_endpoint = http://127.0.0.1:$port" "map_export.otel_insecure = true" "map_export.otel_retries = 0" >"$CONFIG" &&
"$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1 &&
- test -e "$SERIALIZER_PIN" &&
- systemctl start shirudo-map-export.service &&
+ "$SHIRUDO_BIN" upatch map "$NAME" counters --otel --otel-endpoint="http://127.0.0.1:$port" --peek &&
+ "$SHIRUDO_BIN" upatch map "$NAME" counters --otel --otel-endpoint="http://127.0.0.1:$port" --peek &&
+ "$SHIRUDO_BIN" upatch map "$NAME" counters --otel --otel-endpoint="http://127.0.0.1:$port" &&
+ "$SHIRUDO_BIN" upatch map "$NAME" counters --otel --otel-endpoint="http://127.0.0.1:$port" &&
wait "$SERVER"; SERVER="";
+ python3 "$WORK/check-batch.py" "$WORK/bodies.json" &&
+ "$SHIRUDO_BIN" upatch unload "$UNLOAD" --no-precheck >/dev/null 2>&1 &&
+ "$SHIRUDO_BIN" upatch load "$LOAD" --no-precheck >/dev/null 2>&1;
+ python3 ../helper/otel-mock.py success "$WORK/service.port" "$WORK/service.body" "$WORK/service.meta" &
+ SERVER=$!;
+ i=0; while test ! -s "$WORK/service.port" && test "$i" -lt 100; do i=$((i+1)); sleep .1; done;
+ test -s "$WORK/service.port" &&
+ port=$(cat "$WORK/service.port") &&
+ printf "%s\n" "map_export.otel_endpoint = http://127.0.0.1:$port" "map_export.otel_insecure = true" "map_export.otel_retries = 0" >"$CONFIG" &&
+ if ! systemctl start shirudo-map-export.service; then
+ systemctl status shirudo-map-export.service --no-pager || true
+ journalctl -u shirudo-map-export.service --no-pager -n 100 || true
+ return 1
+ fi && wait "$SERVER"; SERVER="";
systemctl show shirudo-map-export.service -p ExecMainStatus --value | grep -qx 0 &&
- python3 "$WORK/check.py" "$WORK/otel.meta" "$WORK/otel.body"
+ python3 "$WORK/check-service.py" "$WORK/service.meta" "$WORK/service.body"
'
test_done
diff --git a/util/upatch_maps_otel.c b/util/upatch_maps_otel.c
index 80cecc7d..d6f5bdb9 100644
--- a/util/upatch_maps_otel.c
+++ b/util/upatch_maps_otel.c
@@ -16,7 +16,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/mman.h>
#include <sys/random.h>
#include <sys/stat.h>
#include <time.h>
@@ -66,6 +65,7 @@ struct otel_response {
char buf[OTEL_RESPONSE_MAX];
size_t len;
__u64 retry_after;
+ bool retry_after_valid;
};
struct otel_state {
@@ -148,9 +148,9 @@ static int metric_type_from_view(const struct shirudo_map_view *v,
return 0;
}
-int upatch_maps_otel_classify(const struct shirudo_map_view *v,
- enum shirudo_otel_signal *signal,
- char *reason, size_t reason_sz)
+int shirudo_upatch_maps_otel_classify(const struct shirudo_map_view *v,
+ enum shirudo_otel_signal *signal,
+ char *reason, size_t reason_sz)
{
struct metric_type mt;
int rc;
@@ -641,7 +641,7 @@ static __attribute__((unused)) void emit_log_map_data(struct shirudo_json_emit *
for (p = 0; p < v->n_serial_pages; p++) {
const struct shirudo_serial_page *page = &v->serial_pages[p];
char *hex = hex_alloc(page->data,
- page->bytes);
+ page->bytes);
otlp_array_kvlist_begin(e);
otlp_kv_int(e, "page_index", page->page_index);
@@ -746,7 +746,7 @@ static int build_log_payload(const char *path,
json_arr_open(&e, "resourceLogs");
json_obj_open(&e);
json_obj_open_key(&e, "resource");
- emit_resource_attributes(&e);
+ emit_resource_attributes(&e);
json_obj_close(&e);
json_arr_open(&e, "scopeLogs");
json_obj_open(&e);
@@ -761,9 +761,9 @@ static int build_log_payload(const char *path,
json_kv_int(&e, "severityNumber", 9);
json_kv_string(&e, "severityText", "INFO");
json_kv_string(&e, "eventName", "shirudo.bpf.map.snapshot");
- decode_rc = path ? upatch_decode_map_file_otel(path, v,
- &decoded, &decoded_len) :
- upatch_decode_map_otel(v, &decoded, &decoded_len);
+ decode_rc = path ? upatch_decode_map_file_otel(path, v,
+ &decoded, &decoded_len) :
+ upatch_decode_map_otel(v, &decoded, &decoded_len);
if (!decode_rc && record_max && decoded_len > record_max) {
xfree(decoded, decoded_len + 1);
decode_rc = -E2BIG;
@@ -803,9 +803,9 @@ static int build_log_payload(const char *path,
return 0;
}
-int upatch_maps_otel_build_log_file(const char *path,
- const struct shirudo_map_view *v,
- char **out, size_t *out_len)
+int shirudo_upatch_maps_otel_build_log_file(const char *path,
+ const struct shirudo_map_view *v,
+ char **out, size_t *out_len)
{
if (!path)
return -EINVAL;
@@ -908,11 +908,12 @@ static int metric_name(const struct otel_state *st,
if (st->opts.metric_name) {
if (!valid_metric_name(st->opts.metric_name))
return -EINVAL;
- strscpy(out, st->opts.metric_name, 256);
+ if (strscpy(out, st->opts.metric_name, 256) < 0)
+ return -ENAMETOOLONG;
return 0;
}
- n = strsprintf(out, 256, "shirudo.%s.%s", v->upatch, v->name);
- if (n < 0)
+ n = snprintf(out, 256, "shirudo.%s.%s", v->upatch, v->name);
+ if (n < 0 || n >= 256)
return -ENAMETOOLONG;
for (i = 0; out[i]; i++) {
__u8 c = (__u8)out[i];
@@ -935,8 +936,9 @@ static int map_start_ns(const struct shirudo_map_view *v, __u64 *out)
}
if (upatch_bpffs_name(bpffs_name, sizeof(bpffs_name), v->upatch))
return -ENAMETOOLONG;
- if (strsprintf(path, sizeof(path), "%s/%s",
- SHIRUDO_BPFFS_UPATCHES_DIR, bpffs_name) < 0)
+ if ((size_t)snprintf(path, sizeof(path), "%s/%s",
+ SHIRUDO_BPFFS_UPATCHES_DIR, bpffs_name) >=
+ sizeof(path))
return -ENAMETOOLONG;
if (stat(path, &st) != 0)
return -errno;
@@ -1023,7 +1025,7 @@ static __attribute__((unused)) int build_metric_payload(const struct otel_state
st->opts.metric_unit ?: "1");
json_obj_open_key(&e,
st->opts.metric_kind == SHIRUDO_OTEL_METRIC_COUNTER ?
- "sum" : "gauge");
+ "sum" : "gauge");
if (st->opts.metric_kind == SHIRUDO_OTEL_METRIC_COUNTER) {
json_kv_int(&e, "aggregationTemporality", 2);
json_kv_bool(&e, "isMonotonic", true);
@@ -1089,7 +1091,7 @@ static int build_metric_decoded_payload(const char *path,
(void)opts;
rc = path ? upatch_decode_map_file_json(path, v,
- &decoded, &decoded_len) :
+ &decoded, &decoded_len) :
upatch_decode_map_json(v, &decoded, &decoded_len);
if (rc)
return rc;
@@ -1192,10 +1194,10 @@ static int append_signal_path(const char *base, enum shirudo_otel_signal signal,
if (prefix_len == 0)
return -EINVAL;
slash = base[prefix_len - 1] == '/' ? "" : "/";
- n = strsprintf(out, out_sz, "%.*s%s%s%s", (int)prefix_len, base,
- slash, signal_path(signal), tail ? tail : "");
+ n = snprintf(out, out_sz, "%.*s%s%s%s", (int)prefix_len, base,
+ slash, signal_path(signal), tail ? tail : "");
- return n < 0 ? -ENAMETOOLONG : 0;
+ return n < 0 || (size_t)n >= out_sz ? -ENAMETOOLONG : 0;
}
static int resolve_endpoint(struct otel_state *st, const char *spec,
@@ -1207,12 +1209,16 @@ static int resolve_endpoint(struct otel_state *st, const char *spec,
if (spec_is_base)
return append_signal_path(spec, st->signal, st->endpoint,
sizeof(st->endpoint));
+ if (strlen(spec) >= sizeof(st->endpoint))
+ return -ENAMETOOLONG;
if (strscpy(st->endpoint, spec, sizeof(st->endpoint)) < 0)
return -ENAMETOOLONG;
return 0;
}
signal_endpoint = otel_signal_env(st->signal, "ENDPOINT");
if (signal_endpoint) {
+ if (strlen(signal_endpoint) >= sizeof(st->endpoint))
+ return -ENAMETOOLONG;
if (strscpy(st->endpoint, signal_endpoint,
sizeof(st->endpoint)) < 0)
return -ENAMETOOLONG;
@@ -1293,10 +1299,10 @@ shirudo_upatch_maps_otel_build_metric(const struct shirudo_map_view *v,
return build_metric_decoded_payload(NULL, v, opts, out, out_len);
}
-int upatch_maps_otel_build_metric_file(const char *path,
- const struct shirudo_map_view *v,
- const struct shirudo_otel_opts *opts,
- char **out, size_t *out_len)
+int shirudo_upatch_maps_otel_build_metric_file(const char *path,
+ const struct shirudo_map_view *v,
+ const struct shirudo_otel_opts *opts,
+ char **out, size_t *out_len)
{
if (!path)
return -EINVAL;
@@ -1493,7 +1499,6 @@ static size_t response_write(char *ptr, size_t size, size_t nmemb, void *ctx)
return n;
}
-/* curl hands over the line without a NUL behind it. */
static size_t response_header(char *ptr, size_t size, size_t nmemb, void *ctx)
{
struct otel_response *r = ctx;
@@ -1502,14 +1507,25 @@ static size_t response_header(char *ptr, size_t size, size_t nmemb, void *ctx)
if (n > sizeof(prefix) - 1 &&
strncasecmp(ptr, prefix, sizeof(prefix) - 1) == 0) {
+ char value[128];
char *p = ptr + sizeof(prefix) - 1;
- __u64 value;
+ size_t len = n - (sizeof(prefix) - 1);
+ __u64 seconds;
- while (p < ptr + n && isspace((__u8)*p))
+ while (len && isspace((__u8)*p)) {
p++;
- if (!parse_u64(p, digits(p, (size_t)(ptr + n - p)), UINT64_MAX,
- &value))
- r->retry_after = value > 30 ? 30 : value;
+ len--;
+ }
+ while (len && isspace((__u8)p[len - 1]))
+ len--;
+ if (len < sizeof(value)) {
+ memcpy(value, p, len);
+ value[len] = '\0';
+ if (!shirudo_otel_retry_after(value, time(NULL), &seconds)) {
+ r->retry_after = seconds;
+ r->retry_after_valid = true;
+ }
+ }
}
return n;
}
@@ -1570,6 +1586,72 @@ static bool retryable_http(long code)
return code == 429 || code == 502 || code == 503 || code == 504;
}
+int shirudo_status_otel_severity(const char *status, const char **text)
+{
+ if (strcmp(status, "ok") == 0) {
+ *text = "INFO";
+ return 9;
+ }
+ if (strcmp(status, "degraded") == 0 ||
+ strcmp(status, "init-pending") == 0) {
+ *text = "WARN";
+ return 13;
+ }
+ *text = "ERROR";
+ return 17;
+}
+
+int shirudo_otel_retry_after(const char *value, time_t now, __u64 *seconds)
+{
+ struct tm date = {};
+ time_t retry_time;
+ __u64 delay = 0;
+ const char *p;
+ char *end;
+ int parsed;
+
+ if (!value || !seconds || !value[0])
+ return -EINVAL;
+ for (p = value; *p; p++) {
+ if (*p < '0' || *p > '9')
+ break;
+ if (delay < 31)
+ delay = delay * 10 + (__u64)(*p - '0');
+ }
+ if (!*p) {
+ *seconds = delay > 30 ? 30 : delay;
+ return 0;
+ }
+ parsed = 0;
+ memset(&date, 0, sizeof(date));
+ end = strptime(value, "%a, %d %b %Y %H:%M:%S GMT", &date);
+ parsed = !!end;
+ if (!parsed) {
+ memset(&date, 0, sizeof(date));
+ end = strptime(value, "%A, %d-%b-%y %H:%M:%S GMT", &date);
+ parsed = !!end;
+ }
+ if (!parsed) {
+ memset(&date, 0, sizeof(date));
+ end = strptime(value, "%a %b %e %H:%M:%S %Y", &date);
+ parsed = !!end;
+ }
+ if (!parsed)
+ return -EINVAL;
+ while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n')
+ end++;
+ if (*end)
+ return -EINVAL;
+ retry_time = timegm(&date);
+ if (retry_time <= now) {
+ *seconds = 0;
+ return 0;
+ }
+ delay = (__u64)(retry_time - now);
+ *seconds = delay > 30 ? 30 : delay;
+ return 0;
+}
+
/*
* The proto3 JSON mapping lets a receiver send the rejected count as a
* string or a number, and the message is advisory: one that does not
@@ -1601,10 +1683,10 @@ static int check_partial_success(enum shirudo_otel_signal signal,
count, SHIRUDO_JSON_T_INT, &rejected, 0, 0, NULL, 0 };
if (json_parse(body, len, root, ARRAY_SIZE(root)))
return -EBADMSG;
- } else if (partial[0].seen &&
- parse_s64(rejected_text, strlen(rejected_text), 0,
- INT64_MAX, &rejected)) {
- return -EBADMSG;
+ } else if (partial[0].seen) {
+ if (parse_s64(rejected_text, strlen(rejected_text), 0,
+ LLONG_MAX, &rejected))
+ return -EBADMSG;
}
if (rejected < 0)
return -EBADMSG;
@@ -1633,7 +1715,8 @@ static __u32 random_below(__u32 limit)
return value % limit;
}
-static void retry_wait(__u32 retry, __u64 retry_after)
+static void retry_wait(__u32 retry, __u64 retry_after,
+ bool retry_after_valid)
{
struct timespec ts;
__u32 cap_ms = 250U << (retry > 4 ? 4 : retry);
@@ -1641,7 +1724,7 @@ static void retry_wait(__u32 retry, __u64 retry_after)
if (cap_ms > 5000)
cap_ms = 5000;
- delay_ms = retry_after ? (__u32)retry_after * 1000U :
+ delay_ms = retry_after_valid ? (__u32)retry_after * 1000U :
random_below(cap_ms + 1);
ts.tv_sec = delay_ms / 1000;
ts.tv_nsec = (long)(delay_ms % 1000) * 1000000L;
@@ -1729,7 +1812,8 @@ static int otel_post(struct otel_state *st, const char *json, size_t json_len)
curl_easy_cleanup(curl);
if (!retry || attempt + 1 == max_attempts)
break;
- retry_wait(attempt, response.retry_after);
+ retry_wait(attempt, response.retry_after,
+ response.retry_after_valid);
}
if (compressed)
xfree(compressed, compressed_cap);
@@ -1792,8 +1876,8 @@ static int otel_open_common(const char *spec, const struct shirudo_map_view *v,
if (!v || !state)
return -EINVAL;
if (automatic) {
- rc = upatch_maps_otel_classify(v, &signal,
- reason, sizeof(reason));
+ rc = shirudo_upatch_maps_otel_classify(v, &signal,
+ reason, sizeof(reason));
if (rc)
return rc;
fprintf(stderr, "otel: selected %s for %s map %s: %s\n",
@@ -1824,9 +1908,9 @@ static int otel_emit(void *state, const struct shirudo_map_view *v)
st->opts.log_record_max_bytes,
&payload, &len);
else if (st->decoder_path)
- rc = upatch_maps_otel_build_metric_file(st->decoder_path, v,
- &st->opts,
- &payload, &len);
+ rc = shirudo_upatch_maps_otel_build_metric_file(st->decoder_path, v,
+ &st->opts,
+ &payload, &len);
else
rc = shirudo_upatch_maps_otel_build_metric(v, &st->opts,
&payload, &len);
@@ -1941,15 +2025,15 @@ static int build_generic_log_payload(const char *scope_name,
return 0;
}
-int otel_send_log_json(const struct shirudo_otel_opts *opts,
- const char *scope_name,
- const char *event_name,
- int severity_number,
- const char *severity_text,
- const char *status,
- const char *version_id,
- __s64 tamper_attempts,
- const char *body_json, size_t body_len)
+int shirudo_otel_send_log_json(const struct shirudo_otel_opts *opts,
+ const char *scope_name,
+ const char *event_name,
+ int severity_number,
+ const char *severity_text,
+ const char *status,
+ const char *version_id,
+ __s64 tamper_attempts,
+ const char *body_json, size_t body_len)
{
char *payload = NULL;
void *state = NULL;
@@ -1986,13 +2070,33 @@ struct snapshot_writer {
static int snapshot_temp_file(FILE **out)
{
+ const char *tmpdir = getenv("TMPDIR");
+ char path[PATH_MAX];
FILE *file;
- int fd;
+ int fd, n;
- fd = memfd_create("shirudo-map-snapshot",
- MFD_CLOEXEC | MFD_NOEXEC_SEAL);
+ if (!tmpdir || !tmpdir[0])
+ tmpdir = "/tmp";
+ n = snprintf(path, sizeof(path), "%s/%s", tmpdir,
+ "shirudo-map-snapshot.XXXXXX");
+ if (n < 0 || (size_t)n >= sizeof(path))
+ return -ENAMETOOLONG;
+ fd = mkstemp(path);
if (fd < 0)
return -errno;
+ if (fchmod(fd, 0600) != 0) {
+ int rc = -errno;
+
+ unlink(path);
+ close(fd);
+ return rc;
+ }
+ if (unlink(path) != 0) {
+ int rc = -errno;
+
+ close(fd);
+ return rc;
+ }
file = fdopen(fd, "w+b");
if (!file) {
int rc = -errno;
@@ -2221,6 +2325,9 @@ static int parse_s3_spec(struct otel_s3_state *st, const char *spec)
if ((__u8)prefix[i] < 0x20 || prefix[i] == '?' ||
prefix[i] == '#')
return -EINVAL;
+ if (prefix[i] == '.' && (i == 0 || prefix[i - 1] == '/') &&
+ (i + 1 == prefix_len || prefix[i + 1] == '/'))
+ return -EINVAL;
}
memcpy(st->prefix, prefix, prefix_len);
st->prefix[prefix_len] = '\0';
@@ -2231,7 +2338,8 @@ static int parse_s3_spec(struct otel_s3_state *st, const char *spec)
region = "us-east-1";
if (!valid_region(region))
return -EINVAL;
- strscpy(st->region, region, sizeof(st->region));
+ if (strscpy(st->region, region, sizeof(st->region)) < 0)
+ return -ENAMETOOLONG;
endpoint = getenv("AWS_ENDPOINT_URL_S3");
if (endpoint && endpoint[0]) {
size_t len = strlen(endpoint);
@@ -2299,6 +2407,10 @@ static int validate_s3_endpoint(struct otel_s3_state *st)
rc = -EINVAL;
goto out;
}
+ if (strlen(host) >= sizeof(st->host)) {
+ rc = -ENAMETOOLONG;
+ goto out;
+ }
if (strscpy(st->host, host, sizeof(st->host)) < 0) {
rc = -ENAMETOOLONG;
goto out;
@@ -2374,29 +2486,29 @@ static int build_s3_urls(const struct otel_s3_state *st,
snprintf(hostname, sizeof(hostname), "unknown");
hostname[sizeof(hostname) - 1] = '\0';
safe_key_segment(hostname);
- n = strsprintf(key, sizeof(key), "%s%s%s/%s/%s/%s.json.gz",
- st->prefix, st->prefix[0] ? "/" : "", hostname,
- v->upatch, v->name, snapshot->sha256_hex);
- if (n < 0)
+ n = snprintf(key, sizeof(key), "%s%s%s/%s/%s/%s.json.gz",
+ st->prefix, st->prefix[0] ? "/" : "", hostname,
+ v->upatch, v->name, snapshot->sha256_hex);
+ if (n < 0 || (size_t)n >= sizeof(key))
return -ENAMETOOLONG;
if ((size_t)n > S3_KEY_MAX)
return -ENAMETOOLONG;
rc = escape_s3_path(key, escaped, sizeof(escaped));
if (rc)
return rc;
- n = strsprintf(uri, uri_sz, "s3://%s/%s", st->bucket, escaped);
- if (n < 0)
+ n = snprintf(uri, uri_sz, "s3://%s/%s", st->bucket, escaped);
+ if (n < 0 || (size_t)n >= uri_sz)
return -ENAMETOOLONG;
if (st->custom_endpoint)
- n = strsprintf(url, url_sz, "%s/%s/%s", st->endpoint,
- st->bucket, escaped);
+ n = snprintf(url, url_sz, "%s/%s/%s", st->endpoint,
+ st->bucket, escaped);
else if (strchr(st->bucket, '.'))
- n = strsprintf(url, url_sz, "https://s3.%s.amazonaws.com/%s/%s",
- st->region, st->bucket, escaped);
+ n = snprintf(url, url_sz, "https://s3.%s.amazonaws.com/%s/%s",
+ st->region, st->bucket, escaped);
else
- n = strsprintf(url, url_sz, "https://%s.s3.%s.amazonaws.com/%s",
- st->bucket, st->region, escaped);
- return n < 0 ? -ENAMETOOLONG : 0;
+ n = snprintf(url, url_sz, "https://%s.s3.%s.amazonaws.com/%s",
+ st->bucket, st->region, escaped);
+ return n < 0 || (size_t)n >= url_sz ? -ENAMETOOLONG : 0;
}
static int s3_header(struct curl_slist **headers, const char *line)
@@ -2481,7 +2593,8 @@ static int s3_put(struct otel_s3_state *st,
curl_slist_free_all(headers);
return rc;
}
- if (strsprintf(sigv4, sizeof(sigv4), "aws:amz:%s:s3", st->region) < 0) {
+ if (snprintf(sigv4, sizeof(sigv4), "aws:amz:%s:s3", st->region) >=
+ (int)sizeof(sigv4)) {
rc = -ENAMETOOLONG;
goto out;
}
@@ -2554,7 +2667,8 @@ static int s3_put(struct otel_s3_state *st,
curl_easy_cleanup(curl);
if (!retry || attempt + 1 == max_attempts)
break;
- retry_wait(attempt, response.retry_after);
+ retry_wait(attempt, response.retry_after,
+ response.retry_after_valid);
}
out:
curl_slist_free_all(headers);
@@ -2741,10 +2855,10 @@ static int otel_s3_close(void *state)
return 0;
}
-int upatch_maps_otel_send_file(const char *decoder_path,
- const struct shirudo_map_view *v,
- enum shirudo_otel_mode mode,
- const struct shirudo_otel_opts *opts)
+int shirudo_upatch_maps_otel_send_file(const char *decoder_path,
+ const struct shirudo_map_view *v,
+ enum shirudo_otel_mode mode,
+ const struct shirudo_otel_opts *opts)
{
const char *endpoint = opts ? opts->endpoint : NULL;
bool automatic = mode == SHIRUDO_OTEL_AUTO;
@@ -2779,28 +2893,28 @@ int upatch_maps_otel_send_file(const char *decoder_path,
return rc ? rc : close_rc;
}
-int upatch_maps_otel_send(const struct shirudo_map_view *v,
- enum shirudo_otel_mode mode,
- const struct shirudo_otel_opts *opts)
+int shirudo_upatch_maps_otel_send(const struct shirudo_map_view *v,
+ enum shirudo_otel_mode mode,
+ const struct shirudo_otel_opts *opts)
{
- return upatch_maps_otel_send_file(NULL, v, mode, opts);
+ return shirudo_upatch_maps_otel_send_file(NULL, v, mode, opts);
}
-int upatch_maps_otel_send_decoded(const struct shirudo_map_view *v,
- enum shirudo_otel_signal signal,
- const struct shirudo_otel_opts *opts)
+int shirudo_upatch_maps_otel_send_decoded(const struct shirudo_map_view *v,
+ enum shirudo_otel_signal signal,
+ const struct shirudo_otel_opts *opts)
{
int rc;
if (signal == SHIRUDO_OTEL_LOG)
- rc = upatch_maps_otel_send(v, SHIRUDO_OTEL_FORCE_LOG,
- opts);
+ rc = shirudo_upatch_maps_otel_send(v, SHIRUDO_OTEL_FORCE_LOG,
+ opts);
else if (signal == SHIRUDO_OTEL_METRIC)
- rc = upatch_maps_otel_send(v, SHIRUDO_OTEL_FORCE_METRIC,
- opts);
+ rc = shirudo_upatch_maps_otel_send(v, SHIRUDO_OTEL_FORCE_METRIC,
+ opts);
else
return -EINVAL;
if (rc == -E2BIG && opts && opts->s3_uri)
- return upatch_maps_otel_send(v, SHIRUDO_OTEL_S3, opts);
+ return shirudo_upatch_maps_otel_send(v, SHIRUDO_OTEL_S3, opts);
return rc;
}
diff --git a/util/upatch_maps_otel.h b/util/upatch_maps_otel.h
index eab172f1..c3a12687 100644
--- a/util/upatch_maps_otel.h
+++ b/util/upatch_maps_otel.h
@@ -6,6 +6,7 @@
#include <stdbool.h>
#include <stddef.h>
+#include <time.h>
#include <shirudo/misc.h>
@@ -44,42 +45,44 @@ struct shirudo_otel_opts {
const char *metric_description;
};
-int upatch_maps_otel_classify(const struct shirudo_map_view *v,
- enum shirudo_otel_signal *signal,
- char *reason, size_t reason_sz);
-int upatch_maps_otel_build_log_file(const char *path,
- const struct shirudo_map_view *v,
- char **out, size_t *out_len);
-int upatch_maps_otel_build_metric_file(const char *path,
+int shirudo_upatch_maps_otel_classify(const struct shirudo_map_view *v,
+ enum shirudo_otel_signal *signal,
+ char *reason, size_t reason_sz);
+int shirudo_upatch_maps_otel_build_log_file(const char *path,
+ const struct shirudo_map_view *v,
+ char **out, size_t *out_len);
+int shirudo_upatch_maps_otel_build_metric_file(const char *path,
+ const struct shirudo_map_view *v,
+ const struct shirudo_otel_opts *opts,
+ char **out, size_t *out_len);
+int shirudo_upatch_maps_otel_send(const struct shirudo_map_view *v,
+ enum shirudo_otel_mode mode,
+ const struct shirudo_otel_opts *opts);
+int shirudo_upatch_maps_otel_send_file(const char *path,
const struct shirudo_map_view *v,
- const struct shirudo_otel_opts *opts,
- char **out, size_t *out_len);
-int upatch_maps_otel_send(const struct shirudo_map_view *v,
- enum shirudo_otel_mode mode,
- const struct shirudo_otel_opts *opts);
-int upatch_maps_otel_send_file(const char *path,
- const struct shirudo_map_view *v,
- enum shirudo_otel_mode mode,
- const struct shirudo_otel_opts *opts);
+ enum shirudo_otel_mode mode,
+ const struct shirudo_otel_opts *opts);
/* Export using the matching decoder's signed, static signal selection. */
-int upatch_maps_otel_send_decoded(const struct shirudo_map_view *v,
- enum shirudo_otel_signal signal,
- const struct shirudo_otel_opts *opts);
+int shirudo_upatch_maps_otel_send_decoded(const struct shirudo_map_view *v,
+ enum shirudo_otel_signal signal,
+ const struct shirudo_otel_opts *opts);
/*
* Send an already-built JSON object as the structured body of one OTLP
* log. A tamper_attempts of 0 or more rides along as an attribute; a
* negative one leaves it out.
*/
-int otel_send_log_json(const struct shirudo_otel_opts *opts,
- const char *scope_name,
- const char *event_name,
- int severity_number,
- const char *severity_text,
- const char *status,
- const char *version_id,
- __s64 tamper_attempts,
- const char *body_json, size_t body_len);
+int shirudo_otel_send_log_json(const struct shirudo_otel_opts *opts,
+ const char *scope_name,
+ const char *event_name,
+ int severity_number,
+ const char *severity_text,
+ const char *status,
+ const char *version_id,
+ __s64 tamper_attempts,
+ const char *body_json, size_t body_len);
+int shirudo_otel_retry_after(const char *value, time_t now, __u64 *seconds);
+int shirudo_status_otel_severity(const char *status, const char **text);
#endif /* SHIRUDO_UTIL_UPATCH_MAPS_OTEL_H */