This is the multi-page printable view of this section.
Click here to print.
Return to the regular view of this page.
Developer Guide
Read the contribution guide before making changes, and prepare the environment using Building from Source.
1 - Extending Features
HUATUO supports three observability extensions: Metrics, Event, and AutoTracing. They share a registration mechanism but differ in triggers, runtime cost, and output.
| Type |
Trigger |
Output |
Use Case |
| Metrics |
Periodic collection |
Prometheus |
Continuous system monitoring and long-term trends |
| Event |
Kernel events or thresholds |
ES, local files, optional Prometheus |
Continuous observation that captures abnormal conditions |
| AutoTracing |
Detected system anomalies |
ES, local files, optional Prometheus |
More expensive context collection on demand |
Modes
Metrics
Metrics periodically collects system state through procfs, sysfs, or eBPF and exports it in Prometheus format for real-time monitoring and trend analysis. Built-in collectors cover:
- CPU: sys, usr, util, load, nr_running, and more.
- Memory: vmstat, memory_stat, directreclaim, asyncreclaim, and more.
- I/O: d2c, q2c, freeze, flush, and more.
- Network: ARP, socket memory, qdisc, netstat, netdev, sockstat, conntrack entry counts and limits, and more.
Event
Event continuously watches kernel events or thresholds and saves kernel context when an anomaly occurs. It targets low-overhead observation that can remain enabled. Data is written to Elasticsearch and local files and can also produce Prometheus metrics. Built-in events include:
- Abnormal scheduling tick intervals:
sched_tick.
- OOM kills:
memory_oom_kill.
- Soft lockups:
softlockup.
- Tasks in D state:
hungtask.
- Memory reclaim:
memory_reclaim_events.
- Packet drops:
dropwatch.
- Network receive latency:
net_rx_latency.
AutoTracing
AutoTracing invokes diagnostic tools after detecting a system anomaly, collecting flame graphs, context snapshots, and other evidence. It suits diagnostic data that is too costly to collect continuously. Results are written to Elasticsearch and local files and can also be converted into Prometheus metrics. Built-in capabilities include:
- Container CPU and host system-mode CPU tracing:
cpuidle, cpusys.
- D-state load tracing:
dload.
- Memory allocation burst tracing:
memburst.
- Disk I/O anomaly tracing:
iotracing.
Event and AutoTracing both use Tracing mode and share the ITracingEvent interface. They save abnormal context for root-cause analysis and can expose statistics to Prometheus by also implementing Collector.
Add Metrics
Custom Metrics exports Prometheus metrics through /metrics.
Implement Collector
Create a type under core/metrics that implements Collector:
type Collector interface {
Update() ([]*Data, error)
}
type exampleMetric struct{}
func (c *exampleMetric) Update() ([]*metric.Data, error) {
return []*metric.Data{
metric.NewGaugeData("example", value, "example value", nil),
}, nil
}
Register the Collector
Register the implementation as a metric collector with FlagMetric:
func init() {
tracing.RegisterEventTracing("example", newExampleMetric)
}
func newExampleMetric() (*tracing.EventTracingAttr, error) {
return &tracing.EventTracingAttr{
TracingData: &exampleMetric{},
Flag: tracing.FlagMetric,
}, nil
}
Manage BPF Objects
If an implementation provides both Start and Update, these methods may run concurrently. Do not read or write a bpf.BPF interface directly in collector fields. Use Reference and Lease from internal/bpf/bpf_ref.go to manage the object lifecycle:
type example struct {
object bpf.Reference
}
func (c *example) Start(ctx context.Context) (retErr error) {
object, err := bpf.LoadBpf(bpf.ThisBpfOBJ(), nil)
if err != nil {
return err
}
if err := object.Attach(); err != nil {
return errors.Join(err, object.Close())
}
if err := c.object.Publish(object); err != nil {
return errors.Join(err, object.Close())
}
defer func() {
retErr = errors.Join(retErr, c.object.UnPublish())
}()
<-ctx.Done()
return nil
}
func (c *example) Update() ([]*metric.Data, error) {
lease, ok := c.object.Acquire()
if !ok {
return nil, nil
}
defer lease.Release()
items, err := lease.DumpMapByName("example_map")
if err != nil {
return nil, fmt.Errorf("dump example_map: %w", err)
}
return buildMetrics(items), nil
}
Interface contracts:
Publish transfers object ownership to Reference. After success, do not call object.Close() directly.
- The
Lease returned by Acquire keeps the BPF object alive until the current Update completes. Pair it with Release and do not copy the Lease.
UnPublish blocks new Acquire calls, waits for all leases to be released, then closes the BPF object and returns any close error.
- Serialize
Publish and UnPublish. The current framework ensures that Start does not run concurrently for the same instance.
An Update that has already started can therefore finish using the original BPF object. When Start exits or restarts, the object is closed only after those Update calls complete.
Add an Event
An Event must implement ITracingEvent:
type ITracingEvent interface {
Start(ctx context.Context) error
}
type exampleEvent struct{}
func (e *exampleEvent) Start(ctx context.Context) error {
// Detect the event and collect context.
// storage.Save writes data to ES and local storage.
storage.Save("example", containerID, time.Now(), eventData)
return nil
}
Register it with FlagTracing:
func init() {
tracing.RegisterEventTracing("example", newExampleEvent)
}
func newExampleEvent() (*tracing.EventTracingAttr, error) {
return &tracing.EventTracingAttr{
TracingData: &exampleEvent{},
Interval: 10,
Flag: tracing.FlagTracing,
}, nil
}
To also export Prometheus metrics, implement Collector and add tracing.FlagMetric to Flag.
Add AutoTracing
AutoTracing uses the same ITracingEvent interface and registration framework as Event:
type exampleAutoTracing struct{}
func (t *exampleAutoTracing) Start(ctx context.Context) error {
// Collect context after an anomaly triggers tracing.
storage.Save("example", containerID, time.Now(), tracingData)
return nil
}
func init() {
tracing.RegisterEventTracing("example", newExampleAutoTracing)
}
func newExampleAutoTracing() (*tracing.EventTracingAttr, error) {
return &tracing.EventTracingAttr{
TracingData: &exampleAutoTracing{},
Interval: 10,
Flag: tracing.FlagTracing,
}, nil
}
See core/metrics, core/events, and core/autotracing for complete implementations covering BPF map access, container information, data storage, and Prometheus output.
2 - Debugging
Choose a debugging workflow: Full Stack, BPF Debugging, or GitHub Actions VM Debugging.
Full Stack
The development Compose setup builds an image from the current workspace and starts the collector, API Server, Elasticsearch, Prometheus, and Grafana. The collector needs access to the host kernel and cgroups. Run from the repository root on Linux with root privileges:
Compose aggregates component logs in the foreground. After changing source code, stop the environment with Ctrl+C and rerun the command. Docker reuses the toolchain and Go build caches.
After debugging, remove the containers, data volumes, and development image:
sudo make compose-dev-down
This command deletes the Elasticsearch data volume. Do not run it if you need to retain the data.
BPF Debugging
BPF code can emit kernel debug messages through the bpf_dbg() and bpf_dbg_msg() macros defined in bpf/include/bpf_dbg.h. Debugging has both compile-time and runtime switches and is fully disabled by default.
Add Instrumentation
Each BPF source file using debug macros must declare its own debug map:
#include "bpf_dbg.h"
BPF_DBG_MAP(native_cpu);
SEC("perf_event")
int prog(void *ctx)
{
bpf_dbg_msg(ctx, native_cpu, "enter prog");
bpf_dbg(ctx, native_cpu, "pid and addr", pid, addr, 0);
return 0;
}
bpf_dbg_msg() emits a message only. bpf_dbg() can also include up to three u64 arguments.
Build Debug Objects
Set BPF_DEBUG=1 to pass -DDEBUG_BPF to Clang:
To regenerate artifacts without rebuilding the binaries:
make BPF_DEBUG=1 gen-build
BPF_DEBUG=0 is the default. In this mode, macros expand to no-ops; the debug perf event array, event structure, bpf_ktime_get_ns, and bpf_perf_event_output are excluded from the BPF object.
Enable Runtime Output
After building debug objects, also pass --log-bpf-debug when starting the profiler. Only the native profiler currently supports this flag:
./profiler --type cpu --language native --log-bpf-debug ...
During BPF loading, bpf.NewDbg(true) rewrites the bpf_dbg_enabled constant to 1 before LoadBpf. When disabled, the verifier eliminates the corresponding branches as dead code. Each BPF object has an independent switch.
Read Debug Output
User space logs debug events at Debug level:
file: BPF source filename.
line: source line number.
ts: event timestamp converted to UTC wall time.
msg: debug message.
args: up to three u64 arguments; omitted when all are zero.
bpf_dbg: file=native_oncpu_profiler.c line=120 ts=2026-01-11T08:30:00.123456Z msg=enter prog args=[0x1f4 0xffff8881 0x0]
Debug output requires both a build with BPF_DEBUG=1 and the runtime flag --log-bpf-debug.
VM Debugging
Use the OS Distro QEMU CI workflow to test a branch in supported Linux virtual machines without preparing a local VM.
Prepare a Fork
- Fork the repository and enable workflows on the fork’s Actions page.
- Add your SSH public key to your GitHub account. Only the user who starts the workflow can connect.
- Push the branch to debug to your fork.
Start a VM
- Open Actions > OS Distro QEMU CI > Run workflow in your fork.
- Select the branch to debug.
- Keep the default
ubuntu24.04, enter multiple distributions separated by commas, or use all to select all supported distributions.
- Under Debug VM, choose when and how long to retain the VM.
- Start the workflow and open its
Test in VM job.
If Run workflow is missing, sync your fork’s default branch first. GitHub only displays manual workflows that exist on the default branch.
Choose Before test to inspect or change the VM before testing, After test on failure to investigate a failed test, or After test always to retain the VM after testing regardless of the outcome.
Connect to the VM
Open the job’s Debug VM: Retain ... step and follow the log instructions:
- Run the complete SSH command from the log in a local terminal to connect to the GitHub runner.
- On the runner, run the logged
ssh -i ... root@<VM_IP> command to enter the VM.
Copy the commands directly; they already contain the correct key path and VM address.
End the Session
Exit the VM, then release the workflow from the runner:
cd "$GITHUB_WORKSPACE"
touch continue
The workflow then continues with testing or cleanup. Disconnecting SSH alone does not release the workflow. Without this command, it waits until the selected retention period expires.
3 - Integration Tests
Integration and E2E tests verify Huatuo collection, service interfaces, and external dependencies. This guide covers running tests, configuring the test environment, and reading results.
Run Tests
Run commands from the repository root. Tests require Linux and root privileges. Use a dedicated test node for cases involving containers, Pods, or block devices.
Build and run through the Makefile:
sudo make integration
sudo make e2e
sudo make test
make test includes unit, integration, and E2E tests. Alternatively, build first, then run scripts as root:
make build test-build
sudo bash integration/run.sh
sudo bash e2e/run.sh
Single Cases and Repetitions
An optional count after the script name sets repetitions. It defaults to 1 and accepts 1–1,000. The number of selected tests multiplied by repetitions must not exceed 10,000.
sudo bash integration/run.sh test_metrics_exclude_filter.sh 10
sudo bash e2e/run.sh test_metrics.sh 2
You can also select E2E with --suite e2e:
sudo bash integration/run.sh --suite e2e test_metrics.sh 2
Invalid arguments return exit code 2 without creating a run directory or report.
Parallel Runs
Integration tests default to one worker. -j accepts 1–8; INTEGRATION_JOBS also sets the worker count:
sudo bash integration/run.sh -j 2
sudo env INTEGRATION_JOBS=2 make integration
Some cases require exclusive execution, so actual concurrency may be lower. Run only one suite runner per host. E2E always runs serially and does not accept -j greater than 1.
E2E cases use a runner-started default bamai unless declared otherwise in integration/lib_runner.sh. A case that needs its own blacklist or configuration can add ["e2e/test_example.sh"]=case to runner_test_bamai_startup (runner is the default). The runner still initializes service addresses, but the case launches bamai with its own configuration and verifies each daemon’s logs before replacement, including daemons in subdirectories. Cleanup retains strict checks for logs/PID files in the case workspace; skipping before startup does not require a daemon log. Integration tests continue to manage their own services.
Environment Requirements
Run make build test-build before invoking scripts; missing build artifacts cause failures. Reports require jq. The test environment also needs unshare, mount, flock, ss, and stat. Individual cases check their required commands, kernel capabilities, services, and input files.
Missing root privileges or required namespace commands cause selected cases to report SKIP. Cases also report specific reasons for missing external dependencies. SKIP does not mean validation passed.
Common environment variables:
| Variable |
Purpose |
INTEGRATION_JOBS |
Integration worker count; default 1 |
KUBELET_CERT, KUBELET_KEY |
Client certificate and private key paths for the local kubelet |
PROFILER_TOOL_DIR |
Java/Python collection tool directory; default _output/tools |
APISERVER_TEST_NODE |
Local Kubernetes node name for the apiserver matrix |
APISERVER_TEST_NATIVE_IMAGE, APISERVER_TEST_GO_IMAGE, APISERVER_TEST_JAVA_IMAGE, APISERVER_TEST_PYTHON_IMAGE |
Apiserver matrix images |
TEST_IO_DISK |
Dedicated scratch disk for IO tests; contents may be overwritten |
Pass overrides with sudo env NAME=value ... so sudo environment filtering does not discard them.
Results and Logs
| Result |
Meaning |
| PASS |
Test and cleanup succeeded |
| SKIP |
Missing dependencies, unstarted execution, or cancellation; see the report reason |
| FAIL |
Test, service preparation, or cleanup failed |
After a failure, no new cases start. Unstarted and cancelled executions are SKIP. INT/TERM interruption returns 130/143. A run with only skipped cases can return success, so also inspect counts and skip reasons.
Each valid invocation creates /tmp/huatuo-test.XXXXXX/. Integration runs remove this directory after every execution passes and the final summary is printed. Runs with skips, failures, or interruptions retain it for diagnosis. E2E runs retain it regardless of outcome. The run directory contains test_run_results.json; each execution directory contains stdout.log, stderr.log, and service logs, configuration, and response data. For a fully passing integration run, the printed output_dir and results_path refer to the directory removed at completion.
Console Summary
The console shows individual results, a JSON summary, and then failed test logs:
| Field |
Meaning |
status |
passed, failed, or interrupted |
output_dir, results_path |
Run directory and full report path |
runs_per_test |
Planned repetitions per test |
started_at, finished_at, duration_seconds |
Start time, finish time, and elapsed seconds |
execution_counts |
total, passed, failed, skipped, including repeated and unstarted executions |
skipped_tests |
Names of skipped tests |
failed_tests |
Failed test names, execution indexes, reasons, and logs |
Each failed_tests entry contains name, run_index, reason, and logs. The logs array contains paths relative to output_dir. |
|
Logs include nonempty .log, .err, .out, .json, and .conf text files under the failed execution directory. Binary files, test_run_results.json, and reason.*.log are excluded. Each failed execution has a Failed: ... (run N/M) heading after the JSON summary, followed by file headings and contents. Files larger than 64 KiB show a (64KB) heading and their last 64 KiB; full content remains in the original file. Start diagnosis with reason and stderr.log, then inspect related service logs and responses.
Log contents are printed as text, including JSON files. Explicit failure reasons take precedence. Unhandled command failures record the script, line, command, and exit code. Failures without a recorded cause retain the exit-code fallback; caught child errors are not treated as the test failure.
Full Report
test_run_results.json uses schema_version: 1:
| Field |
Meaning |
suite, runs_per_test |
Suite and planned repetitions per test |
status |
running, completed, aborted, interrupted |
exit_code, reason |
Run exit code and reason for early termination |
started_at, finished_at, duration_seconds |
Start time, finish time, and elapsed seconds |
execution_counts |
Execution counts |
test_executions |
One record for each planned execution of each test |
Each execution contains test_name, run_index, result, exit_code, reason, timestamps and duration, and logs.stdout / logs.stderr paths relative to the report directory. Results are passed, failed, or skipped; unfinished executions use null. Unstarted executions have no timestamps or logs. Unknown process exit codes are null. Cleanup failure can make an execution failed even if its process exited with code 0.
A report with status: running is incomplete and must not be treated as final. Forced termination or report write failures can leave this state.
Inspect failed or skipped executions:
jq '.test_executions[] | select(.result == "failed" or .result == "skipped") | {test_name, run_index, result, reason, logs}' /tmp/huatuo-test.XXXXXX/test_run_results.json
Common Test Cases
CPU Metrics and Autotracing
sudo bash e2e/run.sh test_metrics_cpu_util.sh
sudo bash e2e/run.sh test_metrics_cpu_stat.sh
sudo bash e2e/run.sh test_metrics_cpu_runqlat_tracing.sh
sudo bash e2e/run.sh test_autotracing_cpuidle.sh
sudo bash e2e/run.sh test_autotracing_dload.sh
These cases need local Kubernetes/kubelet access. The reference environment is a VM with 4 CPUs and 8 GB of memory. Install stress-ng; CPU util/stat also require sysstat. The container runtime must be able to obtain workload images. CPU reference collection, cpuidle, and dload also require Docker.
CPU metrics support cgroup v1/v2. Runqlat and cpuidle require the relevant kernel sampling capabilities. Dload functional checks require Legacy cgroups, taskstats, dm-delay, dmsetup, losetup, mkfs.ext4, modprobe, nsenter, mount privileges, and an available loop device. Other cgroup modes report unsupported behavior and a skip reason.
Apiserver
sudo bash integration/run.sh test_apiserver_profile_disabled.sh
sudo bash integration/run.sh test_apiserver_profiling.sh
sudo bash e2e/run.sh test_apiserver_profiling.sh
sudo bash e2e/run.sh test_apiserver_profiling_matrix.sh
Integration cases cover authentication, capabilities, parameters, and invalid requests. E2E covers profile results, pagination, flamegraphs, and the language/sampling matrix. Run test_apiserver_profiling_{stop,concurrent,recovery,node_recovery}.sh separately for stopping, concurrency, and recovery scenarios.
API checks without storage do not need Docker, perf, or a compiler. Sampling tests need Docker, curl, jq, ss, timeout, perf settings that allow sampling, and built collection tools. Native host workloads also need gcc.
The matrix additionally requires Python 3, ip, kubectl administration access, crictl, local kubelet credentials, and asprof/py-spy. APISERVER_TEST_NODE can select the local node. Otherwise, the test matches it automatically and fails if the match is ambiguous.
Default images are gcc:14, golang:1.24, eclipse-temurin:17-jdk, and python:3.11-slim. Override them with the corresponding APISERVER_TEST_*_IMAGE variables. Image access is required at runtime. The workspace summary.tsv records each matrix combination’s result.
Profiling
sudo bash integration/run.sh test_profiler_native_cpu.sh
sudo bash integration/run.sh test_profiler_native_cpu_offcpu.sh
sudo bash integration/run.sh test_profiler_native_memory_virtual_alloc.sh
sudo bash integration/run.sh test_profiler_native_memory_physical_usage.sh
sudo bash integration/run.sh test_profiler_java_cpu_multi_pid.sh
sudo bash integration/run.sh test_profiler_java_memory_usage_alloc.sh
sudo bash integration/run.sh test_profiler_python_cpu_multi_pid.sh
Java/Python cases need the corresponding collection tools in PROFILER_TOOL_DIR. Container, thread-group, and CPU-specific tests are test_profiler_native_cpu_container.sh, test_profiler_native_cpu_thread_group.sh, and test_profiler_native_cpu_list.sh.
Storage and Resource Limits
These storage tests do not require Elasticsearch:
| Test |
Checks |
test_basic_storage_elasticsearch_config.sh |
Elasticsearch configuration completeness and startup behavior |
test_basic_storage_localfile_rotation.sh |
LocalFile rotation, retention count, and event data |
LocalFile rotation needs kernel BTF, the skb/kfree_skb tracepoint, and built Dropwatch tools.
sudo bash integration/run.sh test_node_runtime_limits.sh
The resource-limit test checks CPU and memory configuration during startup and normal operation. It needs writable CPU and memory controllers; cgroup v2 also needs accessible systemd. Run on both v1/hybrid and v2 environments to establish coverage of both hierarchies. A busy environment or missing capabilities produces SKIP. This case does not test CPU throughput or OOM behavior.
IO
IO cases cover public metrics, container attribution, automatic diagnostics,
health events and device evidence. Run on a dedicated Linux test node with
BPF/BTF support. Build as an ordinary user, then run the harness as root:
make build test-build
sudo bash integration/run.sh test_metrics_io_wait.sh
sudo env TEST_IO_DISK=/dev/vdb bash integration/run.sh test_metrics_blk_iotrace.sh
TEST_IO_DISK defaults to /dev/disk/by-id/virtio-huatuo-ci-io. It must be a
dedicated scratch disk whose contents may be overwritten. When the default
device is missing, cases that require it are skipped. A missing device at a
different configured path, a non-block device, or a mounted or partitioned disk
fails the case. MD, loop and NVMe-loop backing files also
use this disk. Cases requiring SCSI driver controls create separate
scsi_debug devices. Container cases use the local Kubernetes node and
existing kubelet credentials.
make unit checks Go configuration, compatibility selection, decoding and metric conversion.
Host and container metric cases verify real blk_iotrace output; they do not
independently verify complete tracepoint argument counts on each kernel or
exercise every remap path.
Health evidence cases invoke real smartctl and nvme, requiring
smartmontools and nvme-cli, respectively. Controlled tool responses cover
command failures.
SchedBlame
sudo bash integration/run.sh test_sched_blame.sh
Use an isolated Linux 4.18–6.5 test environment with BTF, scheduler and cgroup hooks, a local Kubernetes node, kubelet authentication, and a cached BUSINESS_POD_IMAGE. Unsupported kernels or missing capabilities produce SKIP.
Success prints sched-blame live collection verified. Failed runs retain CSV data, command logs, and Pod diagnostics in the workspace. This case verifies live collection and contention scenarios, not exact resource accounting.
4 - BPF ABI Guide
C structures on the BPF side are the single source of truth for the perf event ABI. Go types are generated from BTF in BPF objects; do not maintain equivalent structures manually.
Conventions
Each ABI domain maps to one C header and one generated Go file:
| Item |
Convention |
| Domain name |
<domain> |
| C header |
bpf/include/abi/<domain>_types.h |
| C structure prefix |
<domain>_ |
| Generated Go file |
internal/bpf/abi/<domain>_types_generated.go |
<domain> must start with a lowercase letter and contain only lowercase letters, digits, and underscores. Avoid overlapping domain prefixes such as net and net_rx.
Implementation
The following example creates the sample domain.
Create bpf/include/abi/sample_types.h:
// Copyright 2026 The HuaTuo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __BPF_ABI_SAMPLE_H__
#define __BPF_ABI_SAMPLE_H__
#include "bpf_abi.h"
#define SAMPLE_DATA_LEN 4
struct sample_detail {
u32 code;
u8 data[SAMPLE_DATA_LEN];
};
struct sample_event {
u64 kernel_observed_ns;
struct sample_detail detail;
u32 tgid;
u8 kind;
u8 pad[3];
};
BPF_ABI_EXPORT(sample_detail);
BPF_ABI_EXPORT(sample_event);
#endif /* __BPF_ABI_SAMPLE_H__ */
Requirements:
- Structure names must use the
<domain>_ prefix.
- Every structure that needs a generated Go type must call
BPF_ABI_EXPORT(<type>), including nested structures.
- Headers define ABI types and related constants only, with no BPF programs, maps, or business logic.
- Array lengths must be compile-time constants and consistent across all BPF compilation units.
2. Use the Types in BPF
ABI headers depend on base types such as u8 and u16. Include them after vmlinux.h and the project’s base headers:
#include "vmlinux.h"
#include "bpf_common.h"
#include "abi/sample_types.h"
Use the ABI structure directly when sending a perf event:
struct sample_event event = {};
event.kernel_observed_ns = bpf_ktime_get_ns();
event.tgid = bpf_get_current_pid_tgid() >> 32;
event.kind = kind;
bpf_perf_event_output(ctx, &events, COMPAT_BPF_F_CURRENT_CPU,
&event, sizeof(event));
Zero-initialize events to avoid writing uninitialized padding to the perf buffer. Structures passed to bpf_perf_event_output must be defined in an ABI header.
3. Generate and Use Go Types
Run from the repository root:
The generated file is:
internal/bpf/abi/sample_types_generated.go
Reference the generated type directly in Go:
import "github.com/ccfos/huatuo/internal/bpf/abi"
var event abi.SampleEvent
if err := reader.ReadInto(&event); err != nil {
return fmt.Errorf("read sample event: %w", err)
}
The generated file contains structures, the SampleEventSize constant, and layout assertions based on unsafe.Sizeof and unsafe.Offsetof. Generated files are read-only; do not edit them manually.
Types and Layout
| Type |
Support |
| Fixed-width integers of 1, 2, 4, or 8 bytes |
Supported |
| Fixed-length arrays with nonzero length |
Supported |
| Nested structures satisfying the same constraints |
Supported |
typedef with a supported target type |
Supported |
Pointers, union, enum, floating-point types |
Unsupported |
Bit fields, _Bool |
Unsupported |
| Zero-length or flexible arrays |
Unsupported |
| Recursive structures, overlapping fields, or non-byte-aligned structures |
Unsupported |
Layout requirements:
- Use fixed-width integers such as
u8, s16, u32, and s64.
- Order fields for alignment, adding explicit
u8 pad[N] padding where needed.
- Do not use platform-dependent types such as
long or unsigned long.
- Do not bypass layout validation with
__attribute__((packed)).
- Structures with the same name in multiple BPF objects must have identical fields, offsets, and sizes.
C names are converted from underscore-separated names to exported Go names: sample_event becomes SampleEvent, and kernel_observed_ns becomes KernelObservedNS. Follow the field conventions for semantics and naming across layers. Avoid C names that map to the same Go name, such as sample_id and sample_i_d.
Validation
After adding or changing an ABI, run:
make gen-build
go test ./build/bpfabi-tool
make check
For new perf events, also add decoding coverage for at least:
- Integer boundary values and native byte order.
- Nested structures and the first and last array elements.
- Fields before and after padding.
- Sample size against the generated
<GoType>Size constant.
Common Errors
| Error |
Check |
has no "<domain>_" btf anchors |
Is the header included by a BPF source file? Does the type call BPF_ABI_EXPORT? |
without matching abi header |
Do the header name and structure prefix match? Do domain prefixes overlap? |
differs between objects |
Do conditional compilation, array-length macros, or included headers change the layout? |
go offset is ... btf offset is ... |
Reorder fields or add explicit padding; do not use packed |
go type name ... collides |
Rename C types or fields that map to the same Go name |
5 - Retransmission and Drop Correlation Design
This guide explains the design, evidence limits, state management, and resource lifecycle of local TCP retransmission/drop correlation for developers and maintainers.
The two streams have no shared event ID, so correlation makes conservative inferences from namespaces, four-tuples, TCP sequence/ACK evidence, and monotonic time.
1. Result Semantics
| Result |
Meaning |
software |
An unconsumed host software drop satisfies every strict condition. |
hardware |
A devlink DROP trap record satisfies the same strict conditions. |
unknown |
No strict match, or the matched record has an unknown source enum; correlation_reason distinguishes matched and unmatched terminal states. |
No match does not prove a network or hardware problem. The drop may predate collection, belong to another network namespace, or arrive without the TCP fields required for matching.
Shutdown finalizes waits according to whether they have expired; see Shutdown.
2. Operating Modes
See Retransmission Tracing for setup, full parameters, and command examples. The modes below define responsibilities and state ownership.
- Without correlation, tcpshark loads
tcp_retransmit.o and collects and directly outputs retransmissions only.
- With correlation, tcpshark loads
tcp_retransmit.o and net_dropwatch.o in one process, which owns both perf inputs, the timer, output, and shutdown.
- huatuo-bamai’s standalone dropwatch runs independently through
cmd/dropwatch, emits only raw DropWatchTracing, and shares no state with the embedded source.
All three retransmission hooks use synthetic L3 filters in both modes. Correlation uses only EventTracing.TCPRetransmit.Filter: an empty value becomes tcp, and the same expression goes to both BPF objects. Expressions depending on Ethernet addresses that cannot be evaluated equivalently on synthetic L3 input are rejected before startup. EventTracing.Dropwatch.Filter controls only standalone dropwatch.
Both commands use HardwareAuto to detect devlink trap support. If the tracepoint is unavailable, they warn and continue software collection. If available, they accept only driver-reported DROP traps. --device and --device-excluded have the same names as in standalone dropwatch, are mutually exclusive, and filter only the embedded source’s software and hardware records. They require --with-dropwatch. Retransmissions use the shared L3 filter.
internal/dropwatch.ResolveMetadata resolves drop sources and reasons. Software reasons come from a BTF table loaded once per session; unknown values are decimal numbers, and unsupported older kernels use NOT_SUPPORTED. Hardware reasons and groups come from trap names and groups, not the software table. Readers own source and reason strings independently of reusable ABI buffers.
Matches output drop_source, drop_reason, and drop_reason_group. Unmatched records omit them and carry one correlation outcome plus separate diagnostics. On a match, drop_location uses drop_source; otherwise it is unknown. This is a correlation classification, unlike standalone dropwatch’s kernel address. Unknown sources are not inferred from reasons or stacks. Hardware records missing namespace or TCP match fields cannot match strictly.
3. Time Windows
dropwatch and retransmission use separate perf readers, and events may come from different CPUs. User-space arrival order therefore differs from kernel occurrence order:
CPU 2: drop monotonic_ns=180, still in the dropwatch ring
CPU 0: retransmit monotonic_ns=200, reaches user space first
User space: retransmit(200) -> drop(180)
The implementation uses two windows for different purposes:
retransmitRetentionDuration = 100 * time.Millisecond
maxDropToRetransmitAge = time.Second
- 100ms is the user-space delivery reordering budget. A retransmission arriving first enters a waiting queue and outputs
unknown if still unmatched at expiry. Expired records are finalized before each new event is processed; the timer only wakes the loop and does not define deadline semantics.
- 1s is the maximum causal candidate age, checked using BPF
kernel_observed_ns. Candidates must satisfy:
drop.kernel_observed_ns <= retransmit.kernel_observed_ns
retransmit.kernel_observed_ns - drop.kernel_observed_ns <= 1s
observed_timestamp is user-space wall time, affected by scheduling and clock adjustments, and is not used for matching. The fixed 1s window is the supported scope, not a theoretical upper bound for every Linux RTO. Results outside it remain unknown.
4. Bounded State
Waiting retransmissions and unmatched drops use separate instances of the package-local generic store[T]. The container handles capacity, TTL, flow indexing, and deletion; the correlator handles strict matching and finalization.
type storeEntry[T any] struct {
value T
flow *flowKey
deadline time.Time
sequence uint64
node *list.Element
}
type store[T any] struct {
byDeadline list.List
byFlow map[flowKey][]*storeEntry[T]
capacity int
ttl time.Duration
nextSequence uint64
}
| Instance |
Stored Value |
Capacity |
TTL |
retransmitStore |
waitingRetransmit, inline in the entry |
1024 |
100ms |
dropStore |
*dropEvent |
4096 |
1s + 100ms |
waitingRetransmit contains only the raw event, matching fields, and cross-namespace candidate flags. storeEntry manages list nodes, deadlines, and insertion sequence; drops use *dropEvent directly. The list’s Element.Value and flow bucket reference the same *storeEntry[T], whose node points back to the list element. Entries reference read-only flow data to avoid copying addresses. Deletion removes both index references and clears the flow slice tail; removing the final entry deletes the empty bucket.
Flow keys canonically order two AddrPort values so both directions share one bucket. Original direction remains in event data for strict matching. Namespace is excluded from the key so similar candidates across namespaces can set diagnostic flags. Matching scans and slice deletion are O(k), where k is the flow’s candidate count. Finding the earliest deadline and removing a list node are O(1).
Each instance has a fixed TTL, and the loop supplies nondecreasing processing time, so insertion order also orders deadlines. The list supports expiry and capacity eviction without exposing a FIFO consumer interface. When the waiting queue is full, the earliest-deadline record is finalized as queue_full. A full drop cache simply evicts its earliest-deadline candidate. Causal checks use kernel_observed_ns.
Two readers deliver events through unbuffered channels. A single correlation loop accesses the stores, with no locks or separate cleanup goroutine. One timer always targets the earliest deadline across both stores, ensuring cleanup even when only cached drops exist. Each input or timer wakeup expires entries before matching and capacity checks; now >= deadline means expired. 100ms is the matching deadline, but blocking synchronous output can delay actual cleanup and delivery.
5. Strict Matching
Forward segment candidates require:
- The same network namespace, address family, and directional four-tuple.
- A drop no later than the retransmission, with a difference of at most 1s.
- Overlapping TCP SYN/data/FIN and retransmission sequence ranges.
- No positive match for RST or unsupported retransmission types.
Reverse ACK candidates use the reverse four-tuple and require an ACK covering the retransmission sequence end. SYN and SYN-ACK apply their own stricter ACK/SYN conditions.
Among drop candidates, choose the greatest drop.kernel_observed_ns, breaking ties by larger insertion sequence. When a drop arrives later, choose the strict-matching retransmission with the smallest insertion sequence while scanning remaining candidates to record namespace-match state. A strict match is immediately removed from both deadline and flow indexes and consumed once. Forward segments and reverse ACKs share the flow index; namespace checks precede packet and time checks.
A same-namespace drop in the same flow sets netNamespace to true even if time or sequence checks fail. Later nonmatching candidates do not clear it. Strict matches always have true. No candidates, only other namespaces, or incomparable namespaces leave false: no match was observed, rather than different namespaces being proven.
NetNamespace preserves this state in output. JSON and text use matched_net_namespace, omitted when false.
6. Terminal States
types.CorrelationReason is a string type. Each correlation outputs one correlation_reason:
| Go Constant |
JSON Value |
Meaning |
CorrelationMatched |
matched |
Strict match, including a drop with an unknown source. |
CorrelationUnsupported |
unsupported |
Current rules cannot handle this retransmission; it never enters the waiting queue. |
CorrelationWarmup |
warmup |
Wait expired without a match; retransmission predates source readiness. |
CorrelationWaitTimeout |
wait_timeout |
Wait expired without a match; retransmission is at or after source readiness. |
CorrelationQueueFull |
queue_full |
The full waiting queue evicted this retransmission before expiry. |
CorrelationInterrupted |
interrupted |
The loop exited and interrupted an unexpired wait. |
Each terminal branch assigns correlationResult.reason directly. Output uses the enum and validates that matched has a drop and the other five states do not. Empty, unknown, or contradictory values return errors. Fields are omitted when correlation is disabled; all finalized events have a valid state when enabled. Upgrade tools and receivers together when migrating from the reason array to the single field.
At expiry, kernel retransmission time determines the state: warmup before source readiness, otherwise wait_timeout, including within 1s after readiness. The 1s drop-to-retransmission bound applies only to matching candidates, not warmup. User-space delays do not change classification. Only the expiry branch applies this rule; strict matches, unsupported events, eviction, and interruption retain their own reasons. Warmup neither prevents matches nor ends waits early.
matched_net_namespace independently indicates a same-namespace drop in the same flow, regardless of packet and time conditions. It cannot replace correlation_reason=matched.
The flag can coexist with loss and rate-limit counters without changing the single terminal state. Unnormalizable drops and drop-cache eviction neither end a retransmission wait directly nor produce retransmission-level reasons.
7. Sample Loss and Rate Limiting
Three independent channels report status separately; do not add them together:
perf_lost: sum of per-CPU bpf_perf_out_dropwatch map counters, using the shared perf-output counter facility bpf_perf_output.h. BPF increments by 1 when bpf_perf_event_output returns a negative value, for example when no reader is attached on the current CPU.
lost_samples: ring-buffer overflow counts accumulated from user-space PERF_RECORD_LOST, visible only while the reader runs and queryable through ReadStatus after processing the loss record.
rate_limited: total_missed in the bpf_rlimit_dropwatch rate-limit status map.
Successful ReadStatus sets HasMapCounters=true, serialized as map_counters_available=true. On error, the flag is false and PerfLost and RateLimited are zero, meaning unavailable rather than no loss or throttling. LostSamples remains valid and the snapshot is retained. These are instance-wide cumulative counters; maps and readers are sampled separately and cannot establish why an individual retransmission was unmatched.
User space sums perf_lost across CPUs and returns the current snapshot without checking counter rollback or uint64 addition overflow. This describes evidence completeness and cannot classify the network fault behind an unmatched event.
The correlator derives TCP sequence spans from IPv4 total length or IPv6 payload length. With GSO/offload, IP header lengths may not cover the full skb; matching scope is not expanded on that basis.
The dropwatch hot path is:
software: hardware marker lookup/delete -> device/pcap filter
-> status map lookup -> bpf_ktime_get_ns() -> rate limit -> perf output
hardware: device/pcap filter -> status map lookup -> bpf_ktime_get_ns()
-> rate limit -> perf output
Filter-rejected events therefore perform no status lookup, event-time read, or counter update. Software drops first consume any hardware dedup marker so a rejected kfree path does not leave it behind.
8. Shutdown
Session and Resource Ownership
The command layer manages process-wide bpf.Init/Shutdown and runtime timeouts. retransmit.Run creates output before attaching probes and finishes finalization, worker waits, Tracer closure, and output completion before returning. Configuration failure, cancellation, and runtime failure release acquired resources. Global BPF resources close after session cleanup.
tcpshark uses one errgroup.WithContext for the retransmission rate-limit reader, retransmission reader, embedded dropwatch reader, and correlation loop. All command workers share groupCtx. A worker error cancels the others, and Wait returns the first worker error. Resource owners combine close errors with errors.Join.
retransmit.Tracer and internal/dropwatch.Tracer each own their BPF objects, readers, and rate-limit alert workers. Failed Open rolls back acquired resources. Callers must still call Close after session context cancellation. An alert-worker failure cancels its collector, and Close returns the original error.
When a startup cancellation check stops setup and rollback succeeds, internal/dropwatch.Open returns dropwatch.ErrOpenCanceled directly. Callers compare this marker directly to identify an expected stop. Operation and rollback failures retain their causes and do not wrap this marker.
Read and Close Contracts
retransmit.Tracer.ReadInto checks closure or cancellation before reading. Once a low-level read starts, its result is preserved rather than replaced by later closure or cancellation. Close can interrupt reads for both tracer types; callers must serialize Close calls on each instance.
internal/dropwatch.Tracer has the following read and lifecycle contracts:
ReadInto returns types.ErrExitByCancelCtx directly for caller cancellation, deadline expiry, signal termination, and normal closure. Callers compare this marker directly. Successful reads and independent read errors remain unchanged even when cancellation happens concurrently.
- An alert-worker failure interrupts reads with the worker error instead of the stop marker.
- Its context derives from
groupCtx. Each instance allows one ReadInto caller; status reads and closure can run concurrently.
ReadStatus can read final counters after context cancellation. The status type is types.DropwatchStatus; output uses drop_perf_status, including map-counter availability.
Close cancels the instance, detaches and closes event and alert readers, waits for the alert worker, then releases the BPF object. Closing the alert reader wakes idle reads without waiting for the polling deadline.
- The first
Close returns cleanup errors. Later calls return nil without retrying cleanup or replaying the first error.
Finalization on Exit
On normal termination or worker failure:
- Cancel the shared
groupCtx.
- Both
ReadInto readers and the correlation loop exit. Stop reading dropwatch perf-ring records not yet delivered to the correlator.
- Call
drainRetransmits(now) with one timestamp: finalize expired entries, then clear unexpired entries, writing output in deadline order.
- After all workers exit, close both Tracers and collect internal alert-worker and resource-release errors.
- Finish socket output last. The session does not close the caller’s
io.Writer.
Expired items output warmup or wait_timeout; unexpired items output interrupted. All retain drop_location=unknown, diagnostic flags, and perf status. Matched or evicted events are not finalized again.
Shutdown does not guarantee draining kernel buffers. Trailing drops may be lost, ending otherwise matchable retransmissions early.
9. File Responsibilities
cmd/tcpshark/
├── main.go # Signals, version, CLI entry
├── cli.go # Argument validation, path and filter normalization
├── run.go # Global BPF lifecycle, timeout, feature dispatch
└── retransmit/ # Retransmission feature package
├── config.go # Config、RunConfig
├── run.go # Run: resource composition, execution, cleanup
├── tracer.go # Open, ReadInto, Close, rate-limit worker
├── bpf_load.go # loadBPF, attachBPF, probe selection
├── event_reader.go # Dual-stream reads, conversion, channel delivery
├── correlation_loop.go # select, timer, exit finalization
├── correlation.go # Correlation state machine, expiry finalization
├── correlation_match.go # Candidate selection, consumption, namespace match state
├── match.go # Match types, namespace/flow/sequence/ktime
├── store.go # Entries, flow index, capacity and expiry management
├── event.go # Conversion of both ABI record types
├── classify.go # Retransmission classification
├── correlation_output.go # Status completion, symbol resolution, correlation fields
└── output.go # Text, JSON, socket output
The top level invokes retransmit.Run(ctx, *RunConfig) without handling ABI records, channels, correlation timers, or status counters.
The CLI validates scalar values and argument combinations before compiling the filter. A nonempty --output-storage skips validation of --output and warns on stderr if the latter was explicitly set. Without storage, only json and text are accepted. RunConfig.Tracing defines collection settings. A nil Dropwatch reads and outputs directly; otherwise two read workers and one correlation loop run. Correlation composes the retransmission feature rather than forming a general collection framework.
Ordinary mode creates no correlation channels or timers. The feature session handles conversion, classification, correlation, and output; Tracer owns low-level collection resources. See Shutdown for lifecycle details.
The correlator expires candidates before processing each input or timer; stores do not repeat expiry checks. It returns matching evidence, one terminal state, and diagnostic flags without modifying output fields. correlation_output.go constructs final output.
Each nonempty output batch reads dropwatch status once at entry; empty batches do not. Only matched drops undergo symbol resolution. Status is read even for an all-matched batch. On read failure, events are still written before returning the status error. Write failure stops the batch and combines both errors. Only unmatched events carry status snapshots and diagnostic flags; valid reader counters survive status-read failure. Matched events do not receive these fields.
Internal retransmission events retain only the ABI record and successful-read observedAt. Waiting queues do not store full display objects. Matching constructs netip addresses directly from ABI data and uses ABI enums without string conversion. IPv4-mapped IPv6 normalizes to IPv4. Single-event reads handle loss retries and read time consistently. Ordinary mode reuses an event with synchronous output; correlation mode reads into independent events before delivery to avoid overwriting pending data.
run.go creates channels and starts read workers; senders close channels. Read functions run synchronously and deliver correlation events through channels. Receivers own events independently of the sender’s reusable buffer. TCPRetransmitTracing is created only for final output; ObservedTimestamp uses the original read time, not correlation completion time. SYNACK conversion fills TCP flags with SYN and ACK.
cmd/tcpshark/retransmit has no Go internal import restriction but is reserved by convention for tcpshark and must not depend back on the command layer. The two commands share collection code in:
internal/dropwatch/
├── config.go # Config, HardwareMode, configuration validation
├── tracer.go # Tracer API, newTracer ownership, rollback, worker lifecycle
├── load.go # loadBPF, attachBPF: loading, map/reader setup, probe attachment
├── netdev.go # Device filtering and map configuration
├── status.go # ReadStatus: output failures, ring loss, rate-limit counters
├── reason.go # LoadReasonNames: kernel BTF reason table and numeric fallback
├── metadata.go # ResolveMetadata: source, software reason, hardware trap/group
└── decode.go # DecodePacket: ABI header adaptation and packet.Parse
Open(ctx, *Config) returns a concrete *Tracer; see Shutdown for read and close contracts. DecodePacket results do not borrow raw record memory.
Symbol resolution and DropWatchTracing display conversion belong to standalone dropwatch. TCP correlation directly retains ABI KernelObservedNS, namespace, stack PCs, and resolved drop sources and reasons.
6 - Storage Interfaces
This guide describes write, filter, and batched-query contracts for development and troubleshooting. See Storage Services for deployment and configuration.
Architecture
Nodes write kernel events to enabled local-file and Elasticsearch or OpenSearch backends. Both remote backends use [Storage.Elasticsearch] and are selected by their address.
Remote writes use the Bulk API to submit batches asynchronously.
graph TB
subgraph kernel["Linux kernel"]
K1[Kernel events]
K2[AutoTracing]
end
subgraph huatuo["HUATUO Agent (node)"]
T["Collection layer"]
L["Local directory\nhuatuo-local/"]
S["Storage module\nBulkIndexer buffer"]
end
subgraph backends["Storage backends"]
ES[Elasticsearch]
OS[OpenSearch]
end
kernel --> T
T --> L
T --> S
S -->|Bulk API + automatic retry| ES
S -->|Bulk API + automatic retry| OS
Write Flow
Remote writes enqueue events in BulkIndexer. Background workers submit a batch when the byte threshold, time threshold, or process-exit condition is met. Local-file writes are synchronous and independent of the remote Bulk path.
sequenceDiagram
participant T as Collection layer
participant L as Local directory (huatuo-local/)
participant S as Storage module (BulkIndexer)
participant B as ES / OpenSearch
T->>S: Collect kernel event and serialize to JSON
par Local path (synchronous)
S->>L: Write local file
and Remote path (asynchronous batches)
S->>S: Enqueue in Bulk buffer; return immediately
Note over S: 5 MB / 1 s / exit condition met
S->>B: POST /_bulk (multiple records)
B-->>S: 200 OK + per-item results
Note over S: Log failed items through OnFailure
end
Bulk Writes
Buffering and Flushing
| Parameter |
Value |
Meaning |
FlushBytes |
5 MB |
Flush immediately when buffered bytes reach this threshold |
FlushInterval |
1 s |
Force a flush 1 second after the previous flush |
NumWorkers |
4 |
Background goroutines submitting concurrent Bulk requests |
| Process exit |
Close(ctx) |
Triggered by SIGTERM/SIGINT; drain buffers within 10 s |
Failures and Retries
Bulk failures have two levels with different retry scopes:
| Level |
Condition |
Handling |
Retry |
| Batch failure |
Transport error (connection, timeout, TLS) HTTP 429 / 502 / 503 / 504 |
After the initial failure, retry at most 3 times, waiting 200, 400, and 800 ms before retries; at most 4 requests |
Automatic |
| Batch rejection |
HTTP 400 / 401 / 403 / 404 / 413, etc. |
No retry; discard the entire batch and log through OnError |
Discard |
| Item failure |
200 OK with an item failure: version conflict, mapping error, oversized document |
No retry; discard only the failed item and log index/id/status/type/reason through OnFailure |
Discard |
| Item success |
200 OK with item success |
Primary shard write succeeded; replica failures produce warnings with the index, document ID, and failed shard count |
— |
HTTP success does not mean every record was written successfully.
The current client also waits 1600 ms after the final retryable failure before returning, without sending a fifth request. Request cancellation can end the wait early.
Data Loss Scenarios
Events can still be lost after Save returns nil:
- Abnormal process termination:
SIGKILL or host power loss discards unflushed BulkIndexer buffers. A local copy may exist only if the local backend is enabled and its write succeeded.
- Mitigation: SIGTERM/SIGINT use graceful shutdown, calling
Close to force a flush with a maximum wait of 10 seconds.
- Permanent batch rejection: 4xx errors other than 429 discard the entire batch. Typical causes include a disabled index, invalid password, or a document exceeding
http.max_content_length.
- Diagnosis:
OnError logs the ES type and reason.
- Permanent item failure: mapping conflicts, version conflicts, or document syntax errors.
- Diagnosis:
OnFailure logs identify the failed record by index/id.
Local copies depend on backend enablement, write success, and rotation and retention policies. Their existence does not guarantee recovery after a remote write failure.
Profiling Window Commit
The IRQ CLI uses the shared profiler runner and single-window Pipeline to send types.ProfilingWindow through Toolstream. The handler registered by internal/profiling.Register calls pkg/profiling/store.SaveSync to save the window. On an error-free commit request, the same handler calls Store.Commit to write a durable completion marker.
After remote output succeeds, the tool sends end + commit and waits for the daemon’s storage and publication ACK. The task succeeds only when the profile is queryable and publication succeeds. Ordinary End, collection failure, and disconnection do not publish a completion marker. If the ACK is lost, results may already be published; callers should query by task ID. See IRQ Tracing for deployment dependencies and upgrade requirements.
Filter Semantics
The internal storage query API combines filters with AND. SQLite and Elasticsearch use these rules for non-null scalar values:
| Operator |
Meaning |
OpEq, OpNe |
Equal/not equal; neither matches missing or null values |
OpGt, OpGte, OpLt, OpLte |
Strict or inclusive range comparison |
OpIn |
Membership in a nonempty slice or array of scalar values |
OpExists, OpNotExists |
Presence/absence of a non-null queryable value; leave Value unset |
An empty string is literal: OpEq("") matches empty strings; OpNe("") requires an existing, non-null, nonempty string. Use OpNotExists for missing fields; OpEq("") does not mean missing. Host profiling queries use OpNotExists on container_hostname.
Comparison values support Go built-in strings, booleans, integers, and finite floating-point numbers; range comparisons reject booleans. time.Time and timeutil.Timestamp become UTC strings with nine fractional digits, including in OpIn. Nil, pointers, objects, nested collections, and non-finite numbers return driver.ErrInvalidQuery. Integer range bounds preserve original JSON precision; supported numeric ranges still depend on the backend and field mapping.
Elasticsearch callers must specify the actual indexed field used for exact comparison: the original field for keyword mappings, or an explicitly configured keyword subfield such as hostname.keyword for text mappings. The backend neither guesses subfields nor ORs text and keyword queries. OpNe combines exists and must_not term on the same field. Full-text matching and whole-array equality are outside this scalar contract.
Elasticsearch existence checks apply to indexed values, not key presence in _source. Mapping settings such as ignore_above, null_value, and normalizers can alter existence or equality behavior. To match SQLite semantics, use mappings that preserve the intended scalar semantics. Date fields cannot be compared with empty strings; use existence operators to express “has a date value.”
Batched Reads
Parameters
Query(ctx, query, consume) invokes callbacks synchronously in order, with at least one record per batch. Callers must supply an explicit total record limit.
| Parameter |
Meaning and Constraints |
Limit |
Total records delivered after skipping Offset matches; must be positive |
Offset |
Matching records to skip; must be nonnegative |
BatchSize |
Records per batch; must be nonnegative. Zero uses the default of 100; each batch is capped by the remaining total allowance |
storage.Store.Query validates parameters; backends consume the validated values.
Count and Values use only Filters, ignoring Sorts, Limit, Offset, and BatchSize, including zero or negative pagination values.
Count counts all matching records. Values uses a separate size, validated as nonnegative by storage.Store.Values. Backends do not repeat pagination or size validation for these operations.
Backend Differences
- SQLite reads rows using one SELECT with
LIMIT/OFFSET. The callback holds the sole database connection and must not synchronously access the same backend again.
- Elasticsearch 7/8 and OpenSearch use Scroll snapshots to read and skip beyond the result window. Deep offsets still require reading and skipping earlier records; separate API requests do not share snapshots.
- Local-file storage does not support queries.
Callbacks and Cleanup
Each batch owns its data independently. Callback, decoding, or backend errors, and cancellation, terminate the query immediately without rolling back earlier callback effects.
Scroll cleanup uses an independent bounded context and attempts resource release even if the query context is canceled. Queries are not retried automatically because a lost response may already have advanced the Scroll cursor.
Application Queries
Task recovery reads 1000 Jobs at a time in ascending ID order, closes the read before starting supervision tasks, and continues with an ID cursor to avoid offset-pagination omissions as task states change.
The API supplies pagination defaults only when limit is omitted:
| Query |
Default Records |
Maximum Records |
Other Limits |
| Job list |
100 |
1000 |
Read one extra record to determine has_more |
| Raw Profiles |
20 |
100 |
Read one extra record to determine has_more; response cap of 64 MiB |
Explicit zero, negative, or excessive limit values return parameter errors. See the Profiling API for request and response formats.
Flame graph queries merge Profiles while reading, up to 100000 windows, and read one extra record to detect overflow. Exceeding the limit prompts the caller to narrow the time range or filters; read or merge failures return no partial results.
Input batches can be released after processing, but merged-result memory still grows with the number of distinct stacks.
Error Semantics
These rules describe Elasticsearch/OpenSearch response handling. HTTP success does not guarantee complete results.
Query and Values return errors on search timeouts or shard failures. Query does not deliver the failed batch, but does not roll back previously consumed batches; Values returns no partial results. Count returns zero and an error on shard failure. Search timeout errors take precedence over shard failures. Shard errors include the total failed shard count and the first failure’s type, reason, and nested cause if available.
After a successful HTTP response, DeleteByQuery checks timeout first, then execution failures. It returns the first error while preserving the reported deletion count. A missing index returns zero without error; other HTTP errors return zero and an error. Completed deletions are not rolled back.
Direct writes and deletes retain primary-shard success semantics on replica failure and log available failure details as warnings. Bulk writes also report replica failures without retrying successful primary-shard writes.
HTTP errors include the response status and available Elasticsearch error details. Unrecognized or oversized error bodies are reported verbatim up to 4 KiB, with a truncation marker when needed.
Kernel Observation Time
Event documents may contain a top-level kernel_observed_timestamp in UTC. observed_timestamp is user-space observation time; uploaded_timestamp is storage write time. None substitutes for another. Older documents and events without kernel time omit the new field; historical data is not migrated automatically. Raw kernel_observed_ns is used only for in-process correlation and is not written to new documents.
7 - Field Conventions
Define consistent semantics before naming event fields according to each layer’s conventions. The same name must not represent different concepts.
Layer Rules
| Layer |
Rule |
Example |
| BPF C |
Reflect raw kernel semantics and units |
tgid, kernel_observed_ns |
| Go |
MixedCaps; keep initialisms uppercase |
TGID, KernelObservedNS |
| JSON |
Use user-facing measurement semantics |
pid, observed_timestamp |
| CLI flags |
Lowercase with hyphens |
--pid, --cpu-list |
| CLI text and column headers |
Use standard uppercase abbreviations |
PID, CPU, COMM |
CPUs and Tasks
| Concept |
Definition |
BPF C |
Go |
JSON |
CLI |
| Logical CPU ID |
ID returned by bpf_get_smp_processor_id() |
cpu |
CPU |
cpu |
--cpu, CPU |
| Process ID |
User-space process identifier, the Linux TGID |
tgid |
TGID in raw events, PID in output |
pid |
--pid, PID |
| Thread ID |
Linux task PID |
tid |
TID |
tid |
--tid, TID |
| Parent process ID |
Parent process TGID |
parent_tgid |
ParentTGID or output-layer ParentPID |
parent_pid |
PPID |
| Task comm |
Kernel task comm, which may be a thread name |
comm |
Comm |
comm |
COMM |
Containers, Cgroups, and Network Namespaces
| Concept |
BPF C |
Go |
JSON |
CLI |
| Container ID |
container_id |
ContainerID |
container_id |
--container-id, CONTAINER_ID |
| cgroup ID |
cgroup_id |
CgroupID |
cgroup_id |
CGROUP_ID |
| Cgroup CSS address |
<subsystem>_css_addr |
<Subsystem>CSSAddr |
<subsystem>_css_addr |
<SUBSYSTEM>_CSS_ADDR |
| Network namespace inode |
netns_inum |
NetNamespaceInum |
net_namespace_inum |
NETNS_INUM |
| Network namespace cookie |
netns_cookie |
NetNamespaceCookie |
net_namespace_cookie |
NETNS_COOKIE |
| Network device index |
ifindex or <name>_ifindex |
Ifindex or <Name>Ifindex |
ifindex or <name>_ifindex |
IFINDEX |
Keep the kernel terms inum and ifindex as single words in Go, not INum or IfIndex. Expand netns to NetNamespace and net_namespace in user-facing Go and JSON fields.
Numeric Units
| Concept |
Definition |
BPF C |
Go |
JSON |
| Nanosecond duration |
Difference between two times |
<name>_ns |
<Name>NS |
<name>_ns |
| Nanosecond threshold |
Duration used as a trigger condition |
<name>_threshold_ns |
<Name>ThresholdNS |
<name>_threshold_ns |
| Count |
Unitless cumulative value |
<name>_count |
<Name>Count |
<name>_count |
| Bytes |
Data size, not bit count |
<name>_bytes |
<Name>Bytes |
<name>_bytes |
Time Fields
Field Semantics
| Concept |
Definition |
BPF C |
Go |
JSON |
| Raw kernel observation time |
CLOCK_MONOTONIC reading in nanoseconds, excluding suspend time |
kernel_observed_ns |
KernelObservedNS |
Not serialized; internal correlation only |
| Kernel observation time |
Raw monotonic time converted to UTC |
Not applicable |
KernelObservedTimestamp |
kernel_observed_timestamp |
| User-space observation time |
UTC time when the producer observes the event in user space |
Not applicable |
ObservedTimestamp |
observed_timestamp |
| Unix nanosecond timestamp |
Unix time in nanoseconds |
timestamp_ns |
TimestampNS |
timestamp_ns |
kernel_observed_timestamp, observed_timestamp, and uploaded_timestamp represent kernel observation, user-space observation, and storage write times, respectively. Kernel observation records when the hook runs; it does not necessarily mark the onset of a physical hardware error or network fault.
Serialization and Parsing
HUATUO serializes timestamps in UTC with exactly nine fractional digits:
2006-01-02T15:04:05.000000000Z
For example, the UTC time July 22, 2026, 00:30:00.123456789 is written as:
2026-07-22T00:30:00.123456789Z
- All hosts use the
Z time zone, so distributed queries do not need to handle different local time zones.
- Nine fractional digits give strings a fixed width. Lexical order therefore matches chronological order, which helps sorting in logs and keyword indexes.
- Nanosecond precision preserves the time information supplied by Go’s
time.Time and event-tracing pipelines.
When writing data to HUATUO, use the shared helper:
timestamp := timeutil.FormatUTC(time.Now())
Read timestamps with timeutil.Parse. It accepts the canonical format and legacy RFC 3339 values with 0 to 9 fractional digits. The returned value is always normalized to UTC.
Compare timestamps as strings only when both values were generated by FormatUTC. Third-party RFC 3339 values may use variable fractional precision or non-UTC offsets.
Clock Conversion
Conversion between monotonic time and UTC requires the same host, boot, and host time namespace. Monotonic time alone cannot precisely recover UTC for historical events across clock adjustments or system suspend.
UTC conversion caches the offset between the monotonic and real-time clocks. The first call at least 1 hour after the last successful sample refreshes it; ordinary calls do not extend the cache lifetime. Sampling failures return an error and are retried on the next call. Clock adjustments or suspend do not trigger early refreshes; the offset updates on the first call after expiry.
Observation Time and Compatibility
The top-level document stores UTC time, not kernel_observed_ns. Producers without kernel time and older documents omit kernel_observed_timestamp; do not fill it with user-space or write time. In historical RAS documents, observed_timestamp represented kernel observation time, so historical user-space observation time cannot be inferred from it.
The JSON and text outputs of tcpshark and dropwatch use kernel_observed_timestamp for kernel observation time. Upgrade the tools and Agent together. Existing documents remain unchanged, without automatic backfill or rewriting.