This is the multi-page printable view of this section.
Click here to print.
Return to the regular view of this page.
Latest
Introduction
HUATUO is an operating-system observability project open sourced by DiDi and incubated by the China Computer Federation (CCF). It provides kernel metrics, abnormal events, automatic tracing, and profiling for cloud-native, AI computing, and bare-metal environments.
Start with Quick Start, choose capabilities in Key Features, and see Deployment and Practical Guides for deployment and integration.
Kernel Versions
The target kernel version is 4.18 or later. Individual features also depend on kernel interfaces, configuration, and drivers. The distribution test matrix includes these virtual machine environments:
| No. |
OS |
Kernel |
Cgroup |
Clang |
libbpf |
glibc |
gcc |
make |
Python |
Java |
Rust |
| 1 |
Ubuntu 26.04 LTS |
7.0.0-30-generic |
v2 |
21.1.8 |
1.6.3 |
2.43 |
15.2.0 |
4.4.1 |
3.14.4 |
17.0.20.1+1 |
1.93.1 |
| 2 |
Ubuntu 24.04.4 LTS |
6.8.0-138-generic |
v2 |
15.0.7 |
1.3.0 |
2.39 |
13.3.0 |
4.3 |
3.12.3 |
17.0.20.1+1 |
1.75.0 |
| 3 |
Ubuntu 22.04.5 LTS |
5.15.0-190-generic |
v2 |
15.0.7 |
0.5.0 |
2.35 |
11.4.0 |
4.3 |
3.10.12 |
17.0.20.1+1 |
1.75.0 |
| 4 |
Ubuntu 20.04.6 LTS |
5.4.0-216-generic |
hybrid |
12.0.0 |
0.5.0 |
2.31 |
9.4.0 |
4.2.1 |
3.8.10 |
17.0.20.1+1 |
1.75.0 |
| 5 |
Debian 13 (trixie) |
6.12.107+deb13-cloud-amd64 |
v2 |
19.1.7 |
1.5.0 |
2.41 |
14.2.0 |
4.4.1 |
3.13.5 |
17.0.20.1+1 |
1.85.1 |
| 6 |
Debian 12 (bookworm) |
6.1.0-53-cloud-amd64 |
v2 |
15.0.6 |
1.1.2 |
2.36 |
12.2.0 |
4.3 |
3.11.2 |
17.0.20.1+1 |
1.63.0 |
| 7 |
Rocky Linux 9.8 |
5.14.0-687.10.1.el9_8.0.1.x86_64 |
v2 |
21.1.8 |
1.5.0 |
2.34 |
11.5.0 |
4.3 |
3.9.25 |
17.0.20.1+1 |
1.92.0 |
| 8 |
Rocky Linux 8.10 |
4.18.0-553.el8_10.x86_64 |
v1 |
21.1.8 |
0.5.0 |
2.28 |
8.5.0 |
4.2.1 |
3.6.8 |
17.0.20.1+1 |
1.92.0 |
| 9 |
Fedora Linux 44 |
6.19.10-300.fc44.x86_64 |
v2 |
22.1.8 |
1.6.3 |
2.43 |
16.2.1 |
4.4.1 |
3.14.3 |
17.0.20.1+1 |
1.98.1 |
| 10 |
openEuler 24.03 LTS-SP4 |
6.6.0-159.4.3.154.oe2403sp4.x86_64 |
v1 |
17.0.6 |
1.2.2 |
2.38 |
12.3.1 |
4.4.1 |
3.11.6 |
17.0.20.1+1 |
1.96.0 |
| 11 |
openEuler 22.03 LTS-SP4 |
5.10.0-216.0.0.115.oe2203sp4.x86_64 |
v1 |
12.0.1 |
0.8.1 |
2.34 |
10.3.1 |
4.3 |
3.9.9 |
17.0.20.1+1 |
1.82.0 |
| 12 |
Anolis OS 8.10 |
5.10.134-18.an8.x86_64 |
v1 |
18.1.8 |
0.5.0 |
2.28 |
8.5.0 |
4.2.1 |
3.6.8 |
17.0.20.1 |
1.79.0 |
| 13 |
OpenCloudOS 9.6 |
6.6.119-51.5.oc9.x86_64 |
v2 |
17.0.6 |
1.2.2 |
2.38 |
12.3.1 |
4.4.1 |
3.11.6 |
17.0.20.1 |
1.96.0 |
- WeChat group (include your name and organization when joining) and official account:

1 - Quick Start
Choose one of three paths: view the demo, run containers, or build from source. Running the collector locally requires Linux. Container deployment also requires Docker and the permissions used in the examples.
View the Demo
Log in to the demo site to view kernel metrics, abnormal events, and flame graphs. The demo username is huatuo and the password is huatuo1024.
Run Containers

Docker
The following image disables container information retrieval and Elasticsearch storage by default. Start the collector:
$ docker run --privileged --pid=host --cgroupns=host --network=host -v /sys:/sys -v /proc:/proc -v /run:/run huatuo/huatuo-bamai:latest
Fetch metrics from another terminal:
$ curl -s localhost:19704/metrics
A response with Prometheus-format metrics confirms that the metric endpoint is accessible. Event and AutoTracing results are written to huatuo-local inside the container. This directory may have no records until collection is triggered. In a test environment, generate the target activity or adjust the corresponding threshold, then check the records.
Docker Compose
From the repository root, start Elasticsearch, Prometheus, Grafana, and the HUATUO components:
$ docker compose --project-directory ./build/docker up
Once the services start, open Grafana. Both the default administrator username and password are admin. Event and AutoTracing panels show data only when corresponding results have been collected. See Data Sources for data source and dashboard configuration.

Build from Source
Build the Image
From the repository root, build an image containing huatuo-bamai, BPF objects, and tools:
$ docker build --network host -t huatuo/huatuo-bamai:latest .
Run the Collector
Run the image:
$ docker run --privileged --pid=host --cgroupns=host --network=host -v /sys:/sys -v /proc:/proc -v /run:/run huatuo/huatuo-bamai:latest
Alternatively, copy the files from /home/huatuo-bamai in the container and run locally:
$ ./huatuo-bamai --region example --config huatuo-bamai.conf
For long-running deployments, use systemd or Kubernetes as appropriate for your environment.
Configuration
See Node Configuration for all fields, defaults, and conditions for settings to take effect.
HUATUO retrieves Pod and container information through kubelet. Set ports and certificates for your environment. Setting both KubeletAuthorizedPort and KubeletReadOnlyPort to 0 disables this feature.
[Pod]
KubeletClientCertPath = "/etc/kubernetes/pki/apiserver-kubelet-client.crt,/etc/kubernetes/pki/apiserver-kubelet-client.key"
Storage
Metrics are exposed at :19704/metrics; configure Prometheus to scrape and store them. Events and AutoTracing results are written to the enabled storage backends. The following examples configure Elasticsearch and local files:
[Storage.Elasticsearch]
Address = "http://127.0.0.1:9200"
Username = "elastic"
Password = "huatuo-bamai"
Index = "huatuo_bamai"
# tracer's record data
# Path: all but the last element of path for per tracer
# RotationSizeMiB: Maximum size of a record file before rotation
# MaxRotatedFiles: Maximum number of rotated files to retain
[Storage.LocalFile]
Path = "huatuo-local"
RotationSizeMiB = 100
MaxRotatedFiles = 10
Event Thresholds
Adjust the configurable event and AutoTracing thresholds in huatuo-bamai.conf for your workload. Trigger conditions, scope, and defaults vary by collector and should be verified in the target environment.
Resource Limits
In Kubernetes and systemd deployments, kubelet or systemd manages HUATUO’s cgroup by default; HUATUO does not move its own PID. Use --enable-cgroup and the following configuration only when running directly without an external manager:
[Runtime]
StartupCPULimitCores = 0.5
CPULimitCores = 2.0
MemoryLimitMiB = 2048
2 - Deployment
Choose a deployment method for your environment. Settings are described in Node Configuration and API Server Configuration.
2.1 - Container Deployment
Use Docker to run the collector or Compose to start the complete environment. Available image versions are listed in the image registry.
Docker
docker run --detach \
--name huatuo-bamai \
--restart unless-stopped \
--privileged \
--pid=host \
--cgroupns=host \
--network=host \
--cpus=2 \
--memory=2g \
--volume /sys:/sys \
--volume /proc:/proc \
--volume /run:/run \
huatuo/huatuo-bamai:latest
Note: The image’s default configuration does not connect to kubelet or Elasticsearch.
Set CPU and memory limits in production to prevent abnormal collection tasks from affecting host workloads. Docker enforces these limits through the container cgroup. Huatuo does not create its own cgroup by default; do not pass --enable-cgroup in Docker deployments.
Use the following commands to verify the limits and inspect actual usage:
docker inspect huatuo-bamai \
--format 'NanoCPUs={{.HostConfig.NanoCpus}} Memory={{.HostConfig.Memory}}'
docker stats huatuo-bamai
These example values are a starting point. Adjust them for node capacity, collection tasks, and peak resource usage.
Docker Compose
Docker Compose provides a complete local environment in which you manage the collector, Elasticsearch, Prometheus, Grafana, and other components.
$ docker compose --project-directory ./build/docker up
See the installation guide to install Docker Compose.
Compose installs Business Charts (volkovlabs-echarts-panel) for the IO
interval overview and profiling label filters. Install this plugin when using an existing Grafana instance.
Continuous profiling in the development stack
From the repository root, start the development stack with ES storage, API authentication,
and Grafana data sources configured:
Fixed credentials are for development only. When changing the ES password in build/docker/.env,
update both service configurations under build/docker/devconf/ and the Grafana ES data source.
The collection script requires Bash, curl, and jq. Container modes also require kubectl,
ip, crictl, an available Kubernetes node on the local host, and access to the gcc:14 image.
IRQ requires python3, taskset, and timeout, without Kubernetes. After startup,
select modes from another terminal at the repository root. Each task runs for 20 seconds:
# Default: profile on-CPU execution in a temporary container
./build/docker/run_test_cpu_profiling.sh
# Profile off-CPU waiting time in a container
./build/docker/run_test_cpu_profiling.sh --offcpu
# Profile host softirq counts
./build/docker/run_test_cpu_profiling.sh --irq
# Run all six modes sequentially
./build/docker/run_test_cpu_profiling.sh --oncpu --offcpu \
--virtual-alloc --physical-alloc --physical-usage --irq
IRQ profiles the host; the other five modes profile containers. The script does not accept
--with-host or --with-container.
Mode flags can be combined in any order; repeated flags have no additional effect. The default is on-CPU.
--virtual-alloc and --physical-alloc observe virtual address space and physical page allocation,
respectively. --physical-usage observes live physical pages tracked during capture, not total process RSS.
Container modes use separate workload Pods. IRQ generates loopback UDP traffic on one allowed CPU
and profiles that CPU, producing one count window with irq_context, irq_type, irq_vector, and
other labels. Node-side sampling limits apply: dropped_samples in raw.json records discarded
samples, so flame graph counts do not represent the total number of interrupts.
Both paths validate raw results and the Grafana flame graph.
Grafana lists the two allocation modes separately under Profile type as
memory:virtual_alloc:bytes:space:bytes and memory:physical_alloc:bytes:space:bytes.
After completion, open the Grafana URL in the output to view the flame graph. The initial login is admin / admin.
Results and diagnostics are saved to the reported output_dir under _output/profiling/run.XXXXXX/.
The temporary container workload is removed on exit; collected results remain queryable.
For label filtering, see View the Flame Graph.
The script targets the default development stack. For custom collection requests, see
Profiling API.
To deploy and benchmark Redis or PostgreSQL and profile the service container:
./build/docker/run_test_redis_profiling.sh
./build/docker/run_test_postgres_profiling.sh
./build/docker/run_test_postgres_profiling.sh --offcpu
./build/docker/run_test_postgres_profiling.sh --oncpu --offcpu
./build/docker/run_test_postgres_profiling.sh --virtual-alloc --physical-alloc --physical-usage
./build/docker/run_test_postgres_profiling.sh --irq
Run make compose-dev-up before these scripts. They require curl, jq, kubectl,
ip, crictl, a Kubernetes node on the local host, and access to its containerd runtime.
They preload missing workload images with crictl. The runtime endpoint defaults to
unix:///run/containerd/containerd.sock; override it with CONTAINER_RUNTIME_ENDPOINT.
They use redis with redislabs/memtier_benchmark, or
ubuntu/postgres:18-26.04_edge with pgbench from postgres:18.7-bookworm.
The host needs no benchmark tools.
Redis runs mixed reads and writes with a 30-second profile. Each PostgreSQL mode profiles for
60 seconds. CPU modes initialize temporary data and run read-only queries; memory modes reconnect
and materialize queries to allocate, touch, and briefly retain memory. Tasks are created through the apiserver;
the scripts stop the benchmark after task completion, then generate the flame graph link.
Success exits with code 0; the JSON output contains the flame graph link in grafana_url and the
results and benchmark log directory in output_dir. Failure exits with a nonzero code and
grafana_url: null. Temporary services, data, and benchmark containers are removed on exit;
the development stack and collected results remain available.
Selecting multiple PostgreSQL modes returns a results array with a separate output_dir and
grafana_url for each trial; any mode failing produces a nonzero exit code.
PostgreSQL --irq keeps pgbench running and generates loopback UDP traffic while profiling host
softirq activity. It requires python3, taskset, and timeout; results include host activity
beyond PostgreSQL on the selected CPU.
Off-CPU uses the same read-only pgbench workload and does not guarantee a particular wait reason.
After the trial, run make compose-dev-down to stop and remove the development stack.
2.2 - Cluster Deployment
Deploy the collector on Kubernetes nodes as a DaemonSet, using either manifests or Helm. The administration machine needs kubectl and access to the target cluster.
1. Deploy with Manifests
1.1 Download the Configuration
curl -L -o huatuo-bamai.conf https://github.com/ccfos/huatuo/raw/main/huatuo-bamai.conf
1.2 Edit the Configuration
Adjust the configuration for your environment, including the storage backend and Pod information source. See the configuration guide.
1.3 Create a ConfigMap
kubectl create configmap huatuo-bamai-config \
--namespace default \
--from-file=./huatuo-bamai.conf \
--dry-run=client -o yaml |
kubectl apply -f -
1.4 Deploy the Collector
Download the DaemonSet manifest:
curl -L -o huatuo-daemonset.yaml \
https://raw.githubusercontent.com/ccfos/huatuo/main/build/huatuo-daemonset.minimal.yaml
Before deploying to production, set resources for the huatuo container to the following baseline:
resources:
limits:
cpu: "2"
memory: 2Gi
requests:
cpu: "2"
memory: 2Gi
Apply the updated manifest:
kubectl apply -f ./huatuo-daemonset.yaml
requests reserve resources for scheduling. The kubelet writes limits to the Pod cgroup to enforce Huatuo’s CPU and memory limits. Huatuo does not create its own cgroup by default, so its processes remain in the kubepods hierarchy and can be reclaimed when containerd restarts or the Pod is deleted.
These values are a starting point. Equal requests and limits give the Pod Guaranteed QoS. [Runtime] takes effect only when --enable-cgroup is explicitly passed; do not pass this flag in Kubernetes deployments.
1.5 Verify the Deployment
kubectl rollout status daemonset/huatuo \
--namespace default \
--timeout=10m
kubectl get pods \
--namespace default \
--selector app=huatuo \
--output wide
kubectl get daemonset huatuo \
--namespace default \
--output jsonpath='{.spec.template.spec.containers[?(@.name=="huatuo")].resources}'
After updating huatuo-bamai.conf, repeat section 1.3 to update the ConfigMap, then trigger a rolling update manually:
kubectl rollout restart daemonset/huatuo --namespace default
2. Deploy with Helm
The Helm chart is in build/charts/.
2.1 Check the Environment
The administration machine needs Helm, kubectl, and access to the target Kubernetes cluster.
(command -v helm || curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash) && helm version
TARGET_CONTEXT="$(kubectl config get-contexts -o name | sed -n '1p')"
kubectl --context "${TARGET_CONTEXT}" get nodes
Confirm that the target nodes are Ready.
2.2 Prepare the Configuration
Follow sections 1.1 and 1.2 to download and edit huatuo-bamai.conf.
2.3 Set Deployment Parameters
Create values-production.yaml:
image:
repository: <registry-accessible-to-all-nodes>/huatuo-bamai
tag: "<pinned-release-version>"
pullPolicy: IfNotPresent
resources:
limits:
cpu: "2"
memory: 2Gi
requests:
cpu: "2"
memory: 2Gi
nodeSelector:
kubernetes.io/os: linux
tolerations:
- operator: Exists
hostPaths:
proc: /proc
sys: /sys
run: /run
var: /var
etc: /etc
data: /var/log/huatuo/huatuo-local
2.4 Validate the Helm Chart
helm lint ./build/charts \
-f ./values-production.yaml \
--set-file config.content=./huatuo-bamai.conf
helm template huatuo ./build/charts \
--namespace huatuo \
-f ./values-production.yaml \
--set-file config.content=./huatuo-bamai.conf \
>/dev/null
2.5 Deploy the Collector
helm upgrade --install huatuo ./build/charts \
--kube-context "${TARGET_CONTEXT}" \
--namespace huatuo \
--create-namespace \
-f ./values-production.yaml \
--set-file config.content=./huatuo-bamai.conf \
--atomic \
--timeout 10m
2.6 Verify the Deployment
helm status huatuo \
--kube-context "${TARGET_CONTEXT}" \
--namespace huatuo
kubectl --context "${TARGET_CONTEXT}" \
--namespace huatuo \
get daemonset,configmap,pod --output wide
kubectl --context "${TARGET_CONTEXT}" \
--namespace huatuo \
rollout status daemonset/huatuo \
--timeout=10m
Inspect the collector logs:
kubectl --context "${TARGET_CONTEXT}" \
--namespace huatuo \
logs \
--selector app.kubernetes.io/name=huatuo \
--prefix \
--tail=100
2.7 Update and Roll Back
After changing the image version or huatuo-bamai.conf, rerun the command in section 2.5.
View the release history and roll back to a specific revision:
helm history huatuo \
--kube-context "${TARGET_CONTEXT}" \
--namespace huatuo
helm rollback huatuo <Revision> \
--kube-context "${TARGET_CONTEXT}" \
--namespace huatuo \
--wait \
--timeout 10m
2.3 - Host Deployment
This guide covers installing HUATUO from a tar archive or RPM and managing it with systemd. Check the resource limits before starting, then verify the service status after installation.
Tar Archive
HUATUO releases provide static Linux tar archives for amd64 and arm64. Each archive contains the huatuo-bamai and huatuo-apiserver binaries, configuration files, and BPF objects.
These commands apply to releases with assets named huatuo-bamai-<version>-static-linux-<arch>.tar.gz. This naming scheme starts with v2.2.0; archives for v2.0.0 and v2.1.0 have different names and cannot use these commands unchanged.
Set HUATUO_VERSION to the target release, such as v2.2.0:
HUATUO_VERSION="<release-version>"
1. Download the Archive
On x86_64 hosts, download the amd64 archive:
wget "https://github.com/ccfos/huatuo/releases/download/${HUATUO_VERSION}/huatuo-bamai-${HUATUO_VERSION}-static-linux-amd64.tar.gz"
On aarch64 hosts, download the arm64 archive:
wget "https://github.com/ccfos/huatuo/releases/download/${HUATUO_VERSION}/huatuo-bamai-${HUATUO_VERSION}-static-linux-arm64.tar.gz"
2. Install the Archive
Create the installation, log, and data directories:
sudo install -d -m 0755 /opt/huatuo-bamai /var/log/huatuo-bamai /var/lib/huatuo-bamai
amd64:
sudo tar -xzf "huatuo-bamai-${HUATUO_VERSION}-static-linux-amd64.tar.gz" --strip-components=1 --no-same-owner -C /opt/huatuo-bamai
arm64:
sudo tar -xzf "huatuo-bamai-${HUATUO_VERSION}-static-linux-arm64.tar.gz" --strip-components=1 --no-same-owner -C /opt/huatuo-bamai
3. Install Service Units
Download the service units from the corresponding source release:
sudo wget -O /etc/systemd/system/huatuo-bamai.service "https://raw.githubusercontent.com/ccfos/huatuo/${HUATUO_VERSION}/build/rpm/huatuo-bamai.service"
sudo wget -O /etc/systemd/system/huatuo-apiserver.service "https://raw.githubusercontent.com/ccfos/huatuo/${HUATUO_VERSION}/build/rpm/huatuo-apiserver.service"
4. Edit the Configuration
Edit /opt/huatuo-bamai/conf/huatuo-bamai.conf and /opt/huatuo-bamai/conf/huatuo-apiserver.conf for your environment. See the huatuo-bamai configuration and huatuo-apiserver configuration for field details.
Set resource limits with CPUQuota, MemoryMax, and TasksMax in the service unit. Configure [Runtime] only when running directly with --enable-cgroup.
5. Reload Service Configuration
Reload the systemd configuration:
sudo systemctl daemon-reload
6. Start the Services
Start the services and enable them at boot:
sudo systemctl enable --now huatuo-bamai huatuo-apiserver
RPM Package
The OpenCloudOS repository provides HUATUO v2.1.0 RPM packages for x86_64 and aarch64. These packages install the HUATUO files and systemd service units.
1. Download the RPM
Download the package for your host architecture:
x86_64:
wget https://mirrors.opencloudos.tech/epol/9/Everything/x86_64/os/Packages/huatuo-bamai-2.1.0-2.oc9.x86_64.rpm
aarch64:
wget https://mirrors.opencloudos.tech/epol/9/Everything/aarch64/os/Packages/huatuo-bamai-2.1.0-2.oc9.aarch64.rpm
2. Install the RPM
x86_64:
sudo dnf install ./huatuo-bamai-2.1.0-2.oc9.x86_64.rpm
aarch64:
sudo dnf install ./huatuo-bamai-2.1.0-2.oc9.aarch64.rpm
3. Edit the Configuration
Edit /etc/huatuo-bamai/huatuo-bamai.conf for your environment. See the huatuo-bamai configuration for field details.
Set resource limits with CPUQuota, MemoryMax, and TasksMax in the service unit. Configure [Runtime] only when running directly with --enable-cgroup.
4. Start the Service
The RPM installs huatuo-bamai.service. Start the service and enable it at boot:
sudo systemctl enable --now huatuo-bamai
See the RPM installation guide for the full instructions.
Resource Limits and Verification
Systemd manages resource limits and the process lifecycle for huatuo-bamai.service. The service unit does not enable Huatuo’s own cgroup by default. It uses these native settings:
[Service]
CPUAccounting=yes
CPUQuota=200%
MemoryAccounting=yes
MemoryMax=2G
TasksAccounting=yes
TasksMax=32768
KillMode=control-group
CPUQuota=200% allows up to 2 CPU cores; MemoryMax=2G limits service memory. Adjust these values for host capacity, collection tasks, and peak usage. Do not pass --enable-cgroup in systemd deployments, as it moves the process out of the service cgroup.
After starting the service, check its status and cgroup:
systemctl status huatuo-bamai --no-pager
systemd-cgls --unit huatuo-bamai.service
3 - Building from Source
This guide covers container and host builds. Run all commands from the repository root. See go.mod for the required Go version.
When updating from a version with io_health, iolatency, or iocost object names, run make clean, then make gen-build, before make build, make check, or make unit. This prevents stale objects and generated Go ABI files from mixing with the new names.
Container Build
Run the script to build in a container and perform static checks:
$ sh build/build-run-testing-image.sh
Or run the steps separately:
1. Prepare the build environment
$ docker build --network host -t huatuo/huatuo-bamai-dev:latest -f ./Dockerfile.devel .
2. Start the build container
$ docker run -it --pid=host --privileged --cgroupns=host --network=host -v $(pwd):/go/huatuo-bamai huatuo/huatuo-bamai-dev:latest sh
3. Build inside the container
Runtime Image
The following command builds a local runtime image. It does not push the image to a registry:
docker build --network host -t huatuo/huatuo-bamai:latest .
Host Build
Install Dependencies
Ubuntu 24.04:
apt install make git clang libbpf-dev linux-tools-common curl capnproto
Fedora 40:
dnf install make git clang libbpf-devel bpftool curl capnproto capnproto-devel glibc-static
go install mvdan.cc/gofumpt@v0.8.0
go install mvdan.cc/sh/v3/cmd/shfmt@v3.11.0
go install golang.org/x/tools/cmd/goimports@v0.36.0
go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.62.2
go install github.com/vektra/mockery/v2@v2.53.6
go install capnproto.org/go/capnp/v3/capnpc-go@v3.1.0-alpha.2
Build
BPF Debug Build
Set BPF_DEBUG=1 to pass -DDEBUG_BPF to Clang and compile debug code into the BPF object:
$ make BPF_DEBUG=1 # Or regenerate artifacts only: make BPF_DEBUG=1 gen-build
See Debugging for instrumentation, runtime switches, and logs.
4 - Configuration
Choose the configuration reference for your component. Both references cover sections, field meanings, defaults, and conditions for settings to take effect.
4.1 - Node Configuration
1. Overview
huatuo-bamai.conf configures huatuo-bamai’s collection scope, tracing rules, resource limits, storage, and logging.
This document quotes huatuo-bamai.conf from the repository and describes its fields in tables. It distinguishes three kinds of values:
- Built-in defaults: Values supplied by the program when a field is omitted. “Default” below refers to these values.
- Explicit configuration values: Uncommented assignments that override built-in defaults when the file is loaded.
- Commented examples: Assignments prefixed with
#. They are not loaded and may differ from built-in defaults.
You do not need to uncomment a field to use its built-in default. Restart after editing the configuration file manually. For updates through the Node API, see Section 5.1 for when changes take effect.
2. Global blacklist
# Global tracing and metrics configuration.
# Default comments describe built-in values used when a field is omitted.
# Uncommented assignments override those values; commented assignments are
# inactive examples and may differ from the built-in defaults.
#
# - BlackList
# Global blacklist for tracing and metrics.
# Default: [] (empty). The list below explicitly disables these modules.
#
BlackList = ["netdev_hw", "netdev_qdisc", "net_conntrack", "metax_gpu", "ascend_npu", "blk_iostat", "tcp_retransmit", "mthreads_gpu", "mthreads_xid"]
| Field |
Description |
BlackList |
Array of tracer and metric collector names to disable. The built-in default is []. To enable a module, remove its name, satisfy its dependencies and enablement conditions, and restart to register it. |
BlackList and --disable-tracing accept the legacy names io_health, iolatency, iocost, and diskio, mapping them to blk_device_health, blk_iotrace, blk_iocost, and blk_iostat, respectively. Existing configurations continue to disable the same collectors; use the new names in new configurations.
The configuration file explicitly disables these modules:
| Blacklist entry |
Function |
netdev_hw |
Network interface hardware statistics |
netdev_qdisc |
Queue statistics |
net_conntrack |
Connection tracking statistics |
metax_gpu |
Metax GPU metrics |
ascend_npu |
Ascend NPU metrics |
blk_iostat |
Disk I/O metrics |
tcp_retransmit |
TCP retransmission tracing |
mthreads_gpu |
Moore Threads GPU metrics |
mthreads_xid |
Moore Threads GPU XID events |
3. Logging
# Log Configuration
[Log]
# - Level
# The log level for huatuo-bamai: Debug, Info, Warn, Error, Panic.
# Default: Info
#
# - File
# Store logs to where the logging file is. If it is empty, don't write log
# to any file.
# Default: empty
#
# Level = "Info"
# File = ""
| Field |
Description |
Level |
Log level. Default: Info. Options: Debug, Info, Warn, Error, and Panic. Use Info or Warn in production; Debug produces more output and is intended for troubleshooting. |
File |
Log file path. Default: "", which disables file output. Set this field to write logs to a file. |
4. Resource limits
Huatuo does not create its own cgroup by default. These settings take effect only when --enable-cgroup is explicitly supplied. Kubernetes and systemd deployments should use their respective resource controls.
# Runtime limits for the huatuo-bamai process.
[Runtime]
# - StartupCPULimitCores
# CPU limit during startup, in cores.
# Default: 0.5
#
# - CPULimitCores
# CPU limit after startup, in cores.
# Default: 2.0
#
# - MemoryLimitMiB
# Memory limit in MiB.
# Default: 2048
#
# StartupCPULimitCores = 0.5
# CPULimitCores = 2.0
# MemoryLimitMiB = 2048
| Field |
Description |
StartupCPULimitCores |
CPU limit during initialization. Default: 0.5 cores. |
CPULimitCores |
CPU limit after startup. Default: 2.0 cores. |
MemoryLimitMiB |
Process memory limit. Default: 2048 MiB. |
5. HTTP service
The HTTP service provides configuration updates, on-demand operation management, and event subscriptions.
# HTTP server configuration.
[HTTPServer]
# - ListenAddress
# Listen address in "host:port" form.
# Default: ":19704"
#
# - MaxEventStreamClients
# Maximum number of concurrent clients allowed to hold an open
# /v1/events/watch SSE connection. Once the limit is reached, new requests
# are rejected with HTTP 429 until an existing client disconnects.
# Default: 100
#
# - EventStreamKeepAliveIntervalSeconds
# Interval in seconds at which the server sends an SSE comment ping to each
# connected client. The ping keeps the connection alive through load
# balancers and proxies that would otherwise time out idle connections.
# Default: 30
#
# ListenAddress = ":19704"
# MaxEventStreamClients = 100
# EventStreamKeepAliveIntervalSeconds = 30
[HTTPServer.Auth]
# Shared service credential used by huatuo-apiserver.
# Default: "" (invalid). Replace the placeholder before starting.
BearerToken = "REPLACE_WITH_RANDOM_HEX"
| Field |
Description |
ListenAddress |
Listen address in host:port format. Default: ":19704". An empty host listens on all interfaces. |
MaxEventStreamClients |
Maximum concurrent connections to POST /v1/events/watch. Default: 100; must be a positive integer. New connections receive HTTP 429 when the limit is reached. |
EventStreamKeepAliveIntervalSeconds |
SSE comment heartbeat interval in seconds. Default: 30; must be a positive integer. Set it below the upstream proxy’s idle timeout. |
Auth.BearerToken |
Service authentication credential. The built-in default is ""; a nonempty value without whitespace is required. It must match the Node credential configured in huatuo-apiserver. Replace the placeholder before deployment. |
Configuration updates, Operations, and event subscriptions require Authorization: Bearer <token>. /readyz, metrics, version information, and GET /openapi.json remain public. Retrieve the complete API definition through GET /openapi.json.
5.1 Update configuration through the API
PUT /v1/config accepts a nonempty config object. Keys use dot-separated paths matching the TOML structure; values retain their JSON types:
curl -i -X PUT 'http://127.0.0.1:19704/v1/config' \
-H 'Authorization: Bearer REPLACE_WITH_RANDOM_HEX' \
-H 'Content-Type: application/json' \
--data '{
"config": {
"BlackList": ["dropwatch", "netdev_hw"],
"Runtime.CPULimitCores": 1.5,
"Runtime.MemoryLimitMiB": 1024
}
}'
A successful update returns 204 No Content. The Node Agent validates the complete configuration, atomically replaces the configuration file, and then updates the in-memory configuration. If validation or persistence fails, it continues using the previous configuration.
Unknown keys, invalid value types, and empty update objects return 400 Bad Request.
Components that read configuration dynamically can use the new values without restarting. Settings read only at startup, such as HTTP listening and authentication, storage initialization, and cgroup settings, are written to the file but take effect only after restarting huatuo-bamai.
5.2 On-demand task management (Operations)
Operations provides shared management for Profiling and Tracing on a node, including concurrency limits, launch, stop, finalization, and terminal record retention. On-demand Tracing currently has no executor: new start requests that pass parameter validation return 501 without creating an operation.
# Shared lifecycle policy for on-demand operations.
[Operations]
# MaxConcurrent = 10
# LaunchTimeoutSeconds = 10
# StopGracePeriodSeconds = 5
# FinalizationTimeoutSeconds = 30
# TerminalRetentionPeriodSeconds = 600
| Field |
Description |
MaxConcurrent |
Limit on unfinished operations, shared by Profiling and Tracing. Default: 10; must be a positive integer. New operations are rejected rather than queued when the limit is reached. |
LaunchTimeoutSeconds |
Operation executor launch timeout in seconds. Default: 10; must be a positive integer. |
StopGracePeriodSeconds |
Wait deadline when stopping an operation, in seconds. Default: 5; must be a positive integer. |
FinalizationTimeoutSeconds |
Executor finalization timeout in seconds. Default: 30; must be a positive integer. |
TerminalRetentionPeriodSeconds |
Time to retain an operation’s terminal record in node memory after completion, in seconds. Default: 600; must be a positive integer. The record is no longer available through the operation API after it expires. |
| Endpoint |
Purpose |
POST /v1/operations |
Create an operation. Returns 202 for a new operation, 200 for an existing idempotent operation, or 429 when the concurrency limit is reached. |
GET /v1/operations/{request_id} |
Query operation status. Returns 404 if the record does not exist or has expired. |
POST /v1/operations/{request_id}/stop |
Request an operation to stop. Returns 202 when the stop request is accepted, or 200 if the operation is already stopping or terminal. |
Start requests select profiling or tracing through kind and specify the execution duration through duration_seconds. The launch, stop, and finalization timeouts apply to their respective stages; they do not replace the execution duration.
5.3 Profiling
Start profiling through POST /v1/operations. Provide request_id, duration_seconds, and scope; set kind = "profiling"; and include type, language, and mode in spec. Container scope also requires container_id. Use the shared operation endpoints in Section 5.2 to query or stop the operation.
# Node-local on-demand profiling settings.
[Profiling]
# AggregationIntervalSeconds = 10
# MaxConcurrentProcesses = 10
# CommandOutputLimitBytes = 65536
# Java uses bin/asprof and lib/libasyncProfiler.so; Python uses py-spy.
# ToolDir defaults to ""; the path below is an example.
# ToolDir = "/opt/huatuo/tools"
| Field |
Description |
AggregationIntervalSeconds |
Sample aggregation interval in seconds. Default: 10; must be a positive integer. The effective interval does not exceed the request duration. Python uses the entire request duration as its aggregation window. |
MaxConcurrentProcesses |
Maximum concurrent profiling subprocesses within one profiler execution. Default: 10; must be a nonnegative integer. 0 means unlimited. Total operation concurrency remains subject to Operations.MaxConcurrent. |
CommandOutputLimitBytes |
Maximum profiler stdout bytes retained by the Node. Default: 65536; must be a positive integer. When exceeded, the most recent output is retained for error diagnostics. This setting does not limit profiling result size. |
ToolDir |
Root directory for external profiling tools. The built-in default is ""; /opt/huatuo/tools is an inactive commented example. Passed to the profiler’s --tool-path. |
Java uses bin/asprof and lib/libasyncProfiler.so under ToolDir; Python uses py-spy. Native profiling does not require these external tools. Only tools required by the requested language are checked. Missing tools cause the request to be rejected without creating an operation.
Operations and Profiling settings are read at service startup. Changes made through the API require restarting huatuo-bamai to take effect.
6. Data storage
6.1 Elasticsearch/OpenSearch
# Storage configuration
[Storage]
# Elasticsearch and OpenSearch Storage
#
# Store the tracing and events data of linux kernel to ES/OS.
#
# - Address
# Port 9200 is commonly used for Elasticsearch/OpenSearch HTTP APIs.
# e.g.
# http://127.0.0.1:9200
# https://127.0.0.1:9200
#
# Address, Username, and Password must be either all empty (disabled) or
# all configured (enabled). Partial connection settings are invalid.
#
# - Index
# Elasticsearch or OpenSearch index, a logical namespace that holds a collection of
# documents for huatuo-bamai.
# Default: huatuo_bamai
#
# - Username
# - Password
# There are no default connection credentials.
#
[Storage.Elasticsearch]
# Address = "http://127.0.0.1:9200"
# Index = "huatuo_bamai"
# Username = "elastic"
# Password = "REPLACE_WITH_PASSWORD"
| Field |
Description |
Address |
Elasticsearch/OpenSearch service address, supporting HTTP/HTTPS. Empty by default. This backend is disabled when Address, Username, and Password are all empty. To enable it, configure all three; a partial configuration prevents startup. |
Index |
Index for tracing and event data. Default: huatuo_bamai. |
Username |
Basic Auth username. Empty by default. |
Password |
Basic Auth password. Empty by default. Use a strong password and enable HTTPS in production. |
6.2 Local files
# LocalFile Storage
#
# Store data to local directory for troubleshooting on the host machine.
#
# - Path
# The directory for storing data. If the Path is empty, LocalFile will be disabled.
# Default: "huatuo-local"
#
# - RotationSizeMiB
# The maximum size in MiB of a record file before it gets rotated
# for per linux kernel tracer.
# Default: 100 MiB
#
# - MaxRotatedFiles
# The maximum number of old log files to retain for per tracer.
# Default: 10
#
[Storage.LocalFile]
# Path = "huatuo-local"
# RotationSizeMiB = 100
# MaxRotatedFiles = 10
| Field |
Description |
Path |
Local data directory. Default: huatuo-local. An empty string disables local file storage. Use an absolute path when enabled. |
RotationSizeMiB |
Rotation size for each tracer’s record file, in MiB. Default: 100. |
MaxRotatedFiles |
Maximum historical files retained per tracer. Default: 10. The oldest files are deleted when this limit is exceeded. |
7. Automatic tracing
Automatic tracing triggers performance collection based on resource usage and configured thresholds.
AutoTracing.CPUIdle.Tool and AutoTracing.CPUSys.Tool independently accept perf or profiler, defaulting to perf. Empty strings and other values are invalid. Updates affect the next collection; running collections retain their selected tool.
perf: preserves inline event flamedata; visualization does not require huatuo-apiserver.
profiler: uses native CPU on-CPU collection, stores profiles separately in Elasticsearch, and displays them through the huatuo-apiserver Pyroscope-compatible interface. Enable bamai Elasticsearch storage and do not use --disable-storage. Events retain trigger metrics with flamedata: null.
Both tools use RunTracingToolTimeout as the collection duration in seconds. Failures do not switch tools.
To view profiler results, open the Continuous Profiling host or container dashboard for the target. Set Task ID to the event tracer_id, set type to process_cpu:cpu:nanoseconds:cpu:nanoseconds, and select a time range covering collection. See View the Flame Graph for dashboard access and interactions.
7.1 Container CPU spikes
# cpuidle
#
# For a high cpu usage all of a sudden in containers.
#
# - UserThreshold
# User CPU usage must exceed this threshold and its increase must exceed
# DeltaUserThreshold.
# Default: 75%
#
# - SysThreshold
# System CPU usage must exceed this threshold and its increase must exceed
# DeltaSysThreshold.
# Default: 45%
#
# - UsageThreshold
# Total CPU usage (system + user) must exceed this threshold and
# its increase must exceed DeltaUsageThreshold.
# Default: 90%
#
# - DeltaUserThreshold
# User CPU usage increase from the previous sample, in percentage points.
# Default: 45 percentage points
#
# - DeltaSysThreshold
# System CPU usage increase from the previous sample, in percentage points.
# Default: 20 percentage points
#
# - DeltaUsageThreshold
# Total CPU usage increase from the previous sample, in percentage points.
# Default: 55 percentage points
#
# - Interval
# The sample interval of the cpu usage for all containers.
# Default: 10s
#
# - IntervalTracing
# Time since last run. Avoid frequently executing this tracing to prevent
# damage to the system.
# Default: 1800s
#
# - RunTracingToolTimeout
# The executing time of this tracing program.
# Default: 10s
#
# NOTE:
# Running this performance tool, when:
# 1. UserThreshold and DeltaUserThreshold are true, or
# 2. SysThreshold and DeltaSysThreshold are true, or
# 3. UsageThreshold and DeltaUsageThreshold
#
[AutoTracing.CPUIdle]
# Tool: perf (default) or profiler. Both use RunTracingToolTimeout.
# Tool = "perf"
# UserThreshold = 75
# SysThreshold = 45
# UsageThreshold = 90
# DeltaUserThreshold = 45
# DeltaSysThreshold = 20
# DeltaUsageThreshold = 55
# Interval = 10
# IntervalTracing = 1800
# RunTracingToolTimeout = 10
| Field |
Description |
UserThreshold |
User-mode CPU utilization threshold. Default: 75%. |
SysThreshold |
System-mode CPU utilization threshold. Default: 45%. |
UsageThreshold |
Total CPU utilization threshold. Default: 90%. |
DeltaUserThreshold |
User-mode CPU utilization increase over the previous sample. Default: 45 percentage points. |
DeltaSysThreshold |
System-mode CPU utilization increase over the previous sample. Default: 20 percentage points. |
DeltaUsageThreshold |
Total CPU utilization increase over the previous sample. Default: 55 percentage points. |
Interval |
Container CPU utilization sampling interval in seconds. Default: 10. |
IntervalTracing |
Minimum interval between automatic traces, in seconds. Default: 1800 (30 minutes). |
RunTracingToolTimeout |
Collection duration in seconds. Default: 10. |
Trigger conditions: Once the tracing interval has elapsed, a container becomes a tracing candidate if both utilization and its increase strictly exceed the corresponding thresholds in any one of these pairs:
UserThreshold and DeltaUserThreshold;
SysThreshold and DeltaSysThreshold;
UsageThreshold and DeltaUsageThreshold.
Container filtering: Use the Included and Excluded rule arrays to control the monitoring scope.
# CPUIdle-specific filtering rules (array form, supports multiple rules)
# Use [[double-bracket]] syntax to define each rule entry.
#
# Supported fields:
# - container_namespace: namespace label of the container
# - container_hostname: hostname of the container
# - container_qos: qos level (guaranteed, burstable, besteffort)
#
# Pattern uses regex matching.
#
# Logic:
# - No rules: all containers are monitored
# - Excluded only: blacklist, matched containers are skipped
# - Included only: whitelist, only matched containers are monitored
# - Both: containers must match Included AND not match Excluded
#
# Examples:
# # Blacklist: ignore besteffort containers
# [[AutoTracing.CPUIdle.Filter.Excluded]]
# Field = "container_qos"
# Pattern = "besteffort"
#
# # Whitelist: only monitor application namespaces
# [[AutoTracing.CPUIdle.Filter.Included]]
# Field = "container_namespace"
# Pattern = "^application-"
#
# # Combine: monitor application namespaces except kube-system
# [[AutoTracing.CPUIdle.Filter.Included]]
# Field = "container_namespace"
# Pattern = ".*"
# [[AutoTracing.CPUIdle.Filter.Excluded]]
# Field = "container_namespace"
# Pattern = "^kube-system$"
| Field |
Description |
Filter |
Container filtering rules. No rules are configured by default, so all containers are monitored. Define rules using TOML arrays of tables ([[...]]), each containing a target field Field and a regular expression Pattern. |
Excluded only: Exclude matching containers.
Included only: Monitor only matching containers.
- Both: Monitor containers that match
Included and do not match Excluded.
7.2 Host CPU bursts
# cpusys
#
# For a high system cpu usage all of a sudden on host machine.
#
# - SysThreshold
# System CPU usage must exceed this threshold and its increase must exceed
# DeltaSysThreshold.
# Default: 45%
#
# - DeltaSysThreshold
# System CPU usage increase from the previous sample, in percentage points.
# Default: 20 percentage points
#
# - Interval
# The sample interval of the cpu usage for host machine.
# Default: 10s
#
# - IntervalTracing
# Minimum time between profiling runs.
# Default: 1800s
#
# - RunTracingToolTimeout
# The executing time of this tracing program.
# Default: 10s
#
# NOTE:
# Running this performance tool, when:
# SysThreshold and DeltaSysThreshold are true.
#
[AutoTracing.CPUSys]
# Tool: perf (default) or profiler. Both use RunTracingToolTimeout.
# Tool = "perf"
# UserThreshold = 75
# DeltaUserThreshold = 45
# UsageThreshold = 90
# DeltaUsageThreshold = 55
# SysThreshold = 45
# DeltaSysThreshold = 20
# Interval = 10
# IntervalTracing = 1800
# RunTracingToolTimeout = 10
| Field |
Description |
UserThreshold / DeltaUserThreshold |
Host user-mode utilization / increase thresholds. Defaults: 75% / 45 percentage points. |
UsageThreshold / DeltaUsageThreshold |
Host executing-total utilization / increase thresholds. Defaults: 90% / 55 percentage points. |
SysThreshold |
Host system-mode CPU utilization threshold. Default: 45%. |
DeltaSysThreshold |
System-mode CPU utilization increase over the previous sample. Default: 20 percentage points. |
Interval |
Host CPU utilization sampling interval in seconds. Default: 10. |
IntervalTracing |
Minimum interval between traces, in seconds. Default: 1800. |
RunTracingToolTimeout |
Collection duration in seconds. Default: 10. |
Trigger conditions: After the shared cooldown, any system/user/total pair
can trigger profiling when both utilization and its increase strictly exceed
their thresholds. System uses the CPUSys thresholds above. User and total use
CPUSys.UserThreshold/DeltaUserThreshold (75/45) and
CPUSys.UsageThreshold/DeltaUsageThreshold (90/55), independently of CPUIdle.
Utilization is percent and delta is percentage points. All three groups use
strict threshold comparisons; zero is a normal threshold, not a disable switch.
All three host conditions share the CPUSys capture cooldown.
7.3 Container D-state load
This tracer requires the cgroup v1 load statistics interface and is skipped on cgroup v2.
# dload
#
# linux tasks D state profiling for containers.
#
# - ThresholdLoad
# D-state load average threshold for each container. Profiling is triggered
# when D-state load exceeds this value and IntervalTracing has elapsed.
# Default: 5
#
# - Interval
# The sample interval of the load for all containers.
# Default: 10s
#
# - IntervalTracing
# Time since last run. Avoid frequently executing this tracing to prevent
# damage to the system.
# Default: 1800s
#
# - EnableDebug
# Bypass ThresholdLoad and IntervalTracing; include task stacks regardless
# of task state. For debugging only.
# Default: false
#
[AutoTracing.Dload]
# ThresholdLoad = 5
# Interval = 10
# IntervalTracing = 1800
# EnableDebug = false
| Field |
Description |
ThresholdLoad |
Load average threshold for container tasks in D state (uninterruptible sleep). Default: 5. Tracing starts when D-state load strictly exceeds this value and IntervalTracing has elapsed. The decision does not use total load, which includes runnable tasks. |
Interval |
Container load sampling interval in seconds. Default: 10. |
IntervalTracing |
Minimum interval between automatic traces, in seconds. Default: 1800 (30 minutes). |
EnableDebug |
Debug switch. Default: false. Bypasses load threshold and minimum tracing interval checks and attempts to collect stacks for tasks in all states in the container and on the host. May increase overhead; use only for debugging. |
# iotracing
#
# io profiling for containers.
#
# - WbpsThreshold
# NVMe write throughput threshold in MiB/s. Both throughput and utilization
# must exceed their thresholds for two consecutive samples.
# Default: 1500 MiB/s
#
# - RbpsThreshold
# NVMe read throughput threshold in MiB/s. Both throughput and utilization
# must exceed their thresholds for two consecutive samples.
# Default: 2000 MiB/s
#
# - UtilThreshold
# Disk busy time percentage. Two consecutive samples must exceed this value.
# NVMe devices also require RbpsThreshold or WbpsThreshold to be exceeded.
# Default: 90%
#
# - AwaitThreshold
# Average read or write IO wait time in ms. Two consecutive samples exceeding
# this threshold trigger tracing independently of utilization and throughput.
# Default: 100ms
#
# - RunTracingToolTimeout
# The executing time of this tracing tool.
# Default: 10s
#
# - MaxProcDump
# The number of processes displayed by iotracing tool.
# Default: 10
#
# - MaxFilesPerProcDump
# The number of files per process displayed by iotracing tool.
# Default: 5
#
[AutoTracing.IOTracing]
# WbpsThreshold = 1500
# RbpsThreshold = 2000
# UtilThreshold = 90
# AwaitThreshold = 100
# RunTracingToolTimeout = 10
# MaxProcDump = 10
# MaxFilesPerProcDump = 5
| Field |
Description |
WbpsThreshold |
NVMe write throughput threshold in MiB/s. Default: 1500. Write throughput and disk utilization must both exceed their thresholds for two consecutive samples. |
RbpsThreshold |
NVMe read throughput threshold in MiB/s. Default: 2000. Read throughput and disk utilization must both exceed their thresholds for two consecutive samples. |
UtilThreshold |
Disk busy-time percentage threshold. Default: 90. Non-NVMe devices trigger tracing after two consecutive samples exceed it; NVMe devices must also meet the read or write throughput condition. |
AwaitThreshold |
Average read or write I/O wait time threshold in ms. Default: 100. Read wait or write wait exceeding this threshold for two consecutive samples triggers tracing independently of utilization and throughput. |
RunTracingToolTimeout |
I/O tracing tool execution timeout in seconds. Default: 10. |
MaxProcDump |
Maximum processes shown in I/O tracing results. Default: 10. |
MaxFilesPerProcDump |
Maximum files shown per process. Default: 5. |
7.5 Host anonymous memory spikes
This module detects host anonymous memory spikes, records process information ranked by RSS, and attempts runtime memory snapshots. Anonymous memory is the sum of Active(anon) and Inactive(anon) in /proc/meminfo. Once the history window is full, both the growth ratio and the share of total memory must reach their thresholds, and the tracing interval must have elapsed, before a report is emitted.
# memory burst
#
# Detect host anonymous-memory bursts and capture snapshots of top RSS processes.
#
# - Interval
# The sample interval of Active(anon) + Inactive(anon) from /proc/meminfo.
# Default: 10s
#
# - DeltaMemoryBurst
# Anonymous-memory growth relative to the oldest sample in the full history
# window. 100% means doubling, e.g., from 200 MiB to 400 MiB.
# Default: 100%
#
# - DeltaAnonThreshold
# Active(anon) + Inactive(anon) as a percentage of host MemTotal.
# Both this threshold and DeltaMemoryBurst must be reached to report a burst.
# Default: 70%
#
# - IntervalTracing
# Time since last run. Avoid frequently executing this tracing
# to prevent damage to the system.
# Default: 1800s
#
# - DumpProcessMaxNum
# Maximum RSS-ranked processes retained in the event.
# Runtime snapshots follow this ranking, capped at 3 processes.
# Default: 10
#
[AutoTracing.MemoryBurst]
# DeltaMemoryBurst = 100
# DeltaAnonThreshold = 70
# Interval = 10
# IntervalTracing = 1800
# DumpProcessMaxNum = 10
| Field |
Description |
DeltaMemoryBurst |
Anonymous memory growth threshold relative to the oldest sample in the history window. Default: 100%, meaning at least a doubling, for example from 200 MiB to 400 MiB. |
DeltaAnonThreshold |
Anonymous memory as a percentage of host MemTotal. Default: 70%; range: 0–100. This is a share of total memory, not a growth ratio. |
Interval |
Host anonymous memory sampling interval in seconds. Default: 10. |
IntervalTracing |
Minimum interval between memory burst traces, in seconds. Default: 1800 (30 minutes). |
DumpProcessMaxNum |
Maximum processes retained in descending RSS order. Default: 10. Runtime snapshots are attempted for the first min(DumpProcessMaxNum, 3) processes; values above 3 only increase the ranking size. |
For snapshot support, capture budgets, and output truncation, see Automatic Tracing Fields.
7.6 Container memory threshold snapshots
Attempts to capture a Go, HotSpot, or CPython runtime snapshot when container memory meets the trigger conditions. Enabled by default; add memory_threshold_snapshot to the global BlackList and restart the huatuo-bamai service to disable it. Runtime support is experimental and requires validation on the target version. Capture is not guaranteed to finish before OOM.
# Capture Go/Java/Python snapshots under container memory pressure.
# Add memory_threshold_snapshot to the global BlackList and restart to disable it.
# v1 uses a usage threshold; v2 checks usage after native high/max events.
# Registration and hard-limit changes also trigger a usage check.
# memory.high is never changed; v2 cannot notify at arbitrary percentages.
# IntervalTracing is the node-wide minimum interval in seconds after each
# successful or failed capture attempt.
# RunTracingToolTimeout is the capture timeout in seconds for all runtimes.
# Timeouts cannot interrupt synchronous syscalls; capture may delay shutdown.
[AutoTracing.MemoryThresholdSnapshot]
# ThresholdPercent = 90
# IntervalTracing = 300
# RunTracingToolTimeout = 2
# MaxMemoryObjectEntries = 10
| Field |
Description |
ThresholdPercent |
Container memory usage as a percentage of its limit. Default: 90; range: 1–100. Trigger behavior depends on the cgroup version, as described below. |
IntervalTracing |
Node-wide minimum interval after a successful or failed capture attempt finishes, in seconds. Default: 300; must be positive. |
RunTracingToolTimeout |
Runtime capture timeout in seconds. Default: 2; must be positive. Cancellation is cooperative, excludes runtime identification and storage time, and cannot interrupt synchronous system calls. It is not an upper bound on the entire operation. |
MaxMemoryObjectEntries |
Maximum ranked memory object entries retained per snapshot. Default: 10; range: 1–100. Final JSON output is limited to 512 KiB and is trimmed if it exceeds this limit. |
Trigger conditions: cgroup v1 registers a memory threshold corresponding to the configured percentage. cgroup v2 checks the current usage-to-limit ratio after high or max events; it does not set memory.high and cannot guarantee notification at exactly the configured percentage. Both versions check usage at registration and when the hard limit changes.
Requirements: Linux, memory cgroups, an enabled Pod manager, kubelet metadata, host PID/procfs/cgroup views, kernel BTF, and permission to use BPF and access target process memory. --procfs-prefix does not redirect process memory reads for snapshots.
Monitoring covers running regular containers and restartable init sidecars. Each container requires its own memory cgroup. Up to 4096 containers can be monitored. Registration failures and invalidated watches are not retried automatically; check the logs, fix the cause, and restart the huatuo-bamai service.
7.7 Interrupt utilization anomalies
This module detects per-CPU irq+softirq utilization anomalies and invokes irqtracing to collect softirq source and victim call stacks. IRQ results use profiling storage, which requires Elasticsearch. An operation succeeds only after its window is queryable and its publication marker is saved. LocalFile alone cannot store these results.
# irqtracing
#
# Detect per-cpu irq+softirq utilization spikes. When enough cpus rise at
# the same time (see Rules), an eBPF program is attached for
# RunTracingToolTimeout seconds to capture the softirq source/victim stacks
# and a flame graph.
#
# - Interval
# The sample interval of /proc/stat per-cpu irq+softirq utilization.
# Default: 2s
#
# - RunTracingToolTimeout
# The executing time of this tracing program.
# Default: 3s
#
# - IntervalTracing
# Time since last run. Avoid frequently executing this tracing to prevent
# damage to the system.
# Default: 300s
#
# - MaxEventsPerSecond
# Maximum source and victim stack samples collected per second on the
# traced CPU. The budget is divided between softirq raise and entry probes.
# Default: 1000
#
# - Rules
# Trigger conditions. Evaluated in order; the first match wins.
#
# Spike rule: fires when >= MinCPUs cpus simultaneously rise by >=
# DeltaUsageThreshold percentage points and >= RelativeIncreaseThreshold%
# relative to the previous sample.
#
# Sustained rule: fires when a single CPU's irq+softirq util stays >=
# UsageThreshold for SustainedIntervals consecutive samples.
#
[AutoTracing.IRQTracing]
# Interval = 2
# RunTracingToolTimeout = 3
# IntervalTracing = 300
# MaxEventsPerSecond = 1000
# MinCPUs = 3
# DeltaUsageThreshold = 20
# RelativeIncreaseThreshold = 30
# SustainedIntervals = 10
# UsageThreshold = 80
| Field |
Description |
Interval |
Per-CPU irq+softirq utilization sampling interval in seconds, using /proc/stat. Default: 2. |
RunTracingToolTimeout |
Duration of one irqtracing capture in seconds. Default: 3. |
IntervalTracing |
Minimum interval between triggers, in seconds. Default: 300. |
MaxEventsPerSecond |
Combined limit on source and victim stack samples per second across the traced CPUs. Default: 1000; range: 2–8589934590. The quota is divided as evenly as possible between softirq_raise and softirq_entry, with 500 samples per second each by default. |
MinCPUs, DeltaUsageThreshold, and RelativeIncreaseThreshold |
Control the rule for irq+softirq utilization spikes across multiple CPUs. The thresholds specify the increase in percentage points and the percentage increase relative to the previous sample. |
SustainedIntervals and UsageThreshold |
Set the consecutive sample count and utilization threshold for sustained high irq+softirq utilization on a single CPU. |
7.8 SchedBlame CPU Contention Attribution
SchedBlame estimates external CPU contention for selected container CPU
cgroups and emits sched-blame-external events when the current one-second
ratio exceeds the target’s adaptive historical threshold.
[AutoTracing.SchedBlame]
# TargetContainerScope = "normal"
# TargetQos = []
# HighlightContainer = ""
# SliceDropPercent = 0
# ExternalAnomalyK = 1.0
# SliceBatchSize = 128
# PerfEventPerCPUBufferBytes = 524288
# PerfEventWatermarkBytes = 8192
# PerfEventQueueRecords = 8192
# PollIntervalMs = 100
# ExternalRatioDebugFile = ""
- TargetContainerScope:
normal selects normal application containers;
all selects every discovered container. Default normal.
- TargetQos: Optional candidate QoS filter. Values are case-insensitive
guaranteed, burstable, or besteffort; an empty list accepts all QoS
classes. Default [].
- HighlightContainer: Optional hostname, full container ID, or unique ID
prefix for one target’s debug log, ratio CSV, and SuperMonitor comparison.
Default empty.
- SliceDropPercent: Percentage of completed scheduler slices discarded
before transport. Valid range
0..99; default 0.
- ExternalAnomalyK: Nonnegative multiplier applied to the target’s
historical P99 external-contention ratio. Default
1.0.
- SliceBatchSize: Maximum slices per perf record. Valid range
1..128;
default 128.
- PerfEventPerCPUBufferBytes: Requested perf-ring data capacity per CPU.
Default
524288.
- PerfEventWatermarkBytes: Positive reader wakeup watermark, smaller than
the effective per-CPU ring capacity. Default
8192.
- PerfEventQueueRecords: Shared decoded-record queue capacity. Default
8192.
- PollIntervalMs: Interval for bounded queue draining and evaluation
checks. Valid range
1..1000; default 100.
- ExternalRatioDebugFile: Optional CSV path for per-target one-second
ratio diagnostics. Default empty. See SchedBlame Analysis
for interactive charts and SuperMonitor comparisons.
7.9 Known issue labeling
# Autotracing configuration.
#
# - IssuesList
# Known issue filters for autotracing.
#
[AutoTracing]
IssuesList = []
| Field |
Description |
IssuesList |
Known issue filter in the form [["issue name", "regex"], ...]. Matching captured stacks are labeled with the corresponding issue name. Default: []. Currently used by dload tracing. Example: IssuesList = [["known_issue1", "softlockup"], ["known_issue2", "alloc_pages.*failed"]]. |
8. Event tracing
This section configures collection conditions for scheduling, memory reclaim, network, and hardware events.
8.1 Scheduler tick intervals
# scheduler tick interval
#
# Trace long scheduler tick intervals.
#
# - IntervalThreshold
# When the scheduler tick interval reaches the threshold, huatuo-bamai
# will collect kernel context.
# Default: 10000000 in nanoseconds, 10ms
#
[EventTracing.SchedTick]
# IntervalThreshold = 10000000
| Field |
Description |
IntervalThreshold |
Scheduler tick interval threshold in nanoseconds. Default: 10000000 (10 ms). An event is collected when the threshold is reached. An unusually long tick interval can indicate a CPU stall, but does not by itself prove that softirqs were disabled. |
8.2 Memory reclaim blocking
# memreclaim
#
# The memory reclaim may block the process, if one process is blocked
# for a long time, reporting the events to userspace.
#
# - BlockedThreshold
# The blocked time when memory reclaiming.
# Default: 900000000ns, 900ms
#
[EventTracing.MemoryReclaim]
# BlockedThreshold = 900000000
| Field |
Description |
BlockedThreshold |
Memory reclaim blocking threshold in nanoseconds. Default: 900000000 (900 ms). An event is reported with context when a process is blocked by memory reclaim for longer than this threshold. |
8.3 Network receive latency
# networking rx latency
#
# linux net stack rx latency for every tcp skbs.
#
# - Driver2NetRx
# The latency from driver to net rx, e.g., netif_receive_skb.
# Default: 5ms
#
# - Driver2TCP
# The latency from driver to tcp rx, e.g., tcp_v4_rcv.
# Default: 10ms
#
# - Driver2Userspace
# The latency from driver to userspace copy data, e.g., skb_copy_datagram_iovec.
# Default: 115ms
#
# - ExcludedContainerQos
# Blacklist: skip containers whose qos level matches any entry in this list.
# Values: "guaranteed", "burstable", "besteffort" (case-insensitive).
# Default: [].
#
# - ExcludedHostNetnamespace
# Don't care the skbs, packets in the host net namespace.
# Default: true
#
[EventTracing.NetRxLatency]
# Driver2NetRx = 5
# Driver2TCP = 10
# Driver2Userspace = 115
# ExcludedContainerQos = []
ExcludedContainerQos = ["besteffort"]
# ExcludedHostNetnamespace = true
| Field |
Description |
Driver2NetRx |
Latency threshold from the driver to network-layer reception, in milliseconds. Default: 5, for example the latency to netif_receive_skb. |
Driver2TCP |
Latency threshold from the driver to TCP stack reception, in milliseconds. Default: 10, for example the latency to tcp_v4_rcv. |
Driver2Userspace |
Latency threshold from the driver to the userspace data copy, in milliseconds. Default: 115, for example the latency to skb_copy_datagram_iovec. |
ExcludedContainerQos |
Container QoS classes to exclude. The built-in default is []; the configuration file explicitly sets ["besteffort"]. Supports guaranteed, burstable, and besteffort, case-insensitively. |
ExcludedHostNetnamespace |
Whether to exclude packet latency in the host network namespace. Default: true. |
8.4 Network interface events
# netdev events
#
# monitor the net device events.
#
# - DeviceList
# Full-match regex patterns for the net devices we take care of.
# Literal names such as "eth0" keep exact-match behavior.
# Default: [] is empty, meaning no devices.
#
[EventTracing.Netdev]
DeviceList = ["eth0", "eth1", "bond4", "lo"]
| Field |
Description |
DeviceList |
Full-match regular expressions for interfaces whose events are monitored. The built-in default is [], meaning no devices are monitored. The configuration file explicitly sets ["eth0", "eth1", "bond4", "lo"]. Literal names such as "eth0" match exactly; patterns such as "bond[0-9]+" can match multiple interfaces. |
8.5 Packet drops
# dropwatch
#
# monitor packets dropped events in the Linux kernel.
#
# NOT supported (go-pcap limitation):
# icmp, icmp6, igmp, vrrp, ah, esp, pim and other raw IP protocol keywords
# CIDR prefix length notation (e.g. /24) is not supported for subnet masks;
# use dotted-decimal notation instead (e.g. mask 255.255.255.0)
[EventTracing.Dropwatch]
Filter = "tcp"
| Field |
Description |
Filter |
Tcpdump-style filter expression for the standalone dropwatch tracer. Default: "tcp". TCP retransmission correlation uses TCPRetransmit.Filter. |
MaxEventsPerSecond |
Maximum dropwatch events emitted by BPF per second. Default: 100; 0 means unlimited. |
ExcludeContainers |
Reserved container exclusion list. Default: []; currently has no effect. Use EventTracing.IssuesList to suppress drop events by call stack. |
8.6 TCP retransmissions
# TCP retransmission tracing through tcpshark --mode retransmit. When local
# dropwatch correlation is enabled, the embedded collector uses the exact
# EventTracing.TCPRetransmit.Filter expression and does not emit raw drops.
# Tail Loss Probe collection is disabled by default.
# MaxEventsPerSecond limits events emitted by the BPF program; 0 disables
# rate limiting.
[EventTracing.TCPRetransmit]
# Retransmission filter. Local correlation applies the same expression
# to both inputs. Empty defaults to "tcp" in local mode and passes no
# --filter flag when correlation is disabled.
# Filter = ""
# EnableTLP = false
# EnableDropwatch = false
# MaxEventsPerSecond = 100
| Field |
Description |
EnableTLP |
Whether to collect tcp_send_loss_probe events. Default: false. |
Filter |
TCP retransmission filter expression. With local drop correlation enabled, both inputs use the same normalized expression; an empty value falls back to tcp. With correlation disabled, an empty value omits --filter. Dropwatch.Filter controls only the standalone dropwatch tracer. |
EnableDropwatch |
Whether to correlate retransmissions and drops within tcpshark. Default: false. Remove tcp_retransmit from BlackList; the standalone dropwatch tracer may remain disabled. Correlation uses the same Filter and does not emit raw drop events separately. |
MaxEventsPerSecond |
Maximum TCP retransmission events emitted by BPF per second. Default: 100; 0 means unlimited. In correlation mode, embedded dropwatch uses the same value with an independent rate limit, so each input is limited to 100 events per second by default. Exceeding the limit produces a rate limit hit log. |
8.7 Hardware errors (RAS)
# ras
#
# Hardware error event tracing (RAS: Reliability, Availability, Serviceability).
# Captures MCE, EDAC, ACPI/GHES, PCIe AER, and MCE threshold (THR) events via eBPF.
#
# - MceThrBackoff
# Minimum interval in seconds between consecutive MCE threshold (THR) event saves.
# THR events are fired by the local-APIC threshold interrupt and can storm at high
# frequency; this cooldown prevents flooding storage with redundant records.
# Default: 1800s (30 minutes)
#
[EventTracing.Ras]
# MceThrBackoff = 1800
| Field |
Description |
MceThrBackoff |
Minimum storage interval for MCE threshold interrupt (THR) events, in seconds. Default: 1800 (30 minutes). THR is triggered by a CPU local APIC threshold interrupt, and corrected hardware errors can produce many events. Shorter intervals increase record volume and storage load. |
8.8 Moore Threads GPU XID events
# Mthreads GPU event tracing
#
# Groups all event-tracing knobs that target the Mthreads / MUSA
# GPU stack. New GPU-side tracers should be added under this
# section.
#
# - MthreadsXidLevel
# Minimum XID severity level that the mthreads_xid tracer will
# report. Anything strictly below this threshold is silently
# dropped. The tracer polls /proc/driver/musa/gpu<idx>/event_report
# every 1s. Valid values:
# "" — disabled; no event_report polling is processed
# "notify" — report all severities (most verbose)
# "warning" — drop notify-level events
# "fatal" — only report fatal events (quietest)
# Default: "" (disabled)
#
[EventTracing.MthreadsGPU]
# Example severity; leaving it commented keeps XID reporting disabled.
# MthreadsXidLevel = "warning"
| Field |
Description |
MthreadsXidLevel |
Minimum severity for reporting XID events. Options: "" (disabled), "notify", "warning", and "fatal". Events below the selected level are filtered out. The built-in default is ""; the commented "warning" value is only an example. |
To enable XID reporting, install the MUSA driver, remove mthreads_xid from the global BlackList, and set MthreadsXidLevel to a valid nonempty level. The tracer polls /proc/driver/musa/gpu*/event_report every second. Events include UUID, XID ID, severity, scope, PCI BDF, process ID, and additional context.
8.9 Known issue suppression
# Linux kernel event tracing configuration.
#
# - IssuesList
# Known issue filters for event tracing.
#
[EventTracing]
IssuesList = []
| Field |
Description |
IssuesList |
Known issue suppression rules in the form [["name", "regex"], ...]. Default: []. For net_rx_latency, the expression matches the generated event title; for dropwatch, it matches the kernel call stack joined with newlines. Matching events are discarded. Names identify rules only and are not written to saved events. Example: IssuesList = [["ignored_process", "comm=ignored_process"], ["neighbor_cleanup", "neigh_invalidate/"]]. |
9. Metric collection
This section configures system, network, and device metrics. Included and Excluded use regular expressions with the following rules:
- No rules: Collect all items.
Excluded only: Exclude matching items.
Included only: Collect only matching items.
- Both: Collect items that match
Included and do not match Excluded.
9.1 Basic network interface statistics
# Netdev statistic
#
# - EnableNetlink
# Use netlink instead of procfs net/dev to get netdev statistic.
# Query the target host or container network namespace.
# Default is "false".
#
# - DeviceIncluded
# Accept special devices in netdev statistic.
# Default: "" (empty), meaning include all.
#
# - DeviceExcluded
# Exclude special devices in netdev statistic.
# Default: "" (empty), meaning exclude nothing.
#
# Filter logic (applies to all Included/Excluded below):
# - No rules: all items are collected
# - Excluded only: blacklist, matched items are skipped
# - Included only: whitelist, only matched items are collected
# - Both: items must match Included AND not match Excluded
#
[MetricCollector.NetdevStats]
# EnableNetlink = false
# DeviceIncluded = ""
DeviceExcluded = "^(lo)|(docker\\w*)|(veth\\w*)$"
| Field |
Description |
EnableNetlink |
Whether to read network interface statistics through Netlink instead of procfs. Default: false. Netlink queries the target host or container network namespace and requires permission to access it. |
DeviceIncluded |
Regular expression for interface names to include. Default: "" (no inclusion restriction). |
DeviceExcluded |
Regular expression for interfaces to exclude. The built-in default is "" (exclude nothing). The configuration file explicitly uses the expression above to exclude matching lo, docker, and veth interfaces. |
9.2 Priority flow control (PFC)
# netdev dcb, DCB (Data Center Bridging)
#
# Collecting the DCB PFC (Priority-based Flow Control).
#
# - DeviceList
# Full-match regex patterns for the net devices we take care of.
# Literal names such as "eth0" keep exact-match behavior.
# Default: [] is empty, meaning no devices.
#
[MetricCollector.NetdevDCB]
DeviceList = ["eth0", "eth1"]
| Field |
Description |
DeviceList |
Full-match regular expressions for interfaces whose DCB PFC information is collected. The built-in default is [] (no devices); the configuration file explicitly sets ["eth0", "eth1"]. |
9.3 Network interface hardware statistics
# netdev hardware statistic
#
# Collecting the hardware statistic of net devices, e.g, rx_dropped.
#
# - DeviceList
# Full-match regex patterns for the net devices we take care of.
# Literal names such as "eth0" keep exact-match behavior.
# Default: [] is empty, meaning no devices.
#
[MetricCollector.NetdevHW]
DeviceList = ["eth0", "eth1"]
| Field |
Description |
DeviceList |
Full-match regular expressions for interfaces whose hardware statistics, such as rx_dropped, are collected. The built-in default is [] (no devices); the configuration file explicitly sets ["eth0", "eth1"]. |
9.4 Network queue statistics (Qdisc)
# Qdisc
#
# - DeviceIncluded / DeviceExcluded
# Same as above.
#
[MetricCollector.Qdisc]
# DeviceIncluded = ""
DeviceExcluded = "^(lo)|(docker\\w*)|(veth\\w*)$"
| Field |
Description |
DeviceIncluded / DeviceExcluded |
Interface filtering expressions. Both default to "", imposing no restrictions. The configuration file explicitly sets DeviceExcluded to the expression above. See the filtering rules at the start of this section. |
9.5 Virtual memory statistics (vmstat)
# vmstat
#
# This metric supports host vmstat and cgroup vmstat.
# - IncludedOnHost / ExcludedOnHost: same as above, for host /proc/vmstat.
# - IncludedOnContainer / ExcludedOnContainer: same, for cgroup containers memory.stat.
#
[MetricCollector.Vmstat]
IncludedOnHost = "allocstall|nr_active_anon|nr_active_file|nr_boost_pages|nr_dirty|nr_free_pages|nr_inactive_anon|nr_inactive_file|nr_kswapd_boost|nr_mlock|nr_shmem|nr_slab_reclaimable|nr_slab_unreclaimable|nr_unevictable|nr_writeback|numa_pages_migrated|pgdeactivate|pgrefill|pgscan_direct|pgscan_kswapd|pgsteal_direct|pgsteal_kswapd"
ExcludedOnHost = "total"
IncludedOnContainer = "active_anon|active_file|dirty|inactive_anon|inactive_file|pgdeactivate|pgrefill|pgscan_direct|pgscan_kswapd|pgsteal_direct|pgsteal_kswapd|shmem|unevictable|writeback|pgscan_globaldirect|pgscan_globalkswapd|pgscan_cswapd|pgsteal_cswapd|pgsteal_globaldirect|pgsteal_globalkswapd"
ExcludedOnContainer = "total"
| Field |
Description |
IncludedOnHost / ExcludedOnHost |
Field filtering expressions for host /proc/vmstat. Both default to "". The configuration file explicitly sets the inclusion list above and excludes fields matching total. |
IncludedOnContainer / ExcludedOnContainer |
Field filtering expressions for container cgroup memory.stat. Both default to "". The configuration file explicitly sets the inclusion list above and excludes fields matching total. |
9.6 Memory events
# MemoryEvents/Netstat/MountPointStat
#
# - Included / Excluded: Same as above.
# - MountPointsIncluded: whitelist only (no Excluded), same logic.
#
[MetricCollector.MemoryEvents]
Included = "watermark_inc|watermark_dec"
# Excluded = ""
| Field |
Description |
Included / Excluded |
Memory event field filtering expressions. Both default to "". The configuration file explicitly sets Included to select fields matching watermark_inc or watermark_dec. |
9.7 Network protocol statistics
[MetricCollector.Netstat]
# Excluded = ""
# Included = ""
| Field |
Description |
Included / Excluded |
Network protocol statistics field filtering expressions. Both default to "", imposing no restrictions. The configuration file does not explicitly set them. |
9.8 Mount point statistics
# MountPointStat
[MetricCollector.MountPointStat]
MountPointsIncluded = "(^/home$)|(^/$)|(^/boot$)"
| Field |
Description |
MountPointsIncluded |
Mount point path filtering expression. The built-in default is "" (no restriction). The configuration file explicitly uses the expression above to collect only /, /home, and /boot. |
9.9 Moore Threads GPU
# Moore Threads (MTT) GPU fine-grained toggles
#
# - EnableHealth
# Enable health metrics: temperature, power, voltage, utilization, memory,
# clocks, fans, pstate, VPU. Default: true
#
# - EnablePCIe
# Enable PCIe link metrics: current/max speed and width, replay counter.
# Default: false
#
# - EnableMTLink
# Enable MtLink interconnect metrics: per-link state and bandwidth.
# Default: false
#
[MetricCollector.Mthreads]
# EnableHealth = true
# EnablePCIe = false
# EnableMTLink = false
| Field |
Description |
EnableHealth |
Health metrics switch. Default: true. Includes temperature, power, voltage, utilization, memory capacity, clocks, fans, performance state, and VPU metrics. |
EnablePCIe |
PCIe link metrics switch. Default: false. Includes current and maximum link speed and width, and replay counters. |
EnableMTLink |
MtLink interconnect metrics switch. Default: false. Includes per-link bandwidth, link count, and link state. |
Requirements: Remove mthreads_gpu from the global BlackList, install libmtml.so.2 or libmtml.so where the system dynamic linker can find it, and restart the huatuo-bamai service. A missing library at startup disables the collector. Restart the huatuo-bamai service after installing the library or changing LD_LIBRARY_PATH.
Configuration updates: All three switches read the latest configuration on each collection. Changes made through the Node API take effect on the next collection.
9.10 Ascend NPU
Remove ascend_npu from the global BlackList and restart the huatuo-bamai service to enable the collector. The node requires an available Ascend NPU and /usr/local/dcmi/libdcmi.so. Device discovery still requires DCMI initialization when EnableDCMI is disabled.
# Ascend NPU fine-grained toggles
# Remove ascend_npu from BlackList and restart to enable the collector.
# DCMI initialization is required even when EnableDCMI is false.
#
# - EnableDCMI
# Enable DCMI metrics: health, power, temp, voltage, util, freq,
# network health, HBM, and ECC info. Default: true
#
# - EnablePCIe
# Enable PCIe link metrics: capability and status (speed/width).
# Default: false
#
# - EnableHCCN
# Enable HCCN network metrics via hccn_tool subprocesses.
# Default: false
#
[MetricCollector.AscendNPU]
# EnableDCMI = true
# EnablePCIe = false
# EnableHCCN = false
| Field |
Description |
EnableDCMI |
Boolean. Default: true. Collects health, power, temperature, voltage, utilization, frequency, network health, HBM, and ECC metrics. |
EnablePCIe |
Boolean. Default: false. Collects maximum and current PCIe link speed and width. |
EnableHCCN |
Boolean. Default: false. Collects network link, traffic, counter, and optical module metrics through /usr/local/Ascend/driver/tools/hccn_tool subprocesses. Ensure the tool is available before enabling it. |
These switches read the latest configuration on each collection. Changes made through the Node API take effect on the next collection.
This section configures the ports and credentials used to retrieve Pod information from kubelet and associate container and Pod labels.
# Pod Configuration
#
# Configure these parameters for fetching pods from kubelet.
#
# - KubeletReadOnlyPort
# The KubeletReadOnlyPort is kubelet read-only port for the Kubelet to serve on with
# no authentication/authorization. The port number must be between 1 and 65535, inclusive.
# Setting this field to 0 disables fetching pods from kubelet read-only service.
# Default: 10255
#
# - KubeletAuthorizedPort
# The port is the HTTPs port of the kubelet. The port number must be between 1 and 65535,
# inclusive. Setting this field to 0 disables fetching pods from kubelet HTTPS port.
# Default: 10250
#
# - KubeletClientCertPath
# https://kubernetes.io/docs/setup/best-practices/certificates/
#
# Client certificate and private key file name. One file or two files:
# "/path/to/xxx-kubelet-client.crt,/path/to/xxx-kubelet-client.key",
# "/path/to/kubelet-client-current.pem"
# Default: "". The assignment below supplies explicit deployment paths.
#
# You can disable this kubelet fetching pods, for bare metal service, by
# KubeletReadOnlyPort = 0, and KubeletAuthorizedPort = 0.
#
[Pod]
KubeletClientCertPath = "/etc/kubernetes/pki/apiserver-kubelet-client.crt,/etc/kubernetes/pki/apiserver-kubelet-client.key"
| Field |
Description |
KubeletReadOnlyPort |
Kubelet read-only port for retrieving the Pod list without authentication. Default: 10255; port range: 1–65535. Set to 0 to disable this method. |
KubeletAuthorizedPort |
Kubelet HTTPS port for retrieving Pod information using certificate authentication. Default: 10250; port range: 1–65535. Set to 0 to disable this method. Recommended for production. |
KubeletClientCertPath |
Kubelet client certificate and private key paths. The built-in default is "". Accepts two comma-separated paths or one PEM file containing both. The configuration file explicitly uses the paths under /etc/kubernetes/pki/ shown above; verify them for your deployment. In non-Kubernetes environments, set both kubelet ports to 0 to disable Pod discovery. |
11. Command-line options
huatuo-bamai supports these command-line options:
huatuo-bamai --region <region> [options]
| Option |
Description |
Default |
--config |
Configuration file name |
huatuo-bamai.conf |
--config-dir |
Configuration directory |
conf |
--bpf-dir |
BPF object directory |
bpf |
--tools-bin-dir |
Tracing tool binary directory |
bin |
--region |
Deployment region (required) |
- |
--disable-kubelet |
Disable Pod discovery through kubelet |
false |
--disable-storage |
Disable storage backends |
false |
--enable-cgroup |
Enable resource limits in Huatuo’s own cgroup (disabled by default) |
false |
--disable-tracing |
Disable a specified tracer; may be repeated |
- |
--log-debug |
Force the log level to Debug |
false |
--dry-run |
Test loading only; exit gracefully after startup |
false |
--procfs-prefix |
Procfs mount prefix |
- |
12. Override rules
Explicit configuration assignments override built-in defaults; comments are not loaded. Command-line options apply according to their own semantics rather than universally overriding the configuration file.
- Log level:
--log-debug forces Debug. Otherwise, Log.Level is used, with Info as the default when omitted.
- Tracing blacklist:
--disable-tracing is merged with the configuration file’s BlackList.
- Independent switches:
--disable-kubelet and --disable-storage disable Pod synchronization and storage backends, respectively. They have no same-named TOML fields, and enabling them does not bypass configuration validation.
13. Configuration recommendations
- Resource control: Use Pod resource limits in Kubernetes and service resource limits in systemd. For direct execution without an external manager, use
--enable-cgroup and [Runtime].
- Storage: Prefer LocalFile for local troubleshooting in small deployments. For large clusters, use Elasticsearch for centralized storage and queries.
- Automatic tracing: Tune thresholds for the workload. Low thresholds trigger frequent traces; high thresholds may miss problems. Validate changes incrementally in a test environment.
- Security: Use a strong password for Elasticsearch and consider enabling HTTPS. Avoid hard-coding sensitive information in configuration files.
- Compatibility: Check the required kernel capabilities, hardware, and runtime dependencies before enabling a feature.
4.2 - API Server Configuration
1. Overview
huatuo-apiserver.conf configures the HTTP server, job management, node communication, authentication, and profiling data queries for huatuo-apiserver.
This document quotes the repository configuration file and describes its fields in tables. A default is the value supplied by the program when a field is omitted. Uncommented assignments override defaults. Assignments commented out with # are inactive examples and may differ from defaults.
Before startup, replace the Agent.Auth.BearerToken placeholder and configure at least one user in Auth.Users. Replace example addresses and credentials with values for your deployment.
The configuration file uses strict TOML parsing. Unknown or obsolete fields prevent startup. Restart the service after editing the file.
2. Logging
# Log Configuration
[Log]
# - Level
# The log level for huatuo-apiserver: Debug, Info, Warn, Error, Panic.
# Default: Info
#
# Level = "Info"
| Field |
Description |
Level |
String. Default: "Info". Accepts Debug, Info, Warn, Error, and Panic, case-insensitively. The --log-debug flag overrides this setting. |
3. Resource Limits
The service does not create its own cgroup by default. The following limits apply only when --enable-cgroup is passed. Kubernetes and systemd deployments should use their native resource controls.
# Runtime limits for the huatuo-apiserver process.
[Runtime]
# - CPULimitCores
# CPU limit in cores.
# Default: 20
#
# - MemoryLimitMiB
# Memory limit in MiB.
# Default: 4096
#
# CPULimitCores = 20
# MemoryLimitMiB = 4096
| Field |
Description |
CPULimitCores |
Integer. Default: 20 CPU cores. Must be greater than 0. |
MemoryLimitMiB |
Integer. Default: 4096 MiB. Must be greater than 0. |
4. HTTP Server
# HTTP server configuration.
[APIServer]
# - ListenAddress
# Listen address in "host:port" form.
# Default: ":12740"
#
# ListenAddress = ":12740"
# Request rate limiting.
[APIServer.RateLimit]
# - RequestsPerSecond
# Maximum process-wide request rate per second.
# Default: 200
#
# - Burst
# Maximum process-wide request burst.
# Default: 200
#
# RequestsPerSecond = 200
# Burst = 200
| Field |
Description |
ListenAddress |
String. Default: ":12740". Uses host:port format. An empty host listens on all network interfaces. |
RateLimit.RequestsPerSecond |
Integer. Default: 200 requests per second. Must be greater than 0. Limits the request rate across the entire service process. |
RateLimit.Burst |
Integer. Default: 200. Must be greater than 0. Token bucket capacity, which limits request bursts. |
HTTP timeouts and request size limits use built-in values and are not configurable.
5. Job Management
5.1 Job Storage
# Job persistence.
[Jobs]
# - StoreDSN
# SQLite DSN. Relative paths are resolved from this file's directory.
# Default: "jobs.db"
#
# StoreDSN = "jobs.db"
| Field |
Description |
StoreDSN |
String. Default: "jobs.db". Must not be empty. Specifies the SQLite data source for persistent job state. Plain relative paths are resolved against the directory specified by --config-dir; file: URIs are passed through unchanged. |
Job records must conform to the current storage format and include a valid revision number. Incompatible records cannot be read. Check database compatibility before upgrading.
5.2 Concurrency Quotas
Profiling and Tracing jobs are counted separately and have independent limits. All quotas below are positive integers that limit the number of jobs that have not yet ended.
# Profiling and tracing retain independent quotas because their resource
# costs and expected concurrency differ.
[Jobs.Profiling]
# - MaxConcurrentPerHost
# Maximum concurrent profiling jobs on one host.
# Default: 3
#
# - MaxConcurrent
# Maximum concurrent profiling jobs across all hosts.
# Default: 500
#
# MaxConcurrentPerHost = 3
# MaxConcurrent = 500
[Jobs.Tracing]
# - MaxConcurrentPerHost
# Maximum concurrent tracing jobs on one host.
# Default: 5
#
# - MaxConcurrent
# Maximum concurrent tracing jobs across all hosts.
# Default: 1000
#
# MaxConcurrentPerHost = 5
# MaxConcurrent = 1000
| Field |
Description |
Jobs.Profiling.MaxConcurrentPerHost |
Maximum Profiling jobs per node. Default: 3. |
Jobs.Profiling.MaxConcurrent |
Maximum Profiling jobs across all nodes. Default: 500. |
Jobs.Tracing.MaxConcurrentPerHost |
Maximum Tracing jobs per node. Default: 5. |
Jobs.Tracing.MaxConcurrent |
Maximum Tracing jobs across all nodes. Default: 1000. |
5.3 Lifecycle
Jobs.Controller controls job status polling, timeout handling, and record cleanup in the API server, independently of the node’s Operation lifecycle settings. All values below are positive integers.
# Apiserver-owned Job supervision policy. These values are independent
# from the Node operation lifecycle settings.
[Jobs.Controller]
# StatusPollIntervalSeconds = 5
# PendingTimeoutSeconds = 30
# CompletionGracePeriodSeconds = 60
# NodeUnavailableGracePeriodSeconds = 30
# JobRetentionPeriodHours = 720
| Field |
Description |
StatusPollIntervalSeconds |
Status polling interval. Default: 5 seconds. |
PendingTimeoutSeconds |
Startup timeout, measured from just before the node Operation is initiated. Default: 30 seconds. A job still in Pending when the timeout expires enters the stop process. |
CompletionGracePeriodSeconds |
Completion grace period. Default: 60 seconds. Once the job is confirmed running, its execution deadline is the current time plus the job duration and this grace period. The same period is used to wait for the node Operation to end after the stop process begins. |
NodeUnavailableGracePeriodSeconds |
Recovery grace period for an unavailable node. Default: 30 seconds. Starts when the node is first found unavailable. The job fails if the node remains unavailable beyond this period. |
JobRetentionPeriodHours |
Retention period for ended job records. Default: 720 hours (30 days). Measured from the time the job ends; expired records are removed by periodic cleanup. |
Service shutdown does not stop active Operations on nodes. After restarting, the service recovers unfinished jobs from the database and resumes managing them. Operations already initiated are not started again.
6. Node Communication
These settings control API server access to huatuo-bamai nodes. They are separate from Auth.Users, which controls client access to the API server.
# huatuo-bamai Agent HTTP client configuration.
[Agent]
# - HTTPPort
# Agent HTTP server port.
# Default: 19704
#
# HTTPPort = 19704
[Agent.Auth]
# Required service credential. It must match HTTPServer.Auth on every
# huatuo-bamai Node.
BearerToken = "REPLACE_WITH_RANDOM_HEX"
| Field |
Description |
HTTPPort |
Integer. Default: 19704. Range: 1–65535. Must match the node’s HTTP server port. |
Auth.BearerToken |
String. Required, with no built-in credential. Must not contain whitespace. Must match HTTPServer.Auth.BearerToken on every node. Replace the placeholder in the configuration file. |
Transport timeouts and other safeguards for node requests use built-in client values.
7. Authentication and Authorization
Configure at least one [[Auth.Users]] entry. The user configurations below are commented examples. Uncomment them and replace the credentials before use. Each user must have a distinct ID and BearerToken.
# Authentication configuration.
[Auth]
# /readyz, /metrics, and /version are public. Flame graph query
# endpoints and /debug/pprof/** are restricted to administrators.
#
# - ID
# Stable principal identifier stored with jobs.
#
# - BearerToken
# Secret used only to authenticate requests. IDs and tokens must be unique.
#
# - Admin
# Whether the principal has unrestricted API access.
#
# - Permissions
# API method and path patterns granted to a restricted principal.
#
# Administrator example:
# [[Auth.Users]]
# ID = "administrator"
# BearerToken = "REPLACE_WITH_RANDOM_HEX"
# Admin = true
#
# Restricted example:
# [[Auth.Users]]
# ID = "huatuo-front"
# BearerToken = "REPLACE_WITH_RANDOM_HEX"
# Permissions = [
# "GET /v1/tracing",
# "GET /v1/tracing/**",
# "GET /v1/profiling",
# "GET /v1/profiling/**",
# ]
| Field |
Description |
ID |
String. Required and unique. Stable user identifier persisted with jobs. |
BearerToken |
String. Required and unique. Used only for request authentication. Rotating the token does not change job ownership. |
Admin |
Boolean. Default: false. When true, grants access to all APIs without restrictions from Permissions. |
Permissions |
Array of strings. Empty by default; required for non-admin users. Each entry is a path or HTTP method path. A path without a method allows any method. |
In paths, * matches one segment and ** matches one or more subsequent segments. For example, GET /v1/profiling/** does not cover the collection path GET /v1/profiling; grant each permission separately.
/readyz, /metrics, /version, and /openapi.json require no authentication. /debug/pprof/** and /v1/profiling/flamegraph/** require administrator access. The pprof endpoints must also be enabled with --enable-pprof.
8. Profiling
8.1 Data Queries
Elasticsearch/OpenSearch provides queries for profiling data written by nodes. This data is stored separately from job records in Jobs.StoreDSN. Address, Username, and Password must either all be empty or all be configured.
# Optional Elasticsearch/OpenSearch backend for querying profiling data.
[Elasticsearch]
# Address, Username, and Password must be configured together to enable
# this backend.
#
# - Address
# Elasticsearch or OpenSearch HTTP address.
#
# - Username
# Elasticsearch or OpenSearch username.
#
# - Password
# Elasticsearch or OpenSearch password.
#
# - Index
# Index containing huatuo-bamai profiling data.
# Default: "huatuo_bamai"
#
# Address = "http://127.0.0.1:9200"
# Username = "elastic"
# Password = "REPLACE_WITH_PASSWORD"
# Index = "huatuo_bamai"
| Field |
Description |
Address |
String. Empty by default. HTTP/HTTPS address; separate multiple addresses with commas. |
Username |
String. Empty by default. Required when the query backend is enabled. |
Password |
String. Empty by default. Required when the query backend is enabled. Replace the example placeholder. |
Index |
String. Default: "huatuo_bamai". Must not be empty when the query backend is enabled. Must match the index to which nodes write profiling data. |
When the backend is disabled, the endpoints remain registered, but raw Profile and flame graph data cannot be queried.
8.2 Result Links
# Profiling result-link configuration.
[Profiling]
# - DashboardBaseURL
# Optional dashboard base URL. Result URLs are omitted when empty.
# Default: empty
#
# DashboardBaseURL = "http://localhost:8006/d"
| Field |
Description |
DashboardBaseURL |
String. Empty by default, which omits Dashboard URLs. When set, must be an HTTP/HTTPS address with a host. The address in the configuration file is only an example. |
Result links are generated only when a job has ended with a completed or unknown outcome and the query backend confirms that its data has been published. Profiler execution and aggregation settings are maintained in the node configuration.
5 - Key Features
HUATUO provides resource metrics, event diagnostics, automatic tracing, and profiling. Choose a feature based on your troubleshooting goal:
| Goal |
Documentation |
Main results |
| Check resource usage on nodes and in containers |
Kernel-wide Insight |
CPU, memory, network, storage, and accelerator metrics |
| Investigate past system anomalies |
Event Diagnostics |
Event times, process and container context, and call stacks |
| Capture diagnostics automatically when metrics indicate an anomaly |
Automatic Tracing |
Triggering metrics, CPU flame graphs, and I/O and memory diagnostics |
| Investigate CPU hotspots and memory allocation |
Continuous Profiling |
CPU time, wait time, and memory allocation attributed to call stacks |
| Investigate CPU, memory, and PCIe hardware errors |
Hardware Error Diagnostics |
RAS error counts, device identifiers, and error details |
Start with resource metrics to identify the time and scope of an anomaly, then examine events or profiling results. For collection switches, thresholds, and storage settings, see Node Configuration. For task management and query settings, see API Server Configuration.
For metrics, event fields, and raw codes, see the Reference Manual.
5.1 - Kernel-wide Insight
Overview
HUATUO collects host and container metrics for CPU, memory, network, I/O, system events, and GPUs to help identify when an anomaly occurs, which resources are involved, and its scope.
| Problem |
Key metrics |
| Busy CPUs or tasks waiting too long to be scheduled |
Utilization, scheduling latency, throttling, and wait ratio |
| Memory pressure, reclaim stalls, or allocation failures |
Memory state, reclaim duration, OOM, and free memory blocks |
| Reduced network throughput, packet drops, or connection anomalies |
Network interface, transmit queue, TCP, and socket statistics |
| Slow disk responses |
I/O latency distributions, throughput, and request duration |
| System stalls or prolonged task blocking |
softlockup and hungtask event counts |
| GPU load, memory, or device state anomalies |
Utilization, memory, temperature, power, and interconnect metrics |
Configuration
Actual output depends on kernel interfaces, device drivers, collector switches, and filters. Some collectors are disabled by default in the repository configuration. For instructions on enabling them, see Node Configuration.
Metrics are exposed through /metrics. For full names, units, labels, examples, and measurement semantics, see the Metrics Reference. A missing metric does not imply a zero value.
CPU
Utilization measures how much CPU capacity is used; scheduling latency measures how long runnable tasks wait for a CPU. Combine these with available container CPU capacity, throttling, and wait ratio to distinguish high compute load, quota limits, and resource contention.
Host utilization is normalized by the number of online CPUs; container utilization is normalized by available CPU capacity. Host load averages and current container task counts use different observation windows and should not be compared directly.
For metrics and bucket ranges, see CPU Metrics.
Memory
Memory state metrics distinguish anonymous and file memory, as well as activity states. Reclaim duration and event counts help investigate stalls caused by memory pressure. Free memory blocks are reported by NUMA node, zone, and order to help investigate contiguous memory allocation problems.
Fields and units vary by kernel and cgroup version. Interpret page counts, byte counts, and event counts separately; some metrics depend on custom kernel interfaces. For measurement conditions, see Memory Metrics.
Network
Network interface and transmit queue metrics show throughput, backlog, and packet drops. TCP, socket, connection tracking, and ARP statistics help analyze connections and protocol resource usage.
Transmit queue backlog is not queueing latency, and aggregate error counts may already include individual error categories. Check measurement semantics to avoid double counting. For metrics and their sources, see Network Metrics.
I/O
iotracing provides disk throughput, IOPS, mean request duration, utilization, and queue length. blk_iotrace measures Q2G, Q2D, and D2C latency and IO size distributions; blk_throtl and blk_iocost report completed queue waits. blk_device_health records Block, NVMe, SCSI, and MD health events and collects read-only device evidence. XFS metrics add filesystem log and allocation state.
Latency, size, and wait metrics describe individual collection intervals. Device changes restart collection, and transition data may be omitted. For names, units, labels, startup requirements, and measurement semantics, see I/O Metrics.
System events
softlockup and hungtask counters track soft lockups and blocked tasks reported by the kernel. Count changes help identify the affected time range. For process and call stack information, see Event Diagnostics. For metric names, see System Event Metrics.
GPU
The collector gathers GPU utilization, memory, temperature, power, PCIe, MetaXLink, ECC, and related metrics. Before enabling it, meet the device and SDK requirements and check the metax_gpu blacklist setting.
For the metric list, see MetaX Metrics.
MThreads
The collector gathers GPU, memory, power, PCIe, MTLink, and related metrics. It requires the MTML management library. After enabling the collector, use MetricCollector.Mthreads to control metric groups.
Interpret device specifications separately from current throughput. For dependencies and the metric list, see MThreads Metrics.
Ascend
Details omitted.
5.2 - Event Diagnostics
Overview
Event diagnostics records scheduling, memory, and network anomalies reported by the Linux kernel, along with process, container, and call stack context for later investigation. Collection primarily uses eBPF probes; network interface state changes are obtained through netlink.
| Problem |
Events or observers |
| Scheduling stalls, soft lockups, or prolonged task blocking |
sched_tick, softlockup, hungtask |
| OOM or blocking during direct memory reclaim |
memory_oom_kill, memory_reclaim_events |
| Packet drops in the network stack or receive latency |
dropwatch, net_rx_latency |
| Network interface state, LACP, or transmit queue timeouts |
netdev_events, netdev_bonding_lacp, netdev_txqueue_timeout |
| TCP retransmissions |
See tcpshark |
| CPU, memory, or PCIe hardware errors |
See Hardware Error Diagnostics |
Events provide diagnostic clues but cannot independently establish a root cause. Probe support, filtering, and rate limits affect coverage; insufficient buffer space can also cause event loss.
Configuration
Set thresholds and filters under EventTracing in huatuo-bamai.conf. For all fields, defaults, and units, see “Event tracing” in Node Configuration. The global blacklist controls whether observers are enabled.
Event records
Events are written to Elasticsearch or local files according to the storage configuration. Filter by tracer_type=event, event name, host or container, and time range to inspect process, call stack, and device information. Container fields are provided only when association succeeds.
For full JSON examples, field units, and compatibility notes, see Event Fields.
CPU scheduling
Scheduler tick interval
Observer: sched_tick.
When the interval between consecutive scheduler ticks reaches the threshold, the observer records the process and kernel stack. This helps investigate prolonged interrupt disabling, CPU stalls, or virtualization scheduling delays. Set the threshold above the normal tick period; normal NO_HZ tick suppression is filtered out.
The record captures the first tick after the delay ends. The process and call stack are not necessarily the cause of the delay. High CPU load or a softirq backlog does not itself imply tick delay.
For field details, see Event Fields.
Soft lockups
Observer: softlockup.
The observer records process, CPU, and NMI backtrace information when the kernel reports a softlockup. This information alone cannot identify the process responsible. The kernel watchdog configuration determines the trigger timing.
The reporting interval for repeated events increases from 10 minutes to a maximum of 3 hours. Event counts continue to accumulate during this interval.
For field details, see Event Fields.
Blocked tasks
Observer: hungtask.
The observer detects system hungtask events and collects kernel stacks of processes in D state (uninterruptible sleep), along with CPU backtraces.
The reporting interval for repeated events increases from 10 minutes to a maximum of 3 hours, while event counts continue to accumulate. The observer is not registered if the kernel does not expose hung_task_timeout_secs. Setting this value to 0 disables kernel hungtask detection.
For field details, see Event Fields.
Memory
OOM kills
Observer: memory_oom_kill.
The observer records the process that triggers the OOM Killer (trigger), the terminated process (victim), and available container, cgroup, and host memory information. The triggering process is not necessarily the main memory consumer; examine memory usage and limits together.
For field details, see Event Fields.
Direct reclaim
Observer: memory_reclaim_events.
The observer records the duration of a single direct memory reclaim operation by a container thread. When try_to_free_pages returns, it reports process, thread, and container information if the call exceeded the threshold, which defaults to 900 milliseconds. Events not associated with a container are filtered out.
Use the registered name memory_reclaim_events in the blacklist. Saved records use memory_reclaim as tracer_name.
For field details, see Event Fields.
Network
Network stack packet drops
Observer: dropwatch.
The observer detects packet drops in the kernel network stack and records the kernel call stack, network five-tuple, TCP state, and related information at the time of the drop. An optional call stack filter can suppress noise patterns verified on the local host.
For field details, see Event Fields.
Receive latency
Observer: net_rx_latency.
The observer measures TCP packet latency from the driver receive point to __netif_receive_skb, tcp_v4_rcv, and the user-space copy point. All three values start at the driver; they are not durations between adjacent observation points. Default thresholds are 5, 10, and 115 milliseconds, respectively. When a threshold is reached, the observer records endpoints, TCP state, sequence numbers, and latency values.
By default, the host network namespace is excluded and only container networks are observed.
For field details, see Event Fields.
Network interface state
Observer: netdev_events.
The observer subscribes to kernel netlink RTM_NEWLINK messages to detect changes in interface link state flags, such as AdminDown and CarrierDown. It records the interface name, link state, MAC address, and driver information.
At startup, the observer scans the current state of interfaces configured in EventTracing.Netdev.DeviceList to establish a baseline. It reports only subsequent state changes.
For field details, see Event Fields.
LACP state
Observer: netdev_bonding_lacp.
The observer is enabled only when an IEEE 802.3ad bonding interface exists. On LACP state changes, it records the bonding interface mode, link state, and negotiation information to help investigate link aggregation anomalies.
Use the registered name netdev_bonding_lacp in the blacklist and tracer_name=lacp when querying records.
For field details, see Event Fields.
Transmit queue timeouts
Observer: netdev_txqueue_timeout.
The observer detects network interface transmit queue timeouts and records the affected queue index, device name, and driver name. Use these records to investigate device, driver, or link problems on the transmit path.
For field details, see Event Fields.
5.3 - Automatic Tracing
Overview
AutoTracing starts collecting diagnostics when metrics meet configured conditions, helping investigate intermittent CPU, I/O, load, and memory anomalies. CPU spikes trigger the configured perf or profiler tool; other scenarios collect process states, call stacks, memory usage rankings, or runtime snapshots as needed.
| Problem |
Tracer |
Results |
| Host system CPU spike |
cpusys |
Host CPU flame graph and triggering metrics |
| Container CPU spike |
cpuidle |
Container CPU flame graph and triggering metrics |
| Elevated container D-state load |
dload |
Process state statistics and kernel stacks of D-state processes |
| Disk I/O anomaly |
iotracing |
Process and file I/O rates, and I/O scheduling wait stacks |
| Host anonymous memory spike |
memburst |
Processes with the highest RSS and runtime memory snapshots |
Collection starts only after a threshold is triggered, so results cannot reconstruct the full execution history before the trigger. Correlate results with the anomaly time, resource metrics, and application requests.
Configuration
Configure AutoTracing in huatuo-bamai.conf. For field defaults, units, and limits, see “Automatic tracing” in Node Configuration.
| Tracer |
Configuration section |
cpusys |
AutoTracing.CPUSys |
cpuidle |
AutoTracing.CPUIdle |
dload |
AutoTracing.Dload |
iotracing |
AutoTracing.IOTracing |
memburst |
AutoTracing.MemoryBurst |
Before use, check the global blacklist, target container filters, and collection tool availability. Cooldown periods and scope depend on the tracer. Default thresholds in this document are built-in values; the configuration file can override them.
Node Configuration also covers interrupt utilization anomalies and container memory snapshots triggered by thresholds. This page focuses on the five tracing results listed above.
Results
Automatic tracing events are written to Elasticsearch or local files according to the enabled storage configuration. Filter by host, container, time range, and tracer, then correlate results with application requests.
For CPU collection, perf embeds flame graph data in the event. With profiler, the event retains trigger metrics; profiles are stored separately in Elasticsearch and linked by the same tracer_id. See Node Configuration for storage requirements and viewing instructions.
Common fields
| Field |
Purpose |
hostname / container_id |
Identify the node or container; container fields are provided only when association succeeds |
tracer_name / tracer_id |
Identify the tracer and the individual trace |
started_timestamp |
Correlate the trace with the anomaly time |
tracer_type |
Set to autotracing for automatic tracing records |
tracer_data |
Triggering metrics and collected results |
For the full record structure, see Automatic Tracing Fields.
Host system CPU
Tracer: cpusys. Select the tool with AutoTracing.CPUSys.Tool (default: perf).
Host CPU sampling starts when both system CPU utilization and its increase between consecutive samples exceed their thresholds. The default thresholds are 45% and 20 percentage points, respectively, with a 30-minute cooldown.
Results include the triggering metrics and a CPU flame graph for identifying call paths with high system CPU usage.
For fields and examples, see Automatic Tracing Fields.
Container CPU
Tracer: cpuidle. Select the tool with AutoTracing.CPUIdle.Tool (default: perf).
Container-level CPU sampling starts when any one of user, system, or total CPU utilization exceeds both its utilization threshold and its increase threshold. The default cooldown is 30 minutes. AutoTracing.CPUIdle.Filter controls the target scope.
Results include utilization values, their increases, and a container CPU flame graph for examining CPU hotspots within the container.
For fields and examples, see Automatic Tracing Fields.
Container D-state load
Tracer: dload.
When the exponential moving average (EMA) of container D-state load exceeds the threshold, the tracer collects kernel stacks of D-state processes in the container and on the host. The default threshold is 5, with a 30-minute cooldown per container.
Results also include process state statistics. Use the stacks to investigate where processes block, and AutoTracing.IssuesList to mark known issues.
For fields and examples, see Automatic Tracing Fields.
Disk I/O
Tracer: iotracing.
The tracer reads /proc/diskstats every 5 seconds. Trigger conditions must hold for two consecutive sampling periods: non-NVMe devices are checked for utilization; NVMe devices must exceed both the utilization threshold and either the read or write throughput threshold. Average read and write wait times are also checked independently for each device.
Results include process and file I/O rates and I/O scheduling wait stacks, helping identify sources of I/O usage and waiting paths.
For fields and examples, see Automatic Tracing Fields.
Host anonymous memory
Tracer: memburst.
By default, the tracer samples every 10 seconds and starts evaluating conditions after collecting 60 samples. It triggers when current anonymous memory usage reaches twice the oldest value in the window and at least 70% of total host memory. The default cooldown is 30 minutes.
By default, results list the top 10 processes by RSS and attempt runtime memory snapshots for the top three to narrow the search for memory consumption. Snapshot support depends on the target runtime. Failed or unavailable captures include a status explanation; they do not mean that the process uses no memory.
For fields and examples, see Automatic Tracing Fields.
5.4 - Continuous Profiling
Overview
Continuous profiling attributes CPU time, wait time, and memory allocation during collection to call stacks, helping identify which code paths consume resources. Combined with resource metrics, it helps narrow an investigation from an affected node or container to functions that need inspection.
Profiling runs for a specified duration and produces periodic windows or a single result, depending on the collection mode. Manage node and container tasks through the API, or run profiler directly on the target node.
Use cases
| Problem |
Profiling mode |
Diagnostic information |
| CPU usage rises and hotspots need investigation |
on-CPU |
CPU time consumed by each call stack |
| Requests slow down without high CPU usage |
off-CPU |
Call paths associated with blocking and scheduling waits |
| Frequent memory allocation requires investigation |
Native memory or Java object allocation |
Allocation volume and allocation call stacks |
| Memory usage keeps growing and live allocations need inspection |
Live physical pages or live Java objects |
Live allocation volume and allocation paths within the collection scope |
Hotspots and live allocation volume provide diagnostic clues; they do not independently prove a performance bottleneck or memory leak. Interpret them alongside workload, collection scope, and time window.
Collection capabilities
CPU
| Mode |
Supported languages |
Measurements |
| on-CPU |
C, C++, Go, Java, Python |
Call stacks sampled at the configured frequency and converted to CPU time |
| off-CPU |
C, C++, Go |
Blocking and scheduling wait time after a thread leaves the CPU |
Native collection uses eBPF; Java uses async-profiler; Python uses py-spy. Off-CPU collection is event-driven and distinguishes blocking from run queue waits. It does not measure end-to-end application request latency.
Memory
| Mode |
Supported languages |
Measurements |
virtual_alloc |
C, C++, Go |
Virtual address space allocation volume |
physical_alloc |
C, C++, Go |
Physical memory allocated within the collection window |
physical_usage |
C, C++, Go |
Bytes in live physical pages tracked during this collection |
object_alloc |
Java |
Object allocation volume and allocation call stacks |
object_usage |
Java |
Live objects and allocation call stacks |
Python currently supports only CPU profiling. physical_usage excludes pages allocated before collection and does not scale values by the inverse sampling probability. It cannot represent a process’s full RSS. Page-free detection and other limitations still require validation and improvement; see Profiling in Practice.
Collection methods
| Method |
Scope |
Dependencies |
| Profiling API |
Remotely create, query, and stop node or container tasks |
huatuo-apiserver and huatuo-bamai; querying results requires Elasticsearch |
profiler CLI |
Collect data for a target process on a node; native CPU collection also supports host or container scope |
A Linux collection environment and the relevant tools; local output requires neither the API service nor Elasticsearch |
Supported languages, modes, and target scopes depend on the current version. Native collection also requires the necessary kernel capabilities and sampling permissions.
Results
Flame graphs
A flame graph shows call paths and their cumulative values. Width represents CPU time, wait time, or bytes in the selected memory dimension; the vertical axis represents call depth. Horizontal position does not indicate chronological order. Inspect wider frames to identify sources of resource consumption.

View results in Grafana or export them locally as SVG, folded stacks, or JSON for offline analysis and further processing.
Use --output-format=tui to open an interactive terminal flame graph after collection. Press v to cycle through the graph, the full frame list, and Top Table. In the graph, Up selects the parent, Down selects the first child or returns from a leaf to the root of the current view, and Left/Right select adjacent frames at the same depth. The frame list includes frames narrower than one terminal column. Up and Down move one row at a time in the list and Top Table.
Enter zooms in, Backspace zooms out, r returns to the full graph, and / searches. Press g in the graph or frame list to group stacks by sample fields, such as cpu,comm. With a file or directory set via --output-path, pressing q saves a gob report that you can reopen by passing its path to --tui-report. Omit --output-path or use stdout or - for terminal viewing only.
Collection windows
Native CPU, native memory, and Java collection process data periodically; Python produces one result when collection ends. Window timestamps describe reception and aggregation intervals, not exact execution times for individual samples.
Live physical page usage uses the latest snapshot and must not be summed across windows. When comparing results, keep the target, mode, time range, and workload comparable.
Completeness
Task status, result publication, and sample loss statistics together determine whether results are usable. A failed task may retain some data already written. A flame graph does not prove that the task completed successfully, and empty results do not prove that no resources were consumed.
For deployment steps, task APIs, CLI examples, and result validation, see Profiling in Practice.
5.5 - Hardware Error Diagnostics
Overview
HUATUO records CPU, memory, and PCIe errors through kernel RAS events, providing error counts and structured details. Analyze failures using device locations, error trends, and application anomalies. A single error or an increase in counts does not by itself prove that a device is about to fail.
Collection scope
| Source |
tracer_data.event |
Main information |
| MCE |
MCE |
CPU machine-check registers, CPU IDs, and bank numbers |
| EDAC |
EDAC |
Memory errors, controllers, and memory location labels |
| ACPI GHES |
NON_STANDARD |
Platform-specific non-standard error records and FRU information |
| PCIe AER |
AER |
PCIe device, error type, and TLP header |
| MCE threshold interrupt |
MCE_THRESHOLD |
Interrupt vector and CPU ID |
Actual coverage depends on hardware, firmware, kernel tracepoints, and probe loading. Current startup checks require the ras tracepoint directory and mce/mce_record; the RAS observer does not start if either is missing. Although the decoder defines ARM GHES records, this does not establish ARM platform availability.
Kernel events pass through eBPF buffers to user space, where they are parsed into count metrics and event records:

Configuration
Ensure that the global blacklist does not disable ras, and enable Elasticsearch or local file storage as needed. See “Hardware errors (RAS)” in Node Configuration.
EventTracing.Ras.MceThrBackoff controls the interval between saved MCE threshold interrupt events. The built-in default is 1800 seconds. Received THR events are still counted during cooldown, so count increases may differ from the number of saved records.
Results
Error counts
huatuo_bamai_ras_hw_err_total counts received RAS events by source to show error trends. It is neither the sum of err_count values in EDAC records nor the number of saved records.
Event records
Events include observation time, device, error source, severity, and source-specific details. The following example omits some fields:
{
"tracer_name": "ras",
"tracer_type": "event",
"tracer_data": {
"dev": "MEM",
"event": "EDAC",
"type": "Corrected",
"info": "{\"err_count\":1,\"label\":\"CPU0_DIMM_A1\"}"
}
}
Query by tracer_name=ras, device, and time range. info is a JSON string that requires a second parsing step; its fields vary by error source. Assess impact using device topology and error trends. A single record does not by itself prove device damage.
Severity
| Type |
Meaning |
Corrected |
Corrected |
UncorrectedRecoverable |
Uncorrected, recoverable category |
UncorrectedDeferred |
Uncorrected, deferred category |
UncorrectedFatal |
Uncorrected, fatal category |
Info |
Informational record |
unknown |
Severity cannot be mapped |
Severity is a classification. It does not establish that recovery succeeded, that the application was unaffected, or that a restart is required. For registers, raw code mappings, and fields by source, see Hardware Event Fields.
6 - Practical Guides
Choose a guide by troubleshooting or integration goal. See Key Features for an overview.
6.1 - Storage Services
Overview
This guide shows how to write kernel events and AutoTracing results to Elasticsearch or OpenSearch and verify remote records. Examples use specific Docker image versions; protocol, authentication, and index settings must match the target service.
Events are written to enabled backends. [Storage.LocalFile] controls local files; [Storage.Elasticsearch] controls remote storage. They are configured independently. The local directory is not an automatic fallback queue for failed remote writes.
Choose a Backend
Choose one backend for your environment. Before starting the collector, confirm the storage service is accessible and set its address, authentication, and index using Node Configuration. For Grafana integration, see Data Sources.
OpenSearch 2.x
1. Deploy OpenSearch
docker pull opensearchproject/opensearch:2.6.0
docker run -d --name opensearch --network host \
-e "discovery.type=single-node" \
opensearchproject/opensearch:2.6.0
2. Verify Service Status
curl -k -u admin:admin https://localhost:9200
Example response:
{
"name" : "22ca72df78c0",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "yxb3foceQVKzXXO6bHpPHQ",
"version" : {
"distribution" : "opensearch",
"number" : "2.6.0",
"build_type" : "tar",
"build_hash" : "7203a5af21a8a009aece1474446b437a3c674db6",
"build_date" : "2023-02-24T18:57:04.388618985Z",
"build_snapshot" : false,
"lucene_version" : "9.5.0",
"minimum_wire_compatibility_version" : "7.10.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "The OpenSearch Project: https://opensearch.org/"
}
If verification fails, inspect the container logs:
Add the following settings to huatuo-bamai.conf. This example uses the OpenSearch 2.6.0 image with admin as both username and password. See the configuration guide for storage settings.
[Storage.Elasticsearch]
Address = "https://127.0.0.1:9200"
Index = "huatuo_bamai"
Username = "admin"
Password = "admin"
4. Start huatuo-bamai
Use --config-dir to specify the directory containing the configuration:
./_output/bin/huatuo-bamai --region dev --config-dir .
Generate the target event in a test environment, then query records for the corresponding node and time. A local file confirms only a local write; verify remote writes by querying OpenSearch:
curl -k -u admin:admin \
-X GET "https://localhost:9200/huatuo_bamai/_search?pretty" \
-H "Content-Type: application/json" \
-d '{"query": {"match_all": {}}}'
Example response:
{
"_index" : "huatuo_bamai",
"_id" : "yjPG_50Bu_OF-hukxKR7",
"_score" : 1.0,
"_source" : {
"hostname" : "hostname",
"region" : "dev",
"uploaded_timestamp" : "2026-05-07T00:11:49.753166222Z",
"tracer_name" : "net_rx_latency",
"observed_timestamp" : "2026-05-07T00:11:49.753166222Z",
"tracer_type" : "event",
"tracer_data" : {
"comm" : "<nil>",
"pid" : 0,
"latency_stage" : "RX_STAGE_NETIF",
"latency_ms" : 1776078133565,
"tcp_saddr" : "127.0.0.1",
"tcp_daddr" : "127.0.0.1",
"tcp_sport" : 37736,
"tcp_dport" : 9200,
"tcp_seq" : 1080592402,
"tcp_ack_seq" : 2465063876,
"packet_len_bytes" : 781
}
}
}
The following command counts records only:
curl -k -u admin:admin -X GET "https://localhost:9200/huatuo_bamai/_count?pretty"
In the response, count is the number of matching records:
{
"count" : 2680,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
}
}
Elasticsearch 8.x
1. Deploy Elasticsearch
docker pull docker.elastic.co/elasticsearch/elasticsearch:8.15.5
docker run -d --name elasticsearch --network host \
-e "discovery.type=single-node" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
-e "ELASTIC_PASSWORD=123456" \
docker.elastic.co/elasticsearch/elasticsearch:8.15.5
2. Verify Service Status
curl -k -u elastic:123456 https://localhost:9200
Example response:
{
"name" : "ab0b562f8dbd",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "aVfOVgJTQXuhZ3HGotK3ww",
"version" : {
"number" : "8.15.5",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "b10896bcfe167cce44a84ba2771d101fb596d40d",
"build_date" : "2024-11-21T22:06:13.985834967Z",
"build_snapshot" : false,
"lucene_version" : "9.11.1",
"minimum_wire_compatibility_version" : "7.17.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "You Know, for Search"
}
Add the following settings to huatuo-bamai.conf. The Elasticsearch image uses the default username elastic; set the password through ELASTIC_PASSWORD. See the configuration guide for storage settings.
[Storage.Elasticsearch]
Address = "https://127.0.0.1:9200"
Index = "huatuo_bamai"
Username = "elastic"
Password = "123456"
4. Start huatuo-bamai
Use --config-dir to specify the directory containing the configuration:
./_output/bin/huatuo-bamai --region dev --config-dir .
Generate the target event in a test environment, then query records for the corresponding node and time. A local file confirms only a local write; verify remote writes by querying Elasticsearch:
curl -k -u elastic:123456 \
-X GET "https://localhost:9200/huatuo_bamai/_search?pretty" \
-H "Content-Type: application/json" \
-d '{"query": {"match_all": {}}}'
Example response:
{
"_index" : "huatuo_bamai",
"_id" : "WtNZAJ4BQ8x-thPHEY1i",
"_score" : 1.0,
"_source" : {
"hostname" : "hostname",
"region" : "dev",
"uploaded_timestamp" : "2026-05-07T02:51:37.696263325Z",
"tracer_name" : "net_rx_latency",
"observed_timestamp" : "2026-05-07T02:51:37.696263325Z",
"tracer_type" : "event",
"tracer_data" : {
"comm" : "<nil>",
"pid" : 0,
"latency_stage" : "RX_STAGE_NETIF",
"latency_ms" : 1776078133565,
"tcp_saddr" : "127.0.0.1",
"tcp_daddr" : "127.0.0.1",
"tcp_sport" : 2379,
"tcp_dport" : 36706,
"tcp_seq" : 950542706,
"tcp_ack_seq" : 1960972383,
"packet_len_bytes" : 91
}
}
}
The following command counts records only:
curl -k -u elastic:123456 -X GET "https://localhost:9200/huatuo_bamai/_count?pretty"
In the response, count is the number of matching records:
{
"count" : 2680,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
}
}
Elasticsearch 7.x
This section uses HTTP. Match the address, protocol, and credentials to the actual service configuration.
1. Deploy Elasticsearch
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.10.1
docker run -d --name elasticsearch --network host \
-e "discovery.type=single-node" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
-e "ELASTIC_PASSWORD=123456" \
docker.elastic.co/elasticsearch/elasticsearch:7.10.1
2. Verify Service Status
curl -k -u elastic:123456 http://localhost:9200
Example response:
{
"name" : "d88c9e8df48b",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "_ZZefWx4SniAc255t_lIVg",
"version" : {
"number" : "7.10.1",
"build_flavor" : "default",
"build_type" : "docker",
"build_hash" : "1c34507e66d7db1211f66f3513706fdf548736aa",
"build_date" : "2020-12-05T01:00:33.671820Z",
"build_snapshot" : false,
"lucene_version" : "8.7.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
[Storage.Elasticsearch]
Address = "http://127.0.0.1:9200"
Index = "huatuo_bamai"
Username = "elastic"
Password = "123456"
4. Start huatuo-bamai
Use --config-dir to specify the directory containing the configuration:
./_output/bin/huatuo-bamai --region dev --config-dir .
Generate the target event in a test environment, then query records for the corresponding node and time. A local file confirms only a local write; verify remote writes by querying Elasticsearch:
curl -k -u elastic:123456 \
-X GET "http://localhost:9200/huatuo_bamai/_search?pretty" \
-H "Content-Type: application/json" \
-d '{"query": {"match_all": {}}}'
Or:
curl -k -u elastic:123456 \
-X GET "http://localhost:9200/huatuo_bamai/_count?pretty"
Verification and Troubleshooting
- Check service health first, then query event records for the target node and time range.
- A higher index count does not necessarily come from the current collection. Check
hostname, tracer_name, and time fields.
- No records may exist until the target event occurs. Check collection conditions before storage logs.
- Both local and remote writes can fail. Local records are also subject to rotation and retention limits and are not guaranteed to persist indefinitely.
See Storage Interfaces for bulk writes, retries, queries, and failure semantics.
6.2 - Data Sources
Prometheus scrapes metrics exposed by HUATUO, and Elasticsearch stores event data. This guide covers data sources and dashboards for Docker Compose and Kubernetes deployments.
Do not run Docker Compose, systemd, and Kubernetes instances of huatuo-bamai on the same node at the same time. They compete for port 19704 and /var/run/huatuo-toolstream.sock.
Docker Compose
build/docker/ provides preconfigured Prometheus, Elasticsearch, Grafana, and HUATUO components.
export ELASTIC_PASSWORD=huatuo-bamai
docker compose --project-directory ./build/docker up -d
Services use host networking:
| Service |
Address |
Purpose |
| Elasticsearch |
http://localhost:9200 |
Event storage |
| Prometheus |
http://localhost:9090 |
Metric collection |
| Grafana |
http://localhost:3000 |
Visualization |
| huatuo-apiserver |
http://localhost:12740 |
Profiling/Tracing task APIs and flame graph queries |
| huatuo-bamai |
http://localhost:19704 |
Metric and event collection |
Grafana’s default credentials are admin/admin. Change the password immediately after the first login.
Data sources are loaded automatically from build/docker/grafana/datasources/:
| Name |
Type |
UID |
huatuo-bamai-prom |
Prometheus |
huatuo-bamai-prom |
huatuo-bamai-es |
Elasticsearch |
huatuo-bamai-es |
huatuo-bamai-infinity |
Infinity |
huatuo-bamai-infinity-auto-flamegraph |
huatuo-apiserver-pyroscope |
Pyroscope |
huatuo-apiserver-pyroscope |
Dashboards are loaded automatically from build/docker/grafana/dashboards/:
- Metric dashboard (host)
- Metric dashboard (container)
- Disk IO dashboard (continuous monitoring)
- HuaTuo root-cause analysis AutoTracing
- Continuous Profiling (host)
- Continuous Profiling (container)
- AutoTracing Flame Redirect
Docker Compose requires no manual data source configuration or dashboard import.
Kubernetes
Prometheus can scrape HUATUO metrics through Pod annotations or a ServiceMonitor. Choose one method to avoid duplicate collection.
Pod Annotations
build/huatuo-daemonset.minimal.yaml includes these annotations by default:
template:
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "19704"
prometheus.io/path: "/metrics"
The Helm chart generates annotations from the following settings in build/charts/values.yaml:
metrics:
enabled: true
port: 19704
path: /metrics
Enable Kubernetes Pod service discovery in Prometheus and use relabeling to read the annotations:
scrape_configs:
- job_name: k8s-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
- source_labels:
[__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
regex: (.+)
target_label: __metrics_path__
- source_labels: [__meta_kubernetes_namespace]
action: replace
target_label: kubernetes_namespace
- source_labels: [__meta_kubernetes_pod_name]
action: replace
target_label: kubernetes_pod_name
ServiceMonitor
ServiceMonitor requires a cluster with Prometheus Operator and the ServiceMonitor CRD installed. This example assumes both the Helm release and namespace are named huatuo. If your names differ, update the namespace and app.kubernetes.io/instance label accordingly.
Create huatuo-service.yaml:
apiVersion: v1
kind: Service
metadata:
name: huatuo
namespace: huatuo
labels:
app.kubernetes.io/name: huatuo
app.kubernetes.io/instance: huatuo
spec:
clusterIP: None
selector:
app.kubernetes.io/name: huatuo
app.kubernetes.io/instance: huatuo
ports:
- name: metrics
port: 19704
targetPort: 19704
protocol: TCP
Create huatuo-servicemonitor.yaml:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: huatuo
namespace: huatuo
labels:
release: prometheus
spec:
namespaceSelector:
matchNames:
- huatuo
selector:
matchLabels:
app.kubernetes.io/name: huatuo
app.kubernetes.io/instance: huatuo
endpoints:
- port: metrics
path: /metrics
interval: 30s
scrapeTimeout: 10s
release: prometheus must match the Prometheus instance’s spec.serviceMonitorSelector. Different Prometheus Operator installations may use different labels.
With build/huatuo-daemonset.minimal.yaml, Pods use the label app: huatuo. Change the Service’s spec.selector to:
ServiceMonitor selects the Service’s metadata.labels, not Pod labels.
Apply the configuration:
kubectl apply -f huatuo-service.yaml
kubectl apply -f huatuo-servicemonitor.yaml
Grafana Data Sources
Without Docker Compose, add the data sources manually in Grafana.
Prometheus
- URL:
http://<prometheus-host>:9090
- Access:Server (proxy)
- UID:
huatuo-bamai-prom
Elasticsearch
- URL:
http://<elasticsearch-host>:9200
- Authentication:Basic Authentication
- Username:
elastic
- Password:
<password>
- Index name:
huatuo_bamai*
- Time field name:
uploaded_timestamp
- UID:
huatuo-bamai-es
See build/docker/grafana/datasources/ for provisioning examples.
Import Dashboards
Docker Compose loads the repository’s dashboards automatically. For an external Grafana instance:
- Open Dashboards -> Import in Grafana.
- Upload or paste
build/docker/grafana/dashboards/*.json.
- Click Load.
- Select the
huatuo-bamai-prom and huatuo-bamai-es data sources.
- Click Import.
You can also export dashboards from the HUATUO console:
- Visit
http://console.huatuo.tech/dashboards.
- Log in and select a dashboard.
- Click Export -> Export as JSON.
- Select “Export the dashboard to use in another instance”.
- Copy the JSON and import it into the target Grafana instance.
Console credentials are provided by the deployment administrator and should not be stored in public documentation.
6.3 - Kernel Event Subscription
Overview
/v1/events/watch is HUATUO’s real-time kernel event subscription interface. A client opens one persistent HTTP POST connection to receive abnormal kernel events from a node. Events use CloudEvents 1.0 envelopes and are delivered through Server-Sent Events (SSE).
Use Cases
| Goal |
Approach |
| Integrate with alerting or diagnostic platforms |
Subscribe by node, namespace, and event type; assess impact alongside application metrics |
| Record a timeline of anomalies |
Write events to a message queue or storage for later queries |
| Validate test scenarios |
Observe target events and context during load tests or fault injection |
Subscription results are diagnostic evidence. They do not guarantee coverage of every anomaly and cannot alone justify restarts, isolation, or scaling.
Server Configuration
Configure event streaming in the [HTTPServer] section of the HUATUO configuration:
[HTTPServer]
# Maximum concurrent clients; new connections above this limit receive HTTP 429
# Default: 100
MaxEventStreamClients = 100
# SSE heartbeat interval in seconds, preventing proxy/load-balancer idle timeouts
# Close a client connection after 3 consecutive heartbeat write failures
# Default: 30
EventStreamKeepAliveIntervalSeconds = 30
| Setting |
Default |
Description |
MaxEventStreamClients |
100 |
Maximum persistent /v1/events/watch connections; excess connections receive HTTP 429 |
EventStreamKeepAliveIntervalSeconds |
30 |
Heartbeat interval; keep it below the upstream proxy’s idle timeout |
Subscription API
Endpoint
Authorization: Bearer <node-token>
Content-Type: application/json
Request Body
{
"filters": {
"tracer_name": "<regex>",
"hostname": "<regex>",
"container_id": "<regex>",
"container_type": "<regex>",
"container_name": "<regex>",
"container_hostname": "<regex>",
"container_namespace": "<regex>",
"container_qos": "<regex>",
"region": "<regex>"
}
}
Filter fields:
| Field |
Type |
Required |
Description |
tracer_name |
string |
No |
Filter by collector name; supports regular expressions |
hostname |
string |
No |
Filter by node hostname; supports regular expressions |
container_id |
string |
No |
Filter by the full runtime container ID; supports regular expressions |
container_type |
string |
No |
Filter by container classification, such as normal, sidecar, or daemonSet; supports regular expressions |
container_name |
string |
No |
Filter by container name; supports regular expressions |
container_hostname |
string |
No |
Filter by container hostname; supports regular expressions |
container_namespace |
string |
No |
Filter by container namespace; supports regular expressions |
container_qos |
string |
No |
Filter by container QoS; supports regular expressions |
region |
string |
No |
Filter by region; supports regular expressions |
- All filter fields are optional; omitted or empty fields match all values.
- Regular expressions can match a substring of the field value. Use
^ and $ for an exact match. For example, select an instance and classification with "container_id": "^<full-container-id>$" and "container_type": "^normal$", replacing <full-container-id> with the full container ID.
- Multiple fields must all match (AND semantics).
- Filters run on the server; only matching events are delivered.
After establishing the connection, the server continuously sends SSE events:
data: {"specversion":"1.0","id":"...","source":"/huatuo/node-1/memory_oom_kill",...}\n\n
The server also sends periodic heartbeat comment lines to keep the connection alive:
curl Examples
Subscribe to All Kernel Events
curl -s -N -X POST http://<node-ip>:19704/v1/events/watch \
-H "Authorization: Bearer <node-token>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Cache-Control: no-cache" \
-H "Connection: keep-alive" \
-d '{}'
Subscribe to OOM Events
curl -s -N -X POST http://<node-ip>:19704/v1/events/watch \
-H "Authorization: Bearer <node-token>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Cache-Control: no-cache" \
-H "Connection: keep-alive" \
-d '{"filters": {"tracer_name": "^memory_oom_kill$"}}'
Subscribe to Network Events on a Node
curl -s -N -X POST http://<node-ip>:19704/v1/events/watch \
-H "Authorization: Bearer <node-token>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Cache-Control: no-cache" \
-H "Connection: keep-alive" \
-d '{
"filters": {
"hostname": "^node-1$",
"tracer_name": "netdev|dropwatch|net_rx_latency"
}
}'
Subscribe to Container Events in the prod Namespace
curl -s -N -X POST http://<node-ip>:19704/v1/events/watch \
-H "Authorization: Bearer <node-token>" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-H "Cache-Control: no-cache" \
-H "Connection: keep-alive" \
-d '{
"filters": {
"container_namespace": "^prod$"
}
}'
Note: -N disables curl buffering so SSE events appear immediately in the terminal.
CloudEvents Fields
Each delivered event is a JSON object conforming to CloudEvents 1.0:
| Field |
Type |
Description |
specversion |
string |
Always "1.0" |
id |
string |
Unique event ID (UUID v4), generated independently for each event |
source |
string |
Event source path: /huatuo/{hostname}/{tracer_name} |
type |
string |
Always "tech.huatuo.kernel.event" |
datacontenttype |
string |
Always "application/json" |
time |
string |
Event collection time (RFC 3339, nanosecond precision, UTC) |
data |
object |
Event body, the WatchEventData structure |
Event Data
The data field contains a standard HUATUO event record:
{
"specversion": "1.0",
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"source": "/huatuo/node-1/memory_oom_kill",
"type": "tech.huatuo.kernel.event",
"datacontenttype": "application/json",
"time": "2026-05-18T10:23:45.123456789Z",
"data": {
"hostname": "node-1",
"region": "cn-beijing",
"observed_timestamp": "2026-05-18T10:23:45Z",
"tracer_name": "memory_oom_kill",
"tracer_id": "abc123",
"tracer_run_type": "auto",
"container_id": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
"container_name": "app",
"container_hostname": "app-pod",
"container_namespace": "prod",
"container_type": "normal",
"container_qos": "guaranteed"
}
}
WatchEventData fields:
| Field |
Type |
Description |
hostname |
string |
Node hostname |
region |
string |
Node region |
observed_timestamp |
string |
UTC time when the producer observes the event in user space |
kernel_observed_timestamp |
string |
Optional kernel observation time in UTC |
tracer_name |
string |
Collector that triggered the event (see the event types below) |
tracer_id |
string |
Unique event instance ID |
tracer_run_type |
string |
Collection mode: auto (automatically triggered) or manual |
container_id |
string |
Container ID, present for container-level events |
container_name |
string |
Container name |
container_hostname |
string |
Container hostname |
container_namespace |
string |
Container namespace |
container_type |
string |
Container classification, such as normal, sidecar, or daemonSet |
container_qos |
string |
Container QoS class |
Event Types
tracer_name |
Description |
memory_oom_kill |
Out-of-memory (OOM Killer) events |
hungtask |
Kernel detection of tasks in prolonged D state |
softlockup |
CPU soft lockup detection |
ras |
Hardware reliability (RAS) errors, such as ECC memory errors |
dropwatch |
Kernel packet drop events |
netdev_events |
Network device state changes, such as Link Up/Down |
netdev_txqueue_timeout |
Network device transmit queue timeouts |
netdev_bonding_lacp |
Bond device LACP protocol anomalies |
net_rx_latency |
Abnormal network receive latency |
sched_tick |
Abnormal scheduling tick intervals |
memory_reclaim_events |
Memory reclaim anomalies |
cpuidle |
Abnormal CPU idle utilization (triggered by AutoTracing) |
cpusys |
Abnormal system-mode CPU utilization (triggered by AutoTracing) |
dload |
Abnormal system load (triggered by AutoTracing) |
iotracing |
Abnormal I/O latency (triggered by AutoTracing) |
blk_device_health |
Block, NVMe, SCSI, and MD health events |
memburst |
Memory usage bursts (triggered by AutoTracing) |
Go Client
POST /v1/events/watch is included in the Node OpenAPI contract. This example uses the generated request types, event types, and client directly.
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"
nodeapi "github.com/ccfos/huatuo/apis/v1/node"
)
func watchEvents(
ctx context.Context,
baseURL string,
token string,
filters nodeapi.WatchEventFilters,
) error {
client, err := nodeapi.NewClient(
baseURL,
nodeapi.WithHTTPClient(&http.Client{}),
nodeapi.WithRequestEditorFn(func(_ context.Context, request *http.Request) error {
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Accept", "text/event-stream")
return nil
}),
)
if err != nil {
return fmt.Errorf("create Node API client: %w", err)
}
resp, err := client.WatchEvents(ctx, nodeapi.WatchEventsJSONRequestBody{
Filters: &filters,
})
if err != nil {
return fmt.Errorf("connect: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
// Skip heartbeat comments and empty lines.
if line == "" || strings.HasPrefix(line, ":") {
continue
}
// SSE data line format: `data: <json>`
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var event nodeapi.WatchEvent
if err := json.Unmarshal([]byte(data), &event); err != nil {
slog.Warn("parse event", "err", err)
continue
}
fmt.Printf(
"[%s] source=%s id=%s\n",
event.Time.Format(time.RFC3339Nano),
event.Source,
event.ID.String(),
)
fmt.Printf(" data: %+v\n", event.Data)
}
return scanner.Err()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
tracerName := "memory_oom_kill|hungtask|softlockup"
err := watchEvents(ctx, "http://192.168.1.10:19704", "node-token", nodeapi.WatchEventFilters{
TracerName: &tracerName,
})
if err != nil {
slog.Error("watch events", "err", err)
os.Exit(1)
}
}
Choose a Streaming Client
Use the generated Client.WatchEvents method to obtain an http.Response directly. Do not use ClientWithResponses.WatchEventsWithResponse for this endpoint: it reads the response body until EOF, while an SSE connection normally remains open until the caller cancels its context.
Reconnect After Disconnection
Network interruptions or service restarts can disconnect clients in production. Add reconnection logic with exponential backoff:
func watchWithRetry(
ctx context.Context,
baseURL string,
token string,
filters nodeapi.WatchEventFilters,
) {
backoff := time.Second
for {
if err := watchEvents(ctx, baseURL, token, filters); err != nil {
if ctx.Err() != nil {
return
}
slog.Warn("disconnected, retrying", "err", err, "backoff", backoff)
// time.NewTimer + Stop releases timer resources immediately on context cancellation.
timer := time.NewTimer(backoff)
select {
case <-ctx.Done():
timer.Stop()
return
case <-timer.C:
}
if backoff < 30*time.Second {
backoff *= 2
}
}
}
}
How It Works
The client keeps its SSE connection open after the POST request. The node collects kernel events, filters them by subscription, and sends matching events in CloudEvents envelopes without client polling. Heartbeats follow the configured interval. Delivery latency depends on collection, processing, and network conditions.
sequenceDiagram
participant C as Client
participant EW as EventsWatch
participant T as Tracer collection layer
participant K as Linux kernel
C->>EW: POST /v1/events/watch {"filters": {...}}
EW-->>C: 200 OK (Content-Type: text/event-stream)
loop Continuous delivery over SSE
K->>T: Kernel event (memory_oom_kill / hungtask / softlockup ...)
T->>EW: Report raw event
EW->>EW: Match filters
alt Match
EW-->>C: data: {CloudEvents JSON}\n\n
else No match
note over EW: Discard without delivery
end
EW-->>C: : ping (heartbeat at the configured interval)
end
6.4 - Flame Graph Formats
This guide explains collapsed stacks and flame graphs and how to interpret them. See the Profiling Guide for collection, storage, and task completion.
HUATUO’s profiler and irqtracing use the same window formatter. Sample units depend on the collection mode: nanoseconds for CPU time, bytes for memory, and counts for IRQ events. Confirm the mode and unit before interpreting values.
| Goal |
Format |
Notes |
| Aggregate, filter, or render again with scripts |
collapsed |
Each line contains a stack and its sample value |
| Inspect call paths in a browser |
flamegraph, svg |
HUATUO produces SVG with interactive scripts |
| Preserve windows, labels, and full symbols |
json or pprof-compatible data |
Avoids name normalization losses in collapsed stacks |
Collapsed Stacks
Collapsed stacks, also called folded stacks, separate frames with semicolons and separate the stack from its final numeric value with a space:
frame1;frame2;frame3;...;frameN COUNT
| Part |
Meaning |
frame1 |
Root frame, such as main or start_thread |
; |
Frame separator |
frameN |
Leaf frame |
COUNT |
Accumulated sample value for this stack; its unit depends on the collection mode |
Frames run from root to leaf, left to right. Values for identical call paths can be aggregated. Before comparing results, confirm that the collection mode, unit, target, and time range match.
Frame Names
Collapsed stacks have no universal escaping convention. HUATUO replaces ; in frame names with : and carriage returns and newlines with spaces so each stack occupies one line. Internal symbols and structured formats preserve the original names.
For example, generic::<[u8; 7]> becomes generic::<[u8: 7]>. Symbols differing only in ; and : merge. Use a structured format when full symbol fidelity is required.
Numeric Example
This illustrative CPU-time output uses nanoseconds for the final values, not sample counts:
main;handle;read 2000000
main;handle;parse 1000000
The two call paths accumulate 2 ms and 1 ms. In this dataset, handle totals 3 ms and the read path accounts for two-thirds. Interpret memory and IRQ modes in bytes and counts, respectively.
Flame Graphs
| Dimension |
Meaning |
| Horizontal position |
Arrangement of call paths, not chronological order |
| Vertical position |
Call depth, usually with roots at the bottom and leaves at the top |
| Frame width |
Accumulated value and proportion of the selected measurement |
| Frame color |
Defined by the renderer; not directly comparable across tools |
A wider frame has a larger share of the selected measurement. It does not by itself prove a bottleneck or fault cause. Keep workloads and collection conditions comparable when assessing results before and after optimization.
HUATUO’s flamegraph and svg outputs are equivalent: both are SVG with interactive scripts. Use zoom, search, and hover details to locate call paths and inspect values.
First confirm the collection mode and unit, then inspect call paths with large shares and use other observations to assess the cause. Retain collapsed stacks for rendering and aggregation; retain structured results when full symbols, windows, or labels are needed.
6.5 - Packet Drops
Overview
dropwatch is HUATUO’s packet-drop observation tool. It collects software drops through tracepoint/skb/kfree_skb and hardware drops from devlink-capable drivers through raw_tracepoint/devlink_trap_report. Output includes protocol types, IP five-tuples, network devices, drop reasons, and kernel stacks.
dropwatch uses the built-in internal/pcapfilter to compile tcpdump-style expressions. Packets are filtered in the kernel, and only matching events are reported to user space.
It also supports device allowlists and denylists, a global reporting rate limit, and integration with huatuo-bamai to store drop events in Elasticsearch for long-term analysis.
Use Cases
- Filter drops by protocol, address, port, or device to investigate connection problems.
- Use stacks and drop reasons to analyze changes in network latency or throughput.
- Store records in HUATUO and correlate them with resource metrics and application anomalies by time.
Drop records provide observation locations and context, but cannot establish an application’s fault cause alone. Hardware visibility depends on the kernel, driver, and devlink trap configuration; see “Hardware Drops.”
Filter Expressions
Filters support a subset of tcpdump syntax and compile to eBPF bytecode at load time. Only matching packets reach user space.
Supported Expressions
The following filter primitives are supported:
Protocols
ip ip6 tcp udp icmp icmp6 igmp pim esp ah vrrp arp rarp
ip proto tcp ip6 proto udp (protocol names only; numeric protocol IDs are unsupported)
Host addresses
host 10.0.0.1
src host 10.0.0.1
dst host 10.0.0.1
Ports
port 80
src port 443
dst port 8080
Networks (CIDR)
net 10.0.0.0/8
src net 192.168.1.0/24
dst net 172.16.0.0/12
Multicast and Ethernet addresses
ip multicast ip6 multicast multicast ether multicast
ether host 00:11:22:33:44:55
Boolean operators and grouping
tcp and port 80
tcp or udp
not arp
tcp and (port 80 or port 443)
ip and src net 192.168.1.0/24 and tcp dst port 3306
Unsupported Expressions
The following expressions are unsupported and cause compilation failures or incorrect matches:
| Expression |
Reason |
tcp[tcpflags] & tcp-syn != 0, ip[8], tcp[0:4] |
Byte-offset expressions (proto[offset:size]) are not implemented |
ip proto 6, ip6 proto 17 |
Numeric protocol IDs are unsupported; use names such as ip proto tcp |
ether proto 0x0800 |
Hexadecimal EtherTypes are unsupported; use names such as ether proto ip |
sctp |
Unrecognized keyword |
portrange 80-90, tcp portrange 1-100 |
Port ranges are unsupported |
less N, greater N |
Packet-length filtering is unsupported |
ip broadcast, ether broadcast |
Broadcast matching is unsupported |
vlan, mpls, pppoes |
Tunnel/encapsulation keywords are unsupported |
gateway |
Unsupported |
Recommended Examples
# Observe all TCP drops (default; reliable in both L2 and L3 contexts)
--filter "tcp"
# TCP and UDP
--filter "tcp or udp"
# A specific destination host (both TCP and UDP)
--filter "dst host 10.0.0.1"
# A specific port
--filter "tcp and port 443"
# Exclude a noisy host
--filter "tcp and not host 169.254.169.254"
# A specific subnet and port
--filter "src net 192.168.1.0/24 and tcp dst port 3306"
# Observe non-TCP drops (UDP and ICMP only; "not tcp" also captures unknown L3 events)
--filter "udp or icmp"
# Observe ARP drops only (L2 contexts only; never matches in L3)
--filter "arp"
--filter "ip" / --filter "ip6" matches the corresponding IP family, using EtherType in L2 and the version nibble in L3. For a specific transport protocol or host, prefer a narrower tcp, udp, host, or ip proto <name> expression.
Run dropwatch
| Flag |
Default |
Description |
--bpf-path <path> |
Required |
Path to the dropwatch eBPF object |
--filter <expr> |
None |
tcpdump-style filter expression |
--device <names> |
None |
Device allowlist: collect drops only on these comma-separated devices, such as eth0,eth1 |
--device-excluded <names> |
None |
Device denylist; mutually exclusive with --device |
--duration <n> |
0 |
Exit after N seconds; 0 runs until Ctrl-C |
--output <json|text> |
text |
Output format; ignored when --output-storage is set |
--output-storage <path> |
None |
Send events to huatuo-bamai through a Unix socket |
--task-id <id> |
None |
Task ID associated with this session, usually used with --output-storage |
--max-events-per-second <n> |
0 |
Global reporting rate limit; 0 is unlimited. Applied after --device / --filter |
--enable-pprof |
false |
Expose the tool process’s Go runtime profiles on 127.0.0.1:6000. |
--filter and device filters are independent and both apply when specified (AND semantics). Without --device or --device-excluded, all devices are collected. These two flags are mutually exclusive. Allowlists reject SKBs without a net_device; denylists allow them.
At startup, dropwatch detects devlink:devlink_trap_report. If available, it loads both software and hardware drop probes; otherwise it logs a warning and loads only the software probe. Hardware collection also requires the NIC driver to register devlink drop traps and the target trap action to be trap. With action drop, hardware does not provide a packet copy to the CPU, so dropwatch cannot capture it.
pprof is disabled by default. Passing --enable-pprof enables it on 127.0.0.1:6000; an occupied port fails startup. It profiles this tool process, not huatuo-bamai or the traced target.
Hardware Drops
No additional dropwatch flags are needed. First confirm that the kernel, driver, and target trap meet the requirements:
# 1. Confirm that the kernel provides the devlink trap tracepoint
test -e /sys/kernel/tracing/events/devlink/devlink_trap_report/id || \
test -e /sys/kernel/debug/tracing/events/devlink/devlink_trap_report/id
# 2. List devlink devices and driver-registered traps
sudo devlink dev show
sudo devlink trap show <bus/device>
# 3. Enable packet reporting for the target DROP trap
sudo devlink trap set <bus/device> trap <trap-name> action trap
# 4. Start dropwatch and show hardware drops only
sudo dropwatch --bpf-path bpf/net_dropwatch.o --output json 2>/dev/null | \
jq -c 'select(.drop_source == "hardware")'
Use a device identifier returned by devlink dev show for <bus/device>, such as pci/0000:03:00.0. Restore the trap’s previous action after diagnosis.
This capability collects only packets reported by drivers as DEVLINK_TRAP_TYPE_DROP. It does not capture all hardware packets and is not equivalent to NIC hardware drop counters. Drops such as full hardware queues are visible only if the driver implements and reports them as devlink drop traps. Traps of type exception or control are not reported as drop events.
--filter, --device, --device-excluded, and --max-events-per-second apply to both software and hardware events. Text output represents hardware reasons as reason=<group>/<trap> drop_source=hardware; JSON uses separate drop_reason_group, drop_reason, and drop_source fields.
tcpshark --with-dropwatch reuses the same source classification and reason resolution and automatically enables available hardware collection. Successful correlation preserves drop_source, drop_reason, and drop_reason_group. See Retransmission Tracing.
Common Commands
# Text output for TCP drops on all devices
sudo dropwatch --bpf-path bpf/net_dropwatch.o --filter "tcp"
# Observe drops on eth0 only
sudo dropwatch --bpf-path bpf/net_dropwatch.o --device eth0 --output json
# Exclude loopback
sudo dropwatch --bpf-path bpf/net_dropwatch.o --device-excluded lo --output json
# Combine device and protocol filters
sudo dropwatch --bpf-path bpf/net_dropwatch.o --device eth0 --filter "tcp and port 443" --output json
# Collect for 60 seconds, then exit
sudo dropwatch --bpf-path bpf/net_dropwatch.o --filter "tcp and port 443" --duration 60 --output json
# Forward events to a running huatuo-bamai instance
sudo dropwatch --bpf-path bpf/net_dropwatch.o --filter "tcp" --output-storage /var/run/huatuo-toolstream.sock
# Collect JSON for 10 seconds, excluding stacks containing ip_finish_output
sudo dropwatch --output json --duration 10 --bpf-path bpf/net_dropwatch.o | jq -c 'select(.stack | test("ip_finish_output") | not)'
# Collect JSON for 10 seconds and print all fields except stack
sudo dropwatch --output json --duration 10 --bpf-path bpf/net_dropwatch.o | jq -c 'del(.stack)'
jq -c writes each matching event as one JSON line for NDJSON storage or further piping. test("ip_finish_output") matches that regular expression against stack, and not negates the result. The command therefore excludes stacks containing ip_finish_output. Remove | not to retain only those events.
del(.stack) removes stack only from jq output, letting you inspect time, device, process, packet_* metadata, and layers fields. To filter stacks in user space before storage, configure EventTracing.IssuesList in huatuo-bamai (see “huatuo-bamai Integration”).
Event Fields
Each drop event is an NDJSON object (types.DropWatchTracing).
| Field |
Type |
Description |
observed_timestamp |
string |
UTC time generated when user space receives/formats the event (RFC3339Nano), not kernel hook time |
kernel_observed_timestamp |
string |
Kernel observation time in UTC (RFC3339Nano), converted from raw monotonic time |
type |
string |
Reserved TCP event type, currently unset (1 ordinary drop, 2 SYN flood, 3/4 listen overflow) |
drop_source |
string |
software for the kernel protocol stack; hardware for a devlink DROP trap |
drop_reason |
string |
Software: SKB_DROP_REASON_*; if kernel BTF resolution fails, log a warning and fall back to a number. Hardware: devlink trap name |
drop_reason_group |
string |
Devlink trap group for categorizing hardware drops; omitted for software drops |
drop_location |
string |
Hexadecimal kfree_skb call address for software drops; omitted for hardware drops |
source |
string |
tools when dropwatch runs independently; events when started by huatuo-bamai |
comm |
string |
Process name at the time of the drop |
pid |
uint64 |
Process TGID |
container_id |
string |
Container ID resolved by huatuo-bamai (omitempty) |
memory_cgroup_css_addr |
string |
Memory cgroup CSS address for container attribution |
net_namespace_cookie |
uint64 |
Network namespace cookie for container attribution |
net_namespace_inum |
uint32 |
Network namespace inum for container attribution |
netdev_name |
string |
Network device name, such as eth0 |
netdev_ifindex |
uint32 |
Network interface index |
netdev_queue_mapping |
uint32 |
TX queue mapping |
netdev_linkstatus |
[]string |
Network device link flags |
packet_skb_addr |
string |
Hexadecimal SKB address (omitempty) |
packet_eth_proto |
string |
Raw EtherType in hexadecimal, such as 0x0800 |
packet_len_bytes |
uint32 |
Snapshot of kernel skb->len; the logical SKB length may differ from the on-wire frame length |
layers |
object |
Decoded protocol layers; unavailable layers are omitted |
stack |
string |
Kernel stack, separated by newlines |
For hardware events, stack shows where the driver called the devlink trap reporting interface, not the actual discard location inside the ASIC. Investigate hardware causes using drop_reason_group, drop_reason, device details, and driver documentation.
layers represents the protocol stack with fixed fields rather than a separate protocol enum:
| Field |
Description |
layers.label |
Protocol combination, such as IPv4/TCP, IPv6/UDP, ARP, or unknown |
layers.ether |
L2 fields when a real Ethernet header is present: saddr, daddr, type, len; len is nonzero only for IEEE 802.3 framing |
layers.ipv4 |
IPv4 fields: version, ihl, tos, len, id, flags, frag_offset, ttl, protocol, checksum, saddr, daddr |
layers.ipv6 |
IPv6 fields: version, traffic_class, flow_label, len, next_header, hop_limit, saddr, daddr |
layers.tcp |
TCP fields: sport, dport, seq, ack_seq, data_offset, window, checksum, urgent, sk_state |
layers.udp |
UDP fields: sport, dport, len, checksum |
layers.icmp |
ICMP/ICMPv6 fields: type, code, checksum, id, seq; ICMPv6 Echo requests/replies include the identifier and sequence, while other ICMPv6 messages omit them |
layers.arp |
ARP fields: addr_type, protocol, hw_address_size, prot_address_size, operation, sender_mac, sender_ip, target_mac, target_ip |
ICMPv6 Echo Request/Reply (types 128/129) populates id and seq only when all four Echo bytes are captured. If the Echo fields are truncated, common ICMPv6 fields remain and ID/Seq are zero. If the common header is also truncated, the decoded IPv6 layer remains but layers.icmp is absent. Other ICMPv6 message types do not populate Echo fields.
JSON omits zero-valued id and seq independently. Text omits them only when both are zero. Missing output fields therefore cannot distinguish absent or truncated Echo fields from valid zero values.
huatuo-bamai Integration
huatuo-bamai starts dropwatch as a child process. --output-storage sends events to its built-in processing pipeline for eventual Elasticsearch storage. Typical arguments:
dropwatch \
--bpf-path <CoreBpfDir>/net_dropwatch.o \
--output-storage /var/run/huatuo-toolstream.sock \
--filter "tcp"
Configuration
[EventTracing]
# Optional stack filtering. dropwatch discards events whose stacks match configured regexes.
# Default: []
IssuesList = []
[EventTracing.Dropwatch]
# tcpdump filter for standalone dropwatch.
# Default: "tcp"
Filter = "tcp"
# Forwarded to dropwatch --max-events-per-second.
# Default: 100
MaxEventsPerSecond = 100
[EventTracing.TCPRetransmit]
# Use tcpshark's private embedded dropwatch source.
EnableDropwatch = false
Standalone dropwatch always outputs raw DropWatchTracing. Local TCP retransmission correlation loads a separate net_dropwatch.o; both inputs use EventTracing.TCPRetransmit.Filter and output only finalized TCPRetransmitTracing results. Both modes can run concurrently. Embedded drops are not also saved as raw events.
Noise Filtering
Stack noise filtering is disabled by default. huatuo-bamai discards matching events only after EventTracing.IssuesList is configured. The following patterns are candidates for operator configuration; verify them against the local kernel and workload before enabling them:
| Pattern |
Stack Frame Prefix |
Reason |
| ARP/neighbor entry expiry |
neigh_invalidate/ |
Cleanup of expired neighbor entries without affecting active flows. Remove the corresponding EventTracing.IssuesList rule to disable filtering. |
| bnxt NIC TX completion |
bnxt_tx_int/ or __bnxt_tx_int/ |
The Broadcom bnxt driver calls kfree_skb after DMA transmission completes. This is normal cleanup, not a packet drop. |
6.6 - Retransmission Tracing
Overview
tcpshark --mode retransmit observes TCP retransmission activity through the kernel tracepoints tcp/tcp_retransmit_skb and tcp/tcp_retransmit_synack. Explicitly enabling TLP also attaches a tcp_send_loss_probe kprobe. Depending on the event type, records can include IP four-tuples, TCP state, congestion-control state, retransmission counters, sequence information, and socket metadata for container attribution.
The user-space classifier derives connection phases and reason labels from the event type, sk_state, ca_state, and reordering counters. These labels are operational heuristics, not conclusive evidence of a packet-drop cause.
internal/pcapfilter compiles filters at load time for execution in the kernel. With or without local correlation, the SKB, SYN-ACK, and TLP hooks filter the same synthetic L3 TCP packet representation. Protocol, address, network, and port conditions are supported; Ethernet addresses, payloads, actual packet lengths, IP/TCP options, and raw byte-offset semantics are not. Safe EtherType checks such as ether proto ip are translated into L3 checks. A pair of IPv4-mapped IPv6 socket addresses is filtered as IPv4; the raw perf record retains AF_INET6, and user space normalizes addresses before matching. Local correlation applies the identical expression to embedded dropwatch. Use a direction-symmetric expression to retain reverse ACK or SYN-ACK evidence.
Use Cases
Retransmission Diagnosis
Observe RTO, fast retransmission, reordering-related retransmission, and TLP events over time to identify abnormal retransmissions during connection establishment, data transfer, and closure. These observations help investigate packet loss, congestion, reordering, or unreachable peers.
Container Networking
Use container IDs, network namespaces, and socket cgroup metadata to locate affected workloads. Focus on a service with --filter "tcp and port <service-port>" to reduce interference from other host connections.
Latency and Throughput
Align retransmission events with application latency, error rates, and throughput to determine whether RTOs or repeated retransmissions coincide with degraded performance. This helps distinguish slower application processing from network anomalies.
Drop Correlation
Local mode correlates retransmissions and drops within one tcpshark process. Matching checks network namespace, tuple direction, TCP sequence or ACK evidence, and kernel monotonic time ordering. A strict match identifies drop evidence satisfying all correlation conditions; its software or hardware source comes from the record. No match remains unknown, because source readiness does not prove that earlier causal history was observed.
Run tcpshark
tcpshark --mode retransmit [flags]
| Flag |
Default |
Description |
--mode retransmit |
Required |
Select TCP retransmission tracing. |
--enable-tlp, --tlp |
Disabled |
Also attach tcp_send_loss_probe and emit TLP events. |
--bpf-path <path> |
Required without correlation |
Path to a single tcp_retransmit.o file. |
--bpf-path-dir <dir> |
Required with correlation |
Directory containing both tcp_retransmit.o and net_dropwatch.o. |
--with-dropwatch |
Disabled |
Load embedded dropwatch and correlate its events with retransmissions. |
--filter <expr> |
None |
L3-compatible tcpdump-style filter shared by the three retransmission hooks and, in local mode, embedded dropwatch; see “Filter Expressions.” |
--device <names> |
None |
Comma-separated device allowlist, as in dropwatch; filters embedded dropwatch only and requires --with-dropwatch. |
--device-excluded <names> |
None |
Device denylist, mutually exclusive with --device; requires --with-dropwatch. |
--duration <n> |
0 |
Exit after N seconds; 0 runs until Ctrl-C. |
--max-events-per-second <n> |
0 |
BPF event rate limit; 0 is unlimited. |
--enable-pprof |
false |
Expose the tool process’s Go runtime profiles on 127.0.0.1:6000. |
--output <json|text> |
text |
Output format; ignored when --output-storage is set. |
--output-storage <path> |
None |
Send events to huatuo-bamai through a Unix socket. |
--task-id <id> |
None |
Task ID for the toolstream session; must be used with --output-storage. |
If both --output and --output-storage are explicitly set, --output is ignored and a warning is printed.
pprof is disabled by default. Passing --enable-pprof enables it on 127.0.0.1:6000; an occupied port fails startup. It profiles this tool process, not huatuo-bamai or the traced target.
Common Commands
# Emit all retransmission-related events as text
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o
# Emit NDJSON
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o --output json
# Filter ordinary retransmission SKBs by destination host and port in BPF
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o --filter "dst host 10.0.0.1 and dst port 443"
# Local correlation: both BPF inputs use the same direction-symmetric filter
sudo tcpshark --mode retransmit --with-dropwatch --bpf-path-dir bpf \
--filter "tcp and port 443"
# Include Tail Loss Probe events (disabled by default)
sudo tcpshark --mode retransmit --enable-tlp --bpf-path bpf/tcp_retransmit.o
# Emit at most 100 events per second; log rate limit hit when exceeded
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o \
--max-events-per-second 100
# Filter all formatted event types in user space, retaining destination port 443
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o --output json \
| jq -c 'select(.tcp_dport == 443)'
# Run for 60 seconds and retain only events classified as RTO
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o --duration 60 --output json \
| jq -c 'select(.tcp_reason == "RTO")'
# Forward events to a running huatuo-bamai instance
sudo tcpshark --mode retransmit --bpf-path bpf/tcp_retransmit.o \
--output-storage /var/run/huatuo-toolstream.sock
jq -c emits each result as one JSON line for NDJSON storage or further piping.
huatuo-bamai Integration
tcpshark and dropwatch share the same --output-storage and toolstream flow. See the dropwatch guide for general storage setup. TCP retransmission tracing adds these settings:
[EventTracing.TCPRetransmit]
# Used by tcpshark in both modes; empty by default.
Filter = ""
# When true, pass tcpshark --enable-tlp; default: false.
EnableTLP = false
# Use embedded dropwatch; default: false.
EnableDropwatch = false
# Passed to tcpshark --max-events-per-second; default: 100, 0 means unlimited.
MaxEventsPerSecond = 100
EventTracing.TCPRetransmit.Filter controls retransmission collection in both modes. With local correlation disabled, an empty value omits --filter. With correlation enabled, the normalized expression goes to both tcpshark inputs; an empty value becomes tcp. EventTracing.Dropwatch.Filter remains independent and controls only standalone dropwatch.
The tcp_retransmit tracer is in the global BlackList by default. Remove it and restart huatuo-bamai to enable it. Local correlation uses a private dropwatch source, so standalone dropwatch can remain blacklisted.
Filter Expressions
tcpshark uses the same tcpdump-style filter expressions as dropwatch. See the dropwatch guide for syntax, limitations, and further examples.
# A specific destination host and port
--filter "dst host 10.0.0.1 and dst port 443"
# Observe bidirectional traffic between two networks
--filter "(src net 10.10.0.0/16 and dst net 10.20.0.0/16) or (src net 10.20.0.0/16 and dst net 10.10.0.0/16)"
In local mode, the same expression must cover both directions. Directional selectors can exclude reverse ACK or SYN-ACK drop evidence, weakening the available evidence.
Local mode rejects primitives depending on Ethernet addresses, such as ether host 02:00:00:00:00:01. ether proto ip and ether proto ip6 are supported because they can be translated into raw-IP version checks.
Event Fields
Each event is an NDJSON object (types.TCPRetransmitTracing). Fields tagged omitempty are omitted when empty or zero.
| Field |
Type |
Description |
observed_timestamp |
string |
UTC time generated when user space receives/formats the event (RFC3339Nano), not kernel hook time. |
kernel_observed_timestamp |
string |
Kernel observation time in UTC (RFC3339Nano), converted from raw monotonic time. |
comm |
string |
Process name in the current kernel execution context; not necessarily the socket owner. |
pid |
uint64 |
TGID of the current execution context; not necessarily the socket owner’s TGID. |
container_id |
string |
Container ID resolved by huatuo-bamai; see “Container ID Resolution.” |
memory_cgroup_css_addr |
string |
Hexadecimal socket memory cgroup CSS address for container attribution. |
net_namespace_cookie |
uint64 |
Socket network namespace cookie for container attribution. |
net_namespace_inum |
uint32 |
Socket network namespace inum for container attribution. |
tcp_saddr |
string |
Source IP address. |
tcp_daddr |
string |
Destination IP address. |
tcp_sport |
uint16 |
Source port. |
tcp_dport |
uint16 |
Destination port. |
tcp_state |
string |
TCP socket state, such as ESTABLISHED, SYN_SENT, or NEW_SYN_RECV. |
phase |
string |
Classification: connect, data, or close. |
tcp_reason |
string |
Classification: RTO, fast_retransmit, TLP, or unknown. |
event_type |
string |
tcp_retransmit_skb, tcp_retransmit_synack, or tcp_send_loss_probe. |
ca_state |
uint8 |
Congestion-control state: 0=Open, 1=Disorder, 2=CWR, 3=Recovery, 4=Loss. |
icsk_retransmits |
uint8 |
Current retransmission counter snapshot. |
icsk_pending |
uint8 |
Raw pending-timer state in inet_connection_sock; see the values below. |
reord_seen |
uint32 |
Cumulative reordering counter for the connection. |
dsack_dups |
uint32 |
Cumulative DSACK duplicate counter. |
tcp_seq |
uint32 |
SKB: TCP_SKB_CB(skb)->seq; TLP: snd_nxt; SYN-ACK: request snt_isn when available. |
tcp_ack_seq |
uint32 |
SKB: tcp_sk(sk)->rcv_nxt; TLP: snd_una; SYN-ACK: request rcv_nxt when available. |
tcp_end_seq |
uint32 |
SKB: TCP_SKB_CB(skb)->end_seq; SYN-ACK: request snt_isn + 1 when available; omitted for TLP. |
tcp_flags |
string |
Rendered TCP flags, such as SYN|ACK or ACK|PSH; from TCP_SKB_CB(skb)->tcp_flags for SKB events, derived from the event type for SYN-ACK, and omitted for TLP. |
skb_addr |
string |
Hexadecimal retransmission-queue SKB pointer; absent for SYN-ACK and TLP events. |
drop_location |
string |
Local correlation classification: software, hardware, or unknown. On a match, equals drop_source; unlike dropwatch, this is not a kernel address. |
drop_source |
string |
Matched drop source: software or hardware; unknown for an unrecognized ABI source; omitted without a match. |
drop_reason |
string |
As in dropwatch: BTF-resolved SKB_DROP_REASON_* for software drops, a decimal number if unresolved, or NOT_SUPPORTED on unsupported older kernels; devlink trap name for hardware drops. |
drop_reason_group |
string |
Devlink trap group, such as l2_drops, for grouping hardware reasons; omitted for software drops and unmatched events. |
correlation_reason |
string |
One terminal state: matched, unsupported, warmup, wait_timeout, queue_full, or interrupted; omitted when correlation is disabled. |
matched_net_namespace |
bool |
A drop with the same namespace was observed in the same TCP flow, independently of packet and time checks. Always true for a strict match; omitted when false. |
drop_perf_status |
object |
Embedded dropwatch cumulative counters for unmatched events. map_counters_available indicates whether map counters are usable; valid reader lost_samples remain available on read failure. |
drop_stack |
string |
Stack of the matched drop; unmatched stacks are not symbolized. |
source |
string |
tools when tcpshark runs independently; events when started by huatuo-bamai. |
icsk_pending is a snapshot of timer state at hook time, not a stable enum of retransmission reasons. TLP classification uses the explicit event_type=tcp_send_loss_probe, not icsk_pending=5.
| Value |
Kernel State |
Meaning |
0 |
None |
No pending transmit-timer event. |
1 |
ICSK_TIME_RETRANS |
Retransmission timeout (RTO) timer. |
2 |
ICSK_TIME_DACK |
Delayed ACK. Modern kernels store this in icsk_ack.pending and use a separate delayed-ACK timer, so it normally does not appear in icsk_pending. |
3 |
ICSK_TIME_PROBE0 |
Zero-window probe timer. |
4 |
Version-dependent |
No longer defined in current mainline kernels. Older kernels used it for Early Retransmit, and earlier kernels for Keepalive. |
5 |
ICSK_TIME_LOSS_PROBE |
Tail Loss Probe (TLP) timer. |
6 |
ICSK_TIME_REO_TIMEOUT |
Reordering timeout, primarily for RACK loss detection. |
Text Output
Text output uses a terminal-readable layout with the same event variables as JSON. Optional variables appear only when nonzero or nonempty, and strings have no JSON quoting or escaping. For compatibility, state, skb, seq, end, ack, flags, ca, retrans, and reason correspond to JSON fields tcp_state, skb_addr, tcp_seq, tcp_end_seq, tcp_ack_seq, tcp_flags, ca_state, icsk_retransmits, and correlation_reason, respectively.
<timestamp> [<phase>/<tcp_reason>] <saddr>:<sport> > <daddr>:<dport> state=<STATE> event_type=<TYPE> [kernel_observed_timestamp=<UTC>] [SYNACK] [skb=<ADDR>] seq=<N> [end=<N>] ack=<N> [flags=<FLAGS>] pid=<N> comm=<COMM> ca=<N> retrans=<N> icsk_pending=<N> [reord_seen=<N>] [dsack_dups=<N>] [container_id=<ID>] [memory_cgroup_css_addr=<ADDR>] [net_namespace_cookie=<N>] [net_namespace_inum=<N>] [drop_location=<LOCATION>] [drop_source=<SOURCE>] [drop_reason=<REASON>] [drop_reason_group=<GROUP>] [reason=<REASON>] [matched_net_namespace=true] [dropwatch_map_counters_available=<true|false> dropwatch_perf_lost=<N> dropwatch_lost_samples=<N> dropwatch_rate_limited=<N>] [source=<SOURCE>]
Example:
2026-07-23T02:14:40.304775546Z [data/RTO] 127.0.0.1:19996 > 127.0.0.1:42128 state=ESTABLISHED event_type=tcp_retransmit_skb kernel_observed_timestamp=2026-07-23T02:14:40.304Z skb=0xffff931c14fdf800 seq=3154974646 end=3154991030 ack=948393597 flags=ACK|PSH pid=1420 comm=kube-apiserver ca=4 retrans=4 icsk_pending=0 net_namespace_inum=4026531992
The example’s pid and comm describe the execution context when the hook runs. Use container_id and socket metadata to attribute the workload.
A nonempty drop_stack appears as indented stack lines after the event line, not as an inline drop_stack= token.
Container ID Resolution
tcpshark cannot access the Pod manager directly. Standalone output usually lacks container_id, but includes socket memcg and network namespace metadata when available. When run through huatuo-bamai, an empty container_id is resolved using memory_cgroup_css_addr, net_namespace_cookie, then net_namespace_inum.
If all lookups fail, the event is still stored with an empty container_id. pid and comm describe the hook execution context and must not be used as a fallback for socket ownership.
Kernel Events and Classification
Attachment Points
| Attachment Point |
Kernel Location |
Event Meaning |
Available Data |
tracepoint tcp/tcp_retransmit_skb |
__tcp_retransmit_skb() |
A retransmission attempt for an SKB in the retransmission queue; tcpshark does not retain the kernel send result. The SKB is headerless, so sequence values come from TCP_SKB_CB(skb) and ACK from tcp_sk(sk)->rcv_nxt. |
SKB pointer, TCP seq/end_seq/ack/flags, socket and CA state, timers, and reordering counters. |
tracepoint tcp/tcp_retransmit_synack |
tcp_rtx_synack() |
tcp_rtx_synack() successfully submitted a passive-open SYN-ACK retransmission. |
Request socket addresses and ports; no retransmission SKB pointer or TCP seq/ack. |
kprobe tcp_send_loss_probe |
tcp_send_loss_probe() |
Preparation of a Tail Loss Probe; collected only with --enable-tlp. |
Socket metadata and snd_nxt/snd_una; no SKB pointer or rendered TCP flags. |
The BPF program uses helpers such as BPF_CORE_READ for CO-RE field access, avoiding recompilation of C source for each supported kernel layout.
Connection Phases
Ordinary SKB events derive their phase from sk_state; SYN-ACK events use a fixed user-space phase.
The TCP three-way handshake illustrates the connect phase and its retransmission observation points:
sequenceDiagram
participant C as Client
participant S as Server
Note over C,S: Initial state: CLOSED / LISTEN
C->>S: ① SYN
Note left of C: SYN_SENT(2)<br/>phase=connect
opt SYN not acknowledged
C-->>S: SYN retransmission<br/>tcp_retransmit_skb
end
Note right of S: SYN_RECV(3) or NEW_SYN_RECV(12)<br/>phase=connect
S->>C: ② SYN + ACK
opt Final ACK not received
S-->>C: SYN-ACK retransmission<br/>tcp_retransmit_synack
end
C->>S: ③ ACK
Note over C,S: ESTABLISHED(1)<br/>Subsequent ordinary data SKB events: phase=data
The three solid lines show the initial handshake packets, which produce no tcpshark events. Only retransmissions in the optional blocks are observed. Active-side SYN retransmissions use tcp_retransmit_skb; passive-side SYN-ACK retransmissions use tcp_retransmit_synack. Both are classified as connect.
Full phase mapping:
| Phase |
Source State or Event |
Description |
connect |
SYN_SENT(2), SYN_RECV(3), NEW_SYN_RECV(12), or tcp_retransmit_synack |
Connection establishment. |
data |
ESTABLISHED(1) or an unrecognized/default state |
Data transfer or default classification. |
close |
FIN_WAIT1(4), FIN_WAIT2(5), TIME_WAIT(6), CLOSE_WAIT(8), LAST_ACK(9), CLOSING(11) |
Connection closure. |
Reason Classification
| Event or Condition |
Reason |
Meaning |
tcp_retransmit_synack |
RTO |
Fixed user-space label for the SYN-ACK retry timer path. |
tcp_send_loss_probe |
TLP |
Fixed user-space label for the optional Tail Loss Probe hook. |
tcp_retransmit_skb, ca_state=4 (Loss) |
RTO |
Socket is currently in TCP_CA_Loss. |
tcp_retransmit_skb, ca_state=3 (Recovery) |
fast_retransmit |
Retransmission on the Recovery path. |
tcp_retransmit_skb, ca_state=0..2, connect/close phase |
RTO |
Phase-based fallback used by the current classifier. |
tcp_retransmit_skb, ca_state=0..2, data phase |
unknown |
The snapshot is insufficient for another label. |
The classifier sees only socket state at hook time and cannot reconstruct the full ACK/drop history. Treat tcp_reason as an aggregation label, not a verified root cause.
Operational Interpretation
No event type can be discarded unconditionally. Prefer thresholds based on rate, proportion, and service impact over filtering solely by event_type or tcp_reason. See the dropwatch guide for huatuo-bamai’s general noise-filtering mechanism.
| Pattern |
Typical Priority |
Guidance |
tcp_reason=RTO |
High |
Investigate sustained increases or RTOs associated with service anomalies; they usually have a larger latency impact than Recovery-path retransmissions. |
tcp_reason=fast_retransmit |
Medium |
Analyze alongside loss, congestion, and SACK/RACK behavior. |
tcp_reason=TLP |
Context-dependent |
This signal is optional; confirm TLP collection is enabled before using it for alerts. |
event_type=tcp_retransmit_synack |
Usually low for a single event |
Repetition may indicate handshake reachability, host egress, firewall, client, or network problems. |
Aggregate alerts by service or connection and account for traffic volume. Small absolute counts on a busy host may be harmless, while bursts on a low-traffic critical service may have a significant impact.
Correlate with dropwatch
With --with-dropwatch, one tcpshark process owns two perf inputs. Retransmissions wait up to 100ms for dropwatch events delivered later to user space. A candidate drop’s kernel monotonic time must precede the retransmission by no more than 1s. The embedded source does not output raw drop documents; an independently enabled standalone dropwatch remains a separate raw event stream.
See Retransmission and Drop Correlation Design for out-of-order reads across perf streams, the 100ms arrival window, the 1s causal window, and limitations of negative evidence.
Like standalone dropwatch, the embedded source automatically detects and enables devlink DROP trap collection (HardwareAuto) without a separate hardware switch. If the tracepoint is unavailable, it logs a warning and continues software collection. Hardware visibility depends on the driver reporting the target DROP trap; see the dropwatch hardware requirements.
--device, --device-excluded, --filter, and --max-events-per-second use the same names as dropwatch. Device allowlists and denylists restrict only embedded dropwatch, for both software and hardware events. Allowlists reject records without device information; denylists allow them. Retransmissions still use the shared L3 filter. Device filtering may reduce available drop evidence.
Matches retain drop_source, drop_reason, and the hardware drop_reason_group. drop_reason describes the observed drop, tcp_reason classifies the retransmission trigger, and correlation_reason is the single outcome of this correlation. Separate diagnostic fields describe observation limits. The BTF reason table loads once per session; failure logs a warning and falls back to numeric software reasons without affecting hardware trap resolution.
# Use dropwatch-compatible device and traffic flags to inspect matched hardware drops
sudo tcpshark --mode retransmit --with-dropwatch --bpf-path-dir bpf \
--device eth0 --filter "tcp and port 443" --output json \
| jq -c 'select(.drop_source == "hardware")'
Hardware drops must meet the same namespace, TCP, and time constraints. Missing namespace or TCP match fields leave the event unmatched; no match does not prove hardware loss. Hardware drop_stack shows the kernel stack when the driver reports a trap, not the discard location inside the ASIC.
When the source enum is unknown, both drop_source and drop_location are unknown. Source is not guessed from the reason or stack; the record still has correlation_reason=matched.
Correlation Results
| Result |
Required Evidence |
Output |
| Forward segment match |
Matching network namespace, address family, direction, four-tuple, monotonic time ordering, and overlapping SYN/data/FIN sequence ranges. |
correlation_reason=matched, drop source, reason, and drop_stack. |
| Reverse ACK match |
Reverse four-tuple in the same namespace, ACK flag, monotonic time ordering, and ACK covering the retransmission sequence end. |
correlation_reason=matched, drop source, reason, and drop_stack. |
| No strict match |
Missing local evidence cannot establish the actual drop location. |
drop_location=unknown, one correlation_reason, and separate diagnostics. |
There are no positive matches based solely on a four-tuple or SKB pointer, across namespaces, or on ambiguous evidence. Before packet and time checks, matched_net_namespace records a same-namespace drop in the same flow in either direction. True does not establish a strict match; full correlation requires correlation_reason=matched. False or omission means no namespace match was observed, not that different namespaces were confirmed. Each matched drop is consumed once; later drops on the same connection can still match. Stacks are symbolized only after a successful match.
Terminal States
Each finalized event has exactly one correlation_reason:
| Value |
Meaning |
matched |
A strict drop match, including a matched record with an unknown source. |
unsupported |
Required event type, namespace, time, or sequence evidence is missing. |
warmup |
The 100ms wait expired without a match, and the retransmission occurred before the embedded source became ready. |
wait_timeout |
The 100ms wait expired without a match, and the retransmission occurred at or after source readiness. This is a correlation timeout, unrelated to TCP RTO. |
queue_full |
The bounded retransmission queue was full and evicted the event before its deadline. |
interrupted |
The correlation loop exited and interrupted an unexpired wait, on either normal stop or failure. |
Expired events are processed before matching and capacity checks. Shutdown uses one timestamp: expired items become warmup or wait_timeout; remaining waits become interrupted. Each event is finalized once and removed from the queue. Undecodable records or drops evicted from the cache do not directly end a retransmission’s correlation.
The single-valued field replaces the former reason array; update tcpshark and its receiver together. Text output uses reason=<value>. The field is omitted when correlation is disabled.
warmup applies only when a wait expires and the retransmission’s kernel time predates source readiness. At or after readiness, expired waits use wait_timeout, including within the first 1s after readiness. The 1s drop-to-retransmission limit constrains candidates, not the warmup period. Processing delays do not change classification. Strict matches, unsupported events, queue eviction, and early interruption retain their own reasons. The terminal state describes observation timing, not the specific cause of a missing match.
matched_net_namespace remains an independent boolean diagnostic for both matched and unmatched results. It can coexist with loss counters and does not change the terminal reason.
On exit, dropwatch perf-ring records not yet delivered to the correlator are not read. Unread trailing drops might otherwise have matched interrupted retransmissions.
Sample Loss and Rate Limiting
Status is read once before each nonempty output batch, including all-matched batches. Unmatched events retain the snapshot:
| Field |
Meaning |
map_counters_available |
Whether both map counters are available; false distinguishes unavailable counters from observed zero values. |
perf_lost |
Cumulative embedded dropwatch events that could not be written to the perf stream; valid only when map counters are available. |
lost_samples |
Samples lost according to user-space PERF_RECORD_LOST records; remains valid on map read failure and is omitted when zero. |
rate_limited |
Cumulative embedded dropwatch events rejected by rate limiting; valid only when map counters are available. |
On status read failure, map_counters_available=false; zero perf_lost and rate_limited mean unavailable, while lost_samples is retained. The batch is written before returning the status error. A write failure stops the batch and preserves both errors. Matched events retain matched and drop metadata without an unmatched-status snapshot.
Counters belong to the current dropwatch instance and reset on reload. Maps and the reader are sampled separately, not atomically. These counters cannot establish why a particular retransmission was unmatched; loss and rate limiting neither append nor replace the correlation reason.
Interpretation and Troubleshooting
| Observation |
Check |
software |
Inspect the matched stack with drop_reason, tuple, direction, sequence, and namespace. |
hardware |
Investigate using drop_reason_group, trap name, and driver documentation; matching is still correlation based on packet evidence. |
unknown with nonzero loss counters |
Narrow the shared filter, increase perf capacity, or adjust embedded dropwatch rate limits, then collect again. |
correlation_reason=wait_timeout |
No strict candidate arrived within 100ms; inspect diagnostic flags and counters. |
correlation_reason=queue_full |
The waiting queue is full; narrow collection scope. |
correlation_reason=interrupted |
Check collection stops or errors; the wait ended early. |
matched_net_namespace=true without a match |
A same-namespace drop was observed in the same flow. Check packet and time conditions; this flag alone is not full correlation. |
correlation_reason=warmup |
The wait expired for a retransmission predating source readiness. Continue collecting later retransmissions; this result cannot exclude earlier drops. |
No drop_location |
off mode. |
huatuo-bamai passes the same normalized EventTracing.TCPRetransmit.Filter to both local-correlation inputs. Consistent scope prevents the sources from observing different traffic, but without a reliable boundary for the start of causal history, no match remains inconclusive.
6.7 - IRQ Tracing
irqtracing collects softirq call stacks on all CPUs or a selected CPU and generates flame graphs. source identifies what triggered the softirq; victim identifies the task directly preempted by it. When ksoftirqd handles the softirq, it is the executor and is not recorded as a victim.
The tool can produce local output independently or be invoked by huatuo-bamai through AutoTracing.IRQTracing. Local output requires no storage backend or configuration file.
Build
The standard project build discovers cmd/irqtracing and compiles bpf/irqtracing.c automatically:
The binary is written to _output/bin/irqtracing and the BPF object to _output/bpf/irqtracing.o. Specify the object with --bpf-path at runtime.
Run
sudo ./_output/bin/irqtracing \
--bpf-path ./_output/bpf/irqtracing.o \
--duration 5 \
--output-format collapsed --output-path irqtracing.folded
The optional --cpu-list traces all CPUs when omitted or empty. Currently only one CPU is supported, for example --cpu-list 1; lists or ranges resolving to multiple CPUs return an unsupported error. The tool attaches only to the irq/softirq_raise and irq/softirq_entry tracepoints. All-CPU mode aggregates sources and directly preempted victims across CPUs; a single CPU ID retains only that CPU’s data. Both modes collect for --duration seconds (default: 3).
The optional --max-events-per-second-per-cpu N limits the total source and victim stack samples collected per tracked CPU per second. Omitting it or setting it to 0 disables the limit. When enabled, N must be between 2 and 8589934590. The per-CPU budget is split as evenly as possible between softirq_raise and softirq_entry; for odd budgets, raise gets the extra sample. In all-CPU mode, the system-wide budget grows with the number of tracked CPUs.
Output
Explicitly specify --output-format. Supported formats are collapsed (the default shown in help), flamegraph, svg, tui, json, and remote-store. Only tui can omit --output-path. Local results go to the specified file, directory, or stdout. With stdout, terminals, redirection, or log systems may retain collected data. A nonexistent path is treated as a new file unless it ends with /, which creates a directory. collapsed emits folded stacks for flame graph tools:
source;source[raiser,NET_RX];raise_softirq_[k] 12
victim;victim[worker(123),NET_RX];work 4
Use --output-format tui in an interactive terminal to explore all collected call stacks after collection. The viewer combines weights for identical stacks by default. Omit --output-path for terminal-only viewing, or specify a local file or directory and press q to save a gob report. Replay the saved file with profiler --tui-report FILE.
Use --output-format flamegraph or --output-format svg to produce an SVG flame graph directly:
sudo ./_output/bin/irqtracing \
--bpf-path ./_output/bpf/irqtracing.o \
--duration 5 \
--output-format flamegraph --output-path irqtracing.svg
The shared collection framework logs a warning when a window contains dropped samples, including the task ID and counts by reason. IRQ logs at warning level or above go to stderr; results go to the specified destination. Failure to write diagnostic logs does not prevent data export.
Remote Storage
To upload a standard profile and dropped-sample counts, use remote-store with a toolstream Unix socket and a unique task ID:
sudo ./_output/bin/irqtracing \
--bpf-path ./_output/bpf/irqtracing.o \
--duration 5 \
--output-format remote-store --output-path /var/run/huatuo-toolstream.sock \
--task-id irq-demo-1
JSON
Use --output-format json --output-path irqtracing.json to save the same window data locally. JSON content:
{
"profile_type": "irqtracing:irq:count:irq:count",
"profile": {
"time_nanos": 1790000000000000000,
"duration_nanos": 3000000000,
"sample_type": [{"type": 1, "unit": 2}],
"string_table": ["", "irq", "count"]
},
"dropped_samples": {"collection": 1234}
}
profile uses pprof format with these sample labels:
| Label |
Meaning |
irq_type |
Currently softirq; hardirq is reserved for future hardware interrupt collection |
irq_vector |
Currently the softirq vector number, as a decimal string without leading zeros |
irq_context |
source is the context at raise; victim is the directly preempted task’s context |
cpu |
Host logical CPU ID at sampling |
pid, comm |
Process ID (TGID) and current task name at sampling; source does not establish business ownership |
Display formats map irq_vector to names such as NET_RX only for irq_type=softirq;
storage and queries retain the numeric string. Kernel frames use the _[k] suffix.
New results replace irq and softirq_vector with irq_context and irq_vector.
Historical data is unchanged; queries for those results still use the original labels.
dropped_samples.collection combines losses from rate limiting and counts-map
write failures without distinguishing their causes. Nonzero values indicate
incomplete results; unreadable counters fail collection. Zero values may be omitted.
aggregation_queue is retained only for historical data compatibility.
--enable-pprof defaults to false. Enable it to listen on 127.0.0.1:6000; an occupied port fails startup. These profiles describe the irqtracing process itself, not IRQ/softIRQ stacks or huatuo-bamai. Keep the tool running throughout collection.
Invocation by huatuo-bamai
When its rules detect a spike or sustained high irq/softirq utilization on a CPU, the daemon’s AutoTracing.IRQTracing tracer invokes the irqtracing binary beside the daemon executable. CoreBinDir is derived from the daemon’s path; in a source build, the tool is _output/bin/irqtracing.
It passes --bpf-path <CoreBpfDir>/irqtracing.o, --cpu-list <cpu>, --duration <RunTracingToolTimeout>, and --max-events-per-second-per-cpu <MaxEventsPerSecond>. MaxEventsPerSecond defaults to 1000, giving raise and entry a default limit of 500/s each.
This path requires Elasticsearch configuration. Tracing local-file storage alone cannot save IRQ profiles. Trigger rules and the triggering CPU’s utilization are recorded in daemon logs.
Results and Compatibility
IRQ results are written to profile_data in profiling storage with tracer_name=irqtracing and tracer_type=profiling. Query them through the profiling API using irqtracing:irq:count:irq:count. Historical tracing documents remain accessible through the original tracing queries and are not rewritten. The old flamedata/nmissed transport format has been removed; protocol version 3 requires the CLI and daemon to be upgraded together.
Completion
A task succeeds only after the profile is queryable, publication succeeds, and the tool receives the daemon’s acknowledgment. Ending data transmission alone, collection failure, or disconnection does not publish a task completion marker. If the acknowledgment is lost, results may already be published; query by task ID to confirm. See Profiling Window Commit for implementation details.
Collect through the API
Use the Profiling API to collect softirq stacks on all CPUs and query tasks and results.
6.8 - Profiling Guide
Overview
This guide covers creating profiling tasks, collecting data with profiler, and querying and interpreting results. See Continuous Profiling for capabilities and use cases.
Quick Start
Use Docker Compose to collect a host CPU profile and view its flame graph in Grafana.
1. Start Services
Follow Docker Deployment to prepare a Linux node, Docker Compose, and build/docker/.env. The example requires curl and jq; the target node should have CPU activity to analyze.
Write the settings below to huatuo-bamai.conf and huatuo-apiserver.conf in the repository root, which Compose mounts. huatuo-bamai writes profiles and huatuo-apiserver queries them; both must connect to the same ES index. Match the ES password to ELASTIC_PASSWORD in .env. Use the same node token in both files; the API token authenticates subsequent requests.
In Grafana’s pyroscope.yaml, configure the Pyroscope and Infinity data sources with the same API token.
In huatuo-bamai.conf:
[HTTPServer.Auth]
BearerToken = "REPLACE_WITH_NODE_TOKEN"
[Storage]
[Storage.Elasticsearch]
Address = "http://127.0.0.1:9200"
Index = "huatuo_bamai"
Username = "elastic"
Password = "huatuo-bamai"
In huatuo-apiserver.conf:
[Agent.Auth]
BearerToken = "REPLACE_WITH_NODE_TOKEN"
[Elasticsearch]
Address = "http://127.0.0.1:9200"
Username = "elastic"
Password = "huatuo-bamai"
Index = "huatuo_bamai"
[Auth]
[[Auth.Users]]
ID = "administrator"
BearerToken = "REPLACE_WITH_RANDOM_HEX"
Admin = true
Run from the repository root:
docker compose --project-directory ./build/docker up
This runs in the foreground. Use another terminal for the remaining steps.
The running components are:
| Service |
Role |
Default Port |
huatuo-bamai |
Collection agent; runs profiler sampling |
19704 |
huatuo-apiserver |
API entry point; creates and dispatches tasks and queries flame graphs |
12740 |
elasticsearch |
Stores profile data in index huatuo_bamai |
9200 |
grafana |
Displays flame graph dashboards |
3000 |
2. Check Services
Confirm the node and API services are accessible:
curl -fsS http://localhost:19704/version | jq .data.name
curl -fsS http://localhost:12740/version | jq .data.name
curl -fsS -u elastic:huatuo-bamai http://localhost:9200/ | jq .cluster_name
The first two checks should return huatuo-bamai and huatuo-apiserver, respectively; the third should return the ES cluster name. These checks establish accessibility only. Step 4 verifies collected results.
Set environment variables for subsequent requests:
API_BASE="http://127.0.0.1:12740"
API_TOKEN="REPLACE_WITH_RANDOM_HEX"
3. Create a Task
This example uses language c (native collection, covering C/C++/Go) to sample the whole host for 30 seconds:
# Use the node hostname reported by huatuo-bamai
TARGET_HOST="REPLACE_WITH_NODE_HOSTNAME"
JOB_ID=$(curl -fsS -X POST \
-H "Authorization: Bearer ${API_TOKEN}" \
-H "Content-Type: application/json" \
-d "{
\"type\": \"cpu\",
\"language\": \"c\",
\"mode\": \"oncpu\",
\"scope\": \"host\",
\"duration_seconds\": 30,
\"hostname\": \"${TARGET_HOST}\"
}" \
"${API_BASE}/v1/profiling" | jq -er .data.request_id)
echo "Job ID: $JOB_ID"
4. Verify Results
Query status using the returned JOB_ID. Collection duration excludes queueing and result submission; use the task status to determine completion:
curl -fsS -H "Authorization: Bearer ${API_TOKEN}" \
"${API_BASE}/v1/profiling/${JOB_ID}" | jq '.data | {status, terminal, result_url}'
Normal completion reports status=terminal and terminal.outcome=completed. If still pending or running, check again later. On failure, use terminal.reason and terminal.message to investigate the node and collection tool.
After the task ends, read one page of its raw results:
curl -fsS -H "Authorization: Bearer ${API_TOKEN}" \
"${API_BASE}/v1/profiling/${JOB_ID}/raw?limit=1&offset=0" | jq .data
A successful response means the result is published. items may be empty, for example if collection produced no valid samples. Do not infer task success from the entire index’s document count. See API Result Queries for error codes and pagination.
5. View the Flame Graph
This example profiles the local host. Open Continuous Profiling, shared by host and container scopes:
Steps:
- Select a time range in the upper-right corner covering the collection period.
- Select Region, the node
hostname, scope host, and this Task ID, then choose process_cpu:cpu:nanoseconds:cpu:nanoseconds as type.
- Inspect aggregated stacks for the task and time range; use Focus block to focus on a frame.
- Choose Both to show the flame graph and function statistics together.

Label filters
The Labels bar below the target variables filters comm, pid, cpu, or extension labels by exact
value. pid is the host TGID. Native on-CPU cpu identifies the sampling CPU;
native off-CPU cpu identifies the original switch-out CPU. Off-CPU also supports
filtering by offcpu_reason; see the sample label reference.
- Click
+ and select a label and value to refresh the flame graph. Conditions use AND.
- Click an existing condition to edit it or its
× to remove it.
- Changing the target, task, or profile type clears conditions. Changing the global time range
preserves them and refreshes suggestions, with warnings for selected values that no longer match.
- Suggestions use the current task, type, time range, and other conditions, excluding the condition
being edited.
Label filters affect only the flame graph; the window timeline is unchanged.
With All containers selected, the task still identifies one target. Physical usage always requires
one task and selects only the latest snapshot.
After the local trial, run docker compose --project-directory ./build/docker down from the repository root to stop and remove these Compose services.
CLI Collection
profiler can collect and produce local results without an API server, Elasticsearch, or Grafana. Replace the example PIDs, container IDs, and tool paths with real targets before running.
Prerequisites
Build the complete artifacts from the repository root:
The binary is _output/bin/profiler. Native collection requires Linux eBPF, perf events, and the project’s built BPF objects. It usually requires root privileges and a kernel.perf_event_paranoid setting that allows sampling. Java requires async-profiler; --tool-path points to a shared tool root containing bin/asprof and lib/libasyncProfiler.so. Python uses py-spy under the same root.
View full help for the current version:
_output/bin/profiler --help
Basic command structure:
sudo _output/bin/profiler \
--type <cpu|memory> \
--language <c|c++|go|java|python> \
--pid <pid> \
--duration 30 \
--aggr-interval 10 \
--output-format flamegraph \
--output-path ./profiles/
--type and --language are required. Java, Python, and native memory collection require exactly one of --pid or --container-id. Native CPU collection can sample the host without a target.
Run container-targeted profiling on the node that hosts the container. Native
profiling resolves the container CSS reference from the local kernel; it does not
need the Node API. The reference contains a CSS address and cgroup ID, both of
which the BPF filter checks against the current cgroup before sampling.
The Node API exposes complete references through cgroup_css_refs for local
consumers; its kernel addresses are not meaningful on another node.
C, C++, and Go
C, C++, and Go use the native eBPF collector; change only --language. On-CPU mode converts samples to CPU time using the sampling frequency and includes resolvable user and kernel stacks.
sudo _output/bin/profiler \
--type cpu \
--language go \
--pid 12345 \
--duration 30 \
--aggr-interval 10 \
--freq 99 \
--output-format flamegraph \
--output-path ./profiles/go-cpu/
Add --thread-group to include worker threads in the same process, or --cpu-list 2,4-7 to restrict CPUs. Native CPU collection also supports container and host scopes:
Native on-CPU collection prefers hardware CPU cycle events and falls back to software CPU clock when the hardware PMU is unavailable. --freq means samples per second with either source. Use --require-hardware-pmu if software-clock fallback would hide CPU time spent with IRQs disabled.
# Collect a specific container
sudo _output/bin/profiler \
--type cpu --language c --container-id <container-id> \
--duration 30 --aggr-interval 10 \
--output-format collapsed --output-path ./profiles/container/
# Collect the host without specifying a PID or container
sudo _output/bin/profiler \
--type cpu --language c \
--duration 30 --aggr-interval 10 \
--output-format flamegraph --output-path ./profiles/host/
Use off-CPU mode to attribute time away from the CPU to the call path that caused the switch-out:
sudo _output/bin/profiler \
--type cpu --language go --pid 12345 --thread-group \
--cpu-mode offcpu --offcpu-phase all \
--cpu-list 2,4-7 \
--offcpu-min-duration-us 1000 \
--duration 30 --aggr-interval 10 \
--output-format flamegraph --output-path ./profiles/go-offcpu/
Off-CPU collection is event-driven and does not use --freq. With --cpu-list, only intervals starting with a switch-out on a target CPU are recorded; later wakeups or switch-ins on other CPUs do not change attribution. Flame graphs use nanosecond values directly and add roots such as off-CPU blocked, scheduling delay (preempted), and scheduling delay (yielded). Phase all accumulates both blocked and runqueue time while displaying them under separate roots.
Native memory collection supports:
--memory-mode |
Measurement |
Use Case |
virtual_alloc |
Virtual address space allocations and their stacks |
Excessive virtual allocation such as mmap, or address-space growth |
physical_alloc |
Physical memory allocated during the collection window |
Page-fault allocation hotspots and allocation-rate analysis |
physical_usage |
Live bytes of physical pages tracked in this collection |
Locate sampled live pages by allocation stack; not full RSS |
Cross-period stack matching, page-free detection, and shutdown data collection for physical_usage still require validation. Results must not be treated as exact physical residency. Read the Live Physical Memory limitations before using this mode.
sudo _output/bin/profiler \
--type memory \
--language c++ \
--memory-mode physical_usage \
--pid 12345 \
--thread-group \
--physical-memory-probability 100 \
--duration 30 \
--aggr-interval 10 \
--output-format flamegraph \
--output-path ./profiles/native-memory/
--physical-memory-probability applies only to physical_alloc and physical_usage. Lower values reduce processing of frequent memory events. physical_alloc estimates allocation volume from the sampling probability. physical_usage counts only tracked pages, without inverse-probability scaling or pages allocated before collection.
Verify the output: Local Results.
Java
Java CPU collection requires async-profiler and supports one PID, a container, or multiple PIDs:
_output/bin/profiler \
--type cpu \
--language java \
--pid 12345,12346 \
--tool-path /opt/huatuo/tools \
--max-concurrent-procs 2 \
--duration 30 \
--aggr-interval 10 \
--freq 99 \
--output-format flamegraph \
--output-path ./profiles/java-cpu/
Java class names use dots, such as java.lang.Thread.run. Allocation object types do not retain color markers for inside/outside TLAB. Objects of the same type in the same stack are combined by bytes. Actual kernel frames retain the _[k] suffix.
Java memory collection supports:
--memory-mode |
Measurement |
Use Case |
object_alloc |
Object allocations and allocation stacks during the window |
High allocation rates, short-lived objects, and sources of GC pressure |
object_usage |
Live objects and their allocation stacks |
Long-lived objects, heap usage, and suspected memory leaks |
_output/bin/profiler \
--type memory \
--language java \
--memory-mode object_usage \
--pid 12345 \
--tool-path /opt/huatuo/tools \
--duration 30 \
--aggr-interval 10 \
--output-format flamegraph \
--output-path ./profiles/java-memory/
For a container target, replace --pid with --container-id <container-id>. If it contains multiple candidate processes, select the executable path with --binary-match-path.
Verify the output: Local Results.
Python
Python currently supports CPU observation only. --aggr-interval must equal --duration, producing one aggregation window per collection. --tool-path points to the shared tool root containing py-spy.
_output/bin/profiler \
--type cpu \
--language python \
--pid 12345,12346 \
--tool-path /opt/huatuo/tools \
--max-concurrent-procs 2 \
--duration 30 \
--aggr-interval 30 \
--freq 99 \
--output-format flamegraph \
--output-path ./profiles/python-cpu/
Verify Local Results
Before collecting, confirm that the target process is running and exercise the requests or operations you want to analyze during collection. Use a separate output directory for this run to avoid mistaking older files for new results.
- Confirm that the command finishes successfully, and check for collection errors, output errors, or sample-loss warnings.
- After a successful Go CPU run with valid samples, check for
profiles/go-cpu/flamegraph_<Unix timestamp>.svg. Use the corresponding output directory for other examples.
- Open the new SVG in a browser, search for expected application functions, and inspect their stacks and values. CPU and wait times use nanoseconds; memory uses bytes. See Flame Graphs for interpretation.
If no file appears, results are empty, or target stacks are missing, check the PID, container, thread, and CPU filters. Confirm that target activity occurred during collection, then check permissions, tool dependencies, and error logs.
A run with no samples may produce no display file; an existing file alone does not prove success or complete data. See Live Physical Memory for empty results when memory allocation and release values cancel out.
Results
| Format |
Output |
When to Use |
collapsed |
perf_<Unix timestamp>.folded; semicolon-separated frames followed by a numeric value |
Scripted searches, comparisons, or rendering with other flame graph tools |
flamegraph |
flamegraph_<Unix timestamp>.svg; SVG with interactive scripts |
Recommended for visual analysis; search, zoom, and inspect frame values in a browser |
svg |
Same interactive SVG as flamegraph |
For callers explicitly requesting SVG; currently equivalent to flamegraph |
tui |
Interactive terminal flame graph with an optional gob report |
Inspect profiles in a terminal and replay saved reports |
json |
One JSON line per collection window; streaming collection may emit multiple lines |
Preserve windows, sample labels, and signed values |
speedscope |
Speedscope profile JSON |
Inspect the profile interactively at speedscope.app or in any Speedscope viewer |
chrometrace |
Chrome tracing JSON |
Load the collection into chrome://tracing or Perfetto; the timeline is synthesised from the sample unit, so it does not preserve the real event order or concurrency |
remote-store |
Uploads pprof-compatible data through a Unix socket without a local flame graph |
HUATUO storage integration; not for offline viewing |
chrometrace only accepts time-based profiles (CPU and off-CPU); --type=memory is rejected. speedscope has no such restriction.
Flame Graphs
A flame graph shows call direction from bottom to top. Rectangle width represents the accumulated value for a stack in the selected measurement. On-CPU widths represent estimated CPU time; off-CPU widths represent blocked or scheduling-wait time. Memory widths represent bytes for the selected memory mode. Horizontal position is not chronological.
Collapsed-stack example:
main;handleRequest;parsePayload 428
main;handleRequest;writeResponse 172
remote-store requires the HUATUO toolstream Unix socket and a nonempty --task-id.
Collection Windows
--duration sets total collection time; --aggr-interval sets the aggregation period. Native CPU, memory, and Java collectors process data periodically; Python outputs once at the end. Window times describe receipt and aggregation intervals, not exact per-sample execution times.
Stacks are aggregated by user stack, kernel stack, and the complete label set. CPU and wait times use nanoseconds; memory uses bytes. comm is only the process command name. Java and Python entry points are stored in java_entry and python_entry labels.
collapsed, flamegraph, svg, and speedscope produce final aggregates after successful collection and clamp negative cumulative sample values to zero with a warning. chrometrace places every window’s stacks on one estimated timeline in arrival order and fails the collection on a negative sample weight instead of clamping it. json preserves each window and signed values. Stored labels do not imply that query APIs support arbitrary label indexing or filtering.
Live Physical Memory
physical_usage measures live bytes of physical pages tracked during this collection. It excludes pages allocated earlier and applies no inverse-probability scaling, so it is not the process’s full RSS.
The remote type is memory:physical_usage:bytes:space:bytes. Each output period stores the current snapshot with zero duration. Queries must specify one Task ID and select only the latest snapshot in the time range. Do not sum snapshots or fall back to an older nonzero result. Grafana scopes the task through a Task ID field.
Local SVG and collapsed stacks show the final accumulated result; JSON retains signed deltas per period. Fully canceled samples still produce a valid empty result. If no samples were ever received, no local display file is created.
Normal shutdown reads the remaining buffered data, but tail completeness in the real sampling path still requires validation. Cross-period stack matching and detection of actual and partial physical-page frees still require validation and improvement. Current results must not be treated as exact physical residency. Memory usage for high-cardinality collection also grows with the number of distinct samples.
Task Completion
After the collection duration or SIGINT (Ctrl+C), the CLI stops collection, reads and delivers final samples, drains the queue, and submits the result. Final processing shares a 30-second budget. Exceeding it, receiving other cancellation signals, or encountering collection or output errors prevents result submission. Resource cleanup still runs; external tool cleanup has its own timeout.
API stop requests abort tasks without publishing a result completion marker. See Stop a Task for result rules. Output is not transactional: windows or local data written before failure may remain.
Remote results receive a completion marker only after remote-store commits them. Raw task-result queries depend on this marker. General flame graph queries do not guarantee exclusion of all incomplete windows, so chart data alone does not prove task success. Upgrade receivers before senders in the remote collection path. Unified windows use application protocol version 3; legacy versions 1/2 support only the older complete pprof payloads.
Sample Loss
Collection loss is recorded under collection in profile_data.metrics.dropped_samples. A full user-space queue waits for aggregation to make space or for the processing context to be canceled, without silently dropping data; aggregation_queue exists only for historical compatibility. physical_usage fails on explicit sample loss; other types may retain loss statistics. Cancellation does not guarantee export of final statistics, so empty results or missing loss fields do not alone prove no loss.
Profiling API
See the Profiling API for task creation, queries, result pagination, and stopping rules.
CLI Parameters
See profiler CLI Parameters for defaults, limits, and applicable modes.
Integration Tests
For reproducible workloads and stack assertions, see Profiling Integration Tests.
6.9 - Standalone SchedBlame
Run SchedBlame independently and record contention diagnostics.
The sched-blame command runs the SchedBlame tracer independently of the Huatuo
daemon. It uses the same target selection, BPF program, attribution, ratio
history, and diagnostics. Anomaly events are appended to a human-readable file;
no Elasticsearch or other storage backend is initialized.
Build
The normal build discovers cmd/sched-blame automatically:
The executable is _output/bin/sched-blame. Use _output/bpf for its BPF
objects, including those required for container discovery. Build these objects
on the target architecture.
If the BPF objects are already built, compile just the command with:
go build -o _output/bin/sched-blame ./cmd/sched-blame
The tracer supports Linux 4.18 through 6.5 with CONFIG_FAIR_GROUP_SCHED=y and
CONFIG_CFS_BANDWIDTH=y. Run with the privileges needed to load BPF and inspect
container cgroups.
Run
sudo ./_output/bin/sched-blame \
--config ./huatuo-bamai.conf \
--bpf-dir ./_output/bpf \
--output-file ./sched-blame-events.log \
--log-debug
The command reads Log, Pod, and AutoTracing from the normal Huatuo TOML
configuration and ignores unrelated sections. Pod settings control kubelet
ports and client certificates exactly as for the daemon. For example:
[Pod]
KubeletReadOnlyPort = 10255
KubeletAuthorizedPort = 10250
KubeletClientCertPath = "/path/client.pem,/path/client-key.pem"
[AutoTracing.SchedBlame]
TargetContainerScope = "normal"
SliceDropPercent = 0
ExternalAnomalyK = 1.0
SliceBatchSize = 128
PerfEventPerCPUBufferBytes = 524288
PerfEventWatermarkBytes = 8192
PerfEventQueueRecords = 8192
PollIntervalMs = 100
--output-file is required. Events include the target identity, external and
internal contention percentages, historical P99, anomaly threshold, runtime,
contention and throttle durations, and the top external competitors.
An unavailable internal percentage is N/A; a valid zero is 0.0000%.
Anomalies require at least 60 valid previous external-ratio samples and a
positive P99 baseline. The event file is therefore not a per-second recording.
Operational logs and highlighted-container diagnostics use the normal Huatuo
logger: stdout by default, or Log.File when configured. Anomaly event data goes
only to the output file. --log-debug enables debug logging.
The command runs until SIGHUP, SIGQUIT, SIGINT, or SIGTERM. Normal shutdown uses
the tracer’s final drain and event-upload queue to finish pending accounting
and file writes.
Options
| Option |
Meaning |
--config PATH |
TOML file; defaults to ../conf/huatuo-bamai.conf relative to the executable directory. |
--bpf-dir PATH |
BPF object directory; defaults to ../bpf relative to the executable directory. |
--output-file PATH |
Required append-only anomaly file. Parent directories are created when needed. |
--highlight-container VALUE |
Overrides HighlightContainer with a container ID, unique prefix, or hostname. |
--ratio-debug-file PATH |
Overrides ExternalRatioDebugFile with a per-second CSV path. |
--log-debug |
Enables debug logs and the configured highlight’s diagnostics. |
--pprof-addr ADDRESS |
Optional HTTP listener for Go runtime profiles; disabled by default. |
Highlighting is optional. When configured, it must resolve at startup to one
container with a usable CPU cgroup. It reserves dense target slot zero and
bypasses the candidate scope and QoS filters. The remaining slots are selected
normally. Without a highlight, all slots remain available for normal selection.
All paths should be supplied through named options. Positional arguments are
rejected.
Ratio Charts
To record ratios and show one container’s debug diagnostics:
sudo ./_output/bin/sched-blame \
--config ./huatuo-bamai.conf --bpf-dir ./_output/bpf \
--output-file ./sched-blame-events.log \
--highlight-container CONTAINER_ID \
--ratio-debug-file ./ratios.csv --log-debug
The CSV records all active targets each second. The highlight also includes
SuperMonitor waitrate when its custom kernel counters are available. Missing
counters produce unavailable SuperMonitor values while SchedBlame continues.
python3 integration/testdata/sched_contention.py chart ratios.csv --html ratios.html
See SchedBlame Analysis for recording and comparison
options.
CPU Profiling
Add --pprof-addr 127.0.0.1:6060 to the command. Capture a text profile with:
curl -o sched-blame.cpu.pprof \
'http://127.0.0.1:6060/debug/pprof/profile?seconds=120'
go tool pprof -top ./_output/bin/sched-blame sched-blame.cpu.pprof
For an interactive browser view:
go tool pprof -http=127.0.0.1:8080 \
./_output/bin/sched-blame sched-blame.cpu.pprof
6.10 - SchedBlame Analysis
Chart and compare CPU scheduling contention measurements.
integration/testdata/sched_contention.py generates interactive HTML charts
from SchedBlame ratio CSV files. It can also record SuperMonitor waitrate from
cgroup v1 counters and compare that recording with the same container’s
SchedBlame measurements.
The script uses only the Python 3 standard library. Open the generated HTML in
Chrome; the browser loads Plotly from its public CDN.
To capture data without starting the daemon, use the
standalone SchedBlame command.
Chart SchedBlame Ratios
Enable recording in the Huatuo configuration:
[AutoTracing.SchedBlame]
ExternalRatioDebugFile = "/tmp/sched-blame-ratios.csv"
Generate a chart from the current CSV format:
python3 integration/testdata/sched_contention.py chart /tmp/sched-blame-ratios.csv \
--html /tmp/sched-blame-ratios.html
The chart has a container selector and shows:
- External contention:
E / (R + E) * 100.
- Internal contention:
I / R * 100.
- Historical external P99 and its anomaly threshold.
- Emitted external anomaly markers.
- Aligned SuperMonitor waitrate when the highlighted container has valid samples.
R is target runtime, E is estimated external contention time, and I is
estimated internally contended runtime. Internal contention overlaps runtime.
Throttle duration does not enter either ratio. An external sample needs
R + E > 0; an internal sample needs R > 0. An unavailable ratio is a gap,
while a valid zero remains a zero. An available historical baseline remains
visible even when the current external sample is invalid.
Charts use UTC+8 and retain nanosecond timestamp precision in the embedded data.
Zoom, pan, use the time-range slider, or click legend entries to select lines.
To connect lines across unavailable samples:
python3 integration/testdata/sched_contention.py chart /tmp/sched-blame-ratios.csv \
--html /tmp/sched-blame-ratios.html --connect-gaps
Large recordings are read in two passes and reduced into time buckets per
container. Each bucket retains its endpoints, external/internal/SuperMonitor
extrema, representative gaps, and its first and last emitted anomaly markers.
--max-buckets controls the number of buckets, not an exact point limit:
python3 integration/testdata/sched_contention.py chart /tmp/sched-blame-ratios.csv \
--html /tmp/sched-blame-ratios.html --max-buckets 8000
The default is 4000 buckets. More buckets preserve more detail at the cost of
larger HTML and greater browser memory use. Container IDs identify series, so
reusing a dense target slot does not combine different containers.
Record SuperMonitor Waitrate
This mode reads a container’s cpu.stat and cpuacct.usage under
/sys/fs/cgroup/cpu,cpuacct. Supply a full container ID or a unique hexadecimal
prefix. The kernel must expose the custom hierarchy_wait_sum, inner_wait_sum,
and throttle_wait_sum counters for valid measurements.
python3 integration/testdata/sched_contention.py record-supermonitor CONTAINER_ID \
--csv /tmp/supermonitor.csv --html /tmp/supermonitor.html \
--duration 600
Sampling defaults to one second; --interval changes it. Omit --duration to
record until Ctrl-C. The HTML is generated when recording stops. Each sample
prints its UTC+8 timestamp and waitrate; -q suppresses normal terminal output.
Missing counters, read failures, counter resets, or zero demand produce N/A
and an empty CSV percentage, with the reason recorded in invalid_reason.
After a failed read, another successful baseline is required before a valid
delta can be calculated.
With deltas between consecutive reads, SuperMonitor uses:
H = delta hierarchy_wait_sum
I = delta inner_wait_sum
TW = delta throttle_wait_sum
R = delta cpuacct.usage
E = H - I - TW
SuperMonitor.waitrate = E / (H + R) * 100
This has a different denominator and task weighting from SchedBlame, so the
comparison is a trend reference rather than an equality check.
Compare Recordings
python3 integration/testdata/sched_contention.py compare \
/tmp/sched-blame-ratios.csv /tmp/supermonitor.csv \
--html /tmp/comparison.html
The two CSV arguments may appear in either order. The script identifies their
formats and selects the full container ID from the SuperMonitor recording.
The SchedBlame recording may contain other containers; only the matching
container is plotted. An unsupported format or missing matching container
produces an error. --max-buckets, --connect-gaps, and -q also apply here.
Tests
python3 -B -m unittest discover -s integration/testdata \
-p 'test_sched_contention.py' -v
7 - Developer Guide
Read the contribution guide before making changes, and prepare the environment using Building from Source.
7.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.
7.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.
7.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.
7.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 |
7.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.
7.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.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.
8 - FAQ
Metrics
-
Why are memory_others_* metrics, such as directstall_time, missing?
The memory_others collector reads memory cgroup extensions provided by DiDi Cloud’s custom kernel: memory.directstall_stat, memory.asynreclaim_stat, and memory.local_direct_reclaim_time. Mainline and common distribution kernels do not provide these interfaces, and no loadable kernel module supplies them. These metrics are therefore expected to be absent on standard kernels.
To observe container direct reclaim on a standard kernel, use the eBPF-based memory_reclaim_container_directstall metric. See Memory Metrics.
9 - Contributing
See the contribution guide to contribute code, documentation, tests, or reviews. See the developer guide for the development environment and testing.
9.1 - Code Contributions
This guide covers the development environment, validation requirements, and contribution workflow. Keep each change focused on one problem so it is easy to review and revert.
Ways to Contribute
You can contribute to HUATUO in several ways:
- Code: fix bugs, add features, or improve performance.
- Documentation: improve documentation, translate content, or write tutorials.
- Testing: write unit and integration tests or report bugs.
- eBPF: add kernel probes or improve kernel compatibility.
- Review: review other contributors’ pull requests.
Development Environment
Prerequisites
| Tool |
Requirement |
Purpose |
| Go |
As specified in go.mod (currently 1.24.3) |
Main implementation language |
| Linux |
Kernel 4.18+ |
Required for eBPF programs |
| Clang/LLVM |
A recent version |
Compile eBPF C programs |
| Docker |
Optional |
Containerized development environment |
| Git |
A recent version |
Version control |
Clone the Repository
# Fork the repository on GitHub first, then:
git clone https://github.com/YOUR_USERNAME/huatuo.git
cd huatuo
git remote add upstream https://github.com/ccfos/huatuo.git
Build and Test
Build
make build # Build BPF programs and Go binaries
make gen-build # Regenerate BPF artifacts and generated Go code
make docker-build # Build the Docker image
Run the Development Stack
Build a development image from the current source and start the collector, API Server, Elasticsearch, Prometheus, and Grafana:
Stop the environment and remove its containers, volumes, and local development image:
Test
make test # Run all tests
make unit # Run unit tests only
make check # Run code style and formatting checks
Note: make test requires /etc/kubernetes/pki for E2E tests. Without a Kubernetes cluster, use make unit.
To test or debug on other distributions without a local VM, see GitHub Actions VM Debugging.
Contribution Workflow
1. Find or Create an Issue
- Browse open issues for bugs and feature requests.
- To work on an unassigned issue, leave a comment asking to take it.
- For a new idea, create an issue to discuss it first.
2. Create a Branch
git checkout -b fix/short-description
# Or: git checkout -b feat/short-description
# Or: git checkout -b docs/short-description
Branch prefixes:
| Prefix |
Purpose |
fix/ |
Bug fixes |
feat/ |
New features |
docs/ |
Documentation |
refactor/ |
Code refactoring |
test/ |
Additional tests |
3. Write Code
- Address one problem at a time.
- Update existing unit tests; add integration tests for components with external dependencies.
- Update documentation when changing configuration, interfaces, storage structures, or features.
- Run
make check to check code style.
- Run
make unit to verify the tests pass.
4. Commit Changes
Use Conventional Commits:
git commit -s -m "fix(scope): short summary
Detailed explanation (optional)
Closes #issue-number
Signed-off-by: Your Name <your.email@example.com>"
The -s flag adds the Signed-off-by line required by the DCO.
5. Push and Open a PR
git push origin your-branch-name
Create a Draft pull request in ccfos/huatuo. When ready, click Ready for review.
6. Code Review
- Maintainers review your PR.
- Address feedback and push new commits.
- You can mark the PR as Draft while revising it, then click Ready for review again.
- Maintainers merge the PR after approval.
Commit Messages
Use type(scope): summary and follow the repository’s AGENTS.md. The body must explain why the change is needed, with no line exceeding 80 characters. Each commit must contain one logical change and no Co-authored-by: trailer.
<type>(<scope>): <description>
Explain why the change is needed (no more than 80 characters per line)
[Optional footer]
Types
| Type |
Description |
fix |
Bug fix |
feat |
New feature |
refactor |
Code restructuring without behavior changes |
Examples
fix(pod): preserve response body read errors in httpDoRequest
feat(bpf): add probe for kernel scheduling latency
fix(docs): clarify development setup requirements
fix(request): cover response body reads after doRequest
Code Style
| Language |
Tool |
| Go |
gofumpt + goimports |
| C (eBPF) |
clang-format (configured in .clang-format) |
| Shell |
shfmt |
| YAML/JSON |
2-space indentation |
Run make check before every commit to verify compliance.
DCO Sign-off
All contributions require a Developer Certificate of Origin (DCO) sign-off.
Each commit must end with:
Signed-off-by: Your Name <your.email@example.com>
Use git commit -s to add it automatically.
The sign-off confirms that you authored the code or have the right to contribute it under the project’s Apache 2.0 license.
- GitHub Issues: report bugs and request features.
- GitHub Discussions: ask questions and share ideas.
- WeChat: scan the QR code in the README to join the group.
10 - Reference
Use these references to look up metrics, record fields, measurement semantics, and interface parameters. See Key Features for capabilities and applicable problems.
| Reference |
Contents |
| Metrics |
Names, units, labels, sources, and measurement semantics |
| AutoTracing Fields |
Trigger metrics, collected results, and JSON examples |
| Abnormal Event Fields |
Event structures, fields, limitations, and compatibility |
| Hardware Event Fields |
RAS counts, severity, registers, and error codes |
| Profiling API |
Task creation, states, result queries, and stopping rules |
| profiler CLI Parameters |
Parameter defaults, limits, and applicable modes |
10.1 - Metrics Reference
This reference lists metric names, units, labels, sources, and measurement semantics. See Kernel-Wide Insight for capabilities and troubleshooting scenarios.
How to Read This Reference
Common metrics are grouped by CPU, memory, network, I/O, system events, and GPU for querying and troubleshooting. Actual output depends on kernel interfaces, device drivers, enabled collectors, and filters. The node’s /metrics output is authoritative for the complete set. See Node Configuration for enablement.
- Names: tables omit the
huatuo_bamai_ prefix. For example, cpu_util_total is exposed as huatuo_bamai_cpu_util_total.
- Labels: all metrics include
hostname and region. Container metrics also include container_id, container_hostname, container_namespace, container_qos, container_name, and container_type. Tables list only additional labels; — means none.
- Counts and units: counts measure events or objects, not latency. Use
rate() or increase() for cumulative Counters. Some cumulative kernel statistics are exported as Gauges; interpret their field semantics rather than inferring from type or name alone.
- Examples: values illustrate output format, not diagnostic thresholds. A missing metric does not mean zero.
# TYPE huatuo_bamai_runqlat_latency counter
huatuo_bamai_runqlat_latency{hostname="hostname",region="dev",zone="0"} 35100
# TYPE huatuo_bamai_runqlat_container_latency counter
huatuo_bamai_runqlat_container_latency{container_id="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",container_hostname="coredns-855c4dd65d-8v5kg",container_namespace="kube-system",container_qos="burstable",container_name="coredns",container_type="normal",hostname="hostname",region="dev",zone="0"} 226
This example shows host and container scheduling-latency bucket counts. The zone ranges are listed below.
Public labels
These fields use the same names and values as the public fields in Elasticsearch documents. Node observations provide region and hostname; container observations also provide the six container fields below.
| Field |
Meaning |
region |
Region configured on the Agent |
hostname |
Hostname of the collection node |
container_id |
Full runtime container ID, distinguishing instances across container recreation |
container_name |
Container name |
container_hostname |
Hostname obtained during container discovery; the default implementation uses the Pod’s spec.hostname or name, and the node hostname for DaemonSets |
container_namespace |
Orchestration namespace; the default implementation uses the Kubernetes Pod namespace |
container_type |
Container classification, such as normal, sidecar, or daemonSet |
container_qos |
Container QoS, such as guaranteed, burstable, or besteffort |
Names, hostnames, and namespaces describe and filter containers; they do not replace container_id as the identity of a container instance. Host observations omit container fields. An empty metric label or an omitted document field represents an unavailable descriptive attribute. Public fields come from the observation target’s metadata and cannot be overridden by additional business labels.
huatuo_bamai_build_info and huatuo_apiserver_build_info are Gauges with a
constant value of 1, describing the running bamai and apiserver builds
respectively. Each is exposed by its application’s /metrics endpoint and
uses the same build information as that application’s /version endpoint.
They carry the existing hostname and region labels (empty for apiserver) and
these build labels:
| Label |
Meaning |
name |
Application name, matching name in /version |
version |
Application release version, matching version in /version |
git_commit |
Build Git identifier, matching git_commit in /version; not necessarily a full SHA |
git_tree_state |
Build working-tree state: clean, dirty, or unknown |
build_time |
Timestamp from /version: injected build time, falling back to VCS commit time or (devel) |
go_version |
Go toolchain version used to build the application |
compiler |
Go compiler, such as gc |
platform |
Operating system and architecture, such as linux/amd64 |
When no release version is supplied, version uses (devel). git_commit
uses the injected identifier first, then the VCS revision from Go build information,
and falls back to (devel) when neither is available.
Build labels apply only to this metric; business metric labels remain unchanged.
After scraping, join build information with business metrics using the same
job and instance. Cross-cluster queries must also include the labels that
distinguish targets between clusters.
CPU
Scheduling Latency
Scheduling latency is the wait from becoming runnable to actually receiving CPU time. These eBPF metrics are cumulative Counters bucketed by zone: 0 = [0, 10) ms, 1 = [10, 20) ms, 2 = [20, 50) ms, and 3 = >=50 ms.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
runqlat_container_latency |
Scheduling-latency bucket count |
Count |
Container |
eBPF |
zone |
runqlat_latency |
Scheduling-latency bucket count |
Count |
Host |
eBPF |
zone |
Softirq Latency
Measures the wait from softirq raise to processing on each CPU. Currently only NET_RX and NET_TX are emitted. This is a cumulative Counter with zone buckets: 0 = [0, 10) μs, 1 = [10, 100) μs, 2 = [100, 1000) μs, and 3 = >=1 ms.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
softirq_latency |
Softirq response-latency bucket count |
Count |
Host |
eBPF |
cpuid, type, zone |
Utilization
Host utilization is normalized by online CPU cores; container utilization by available CPU capacity. Values range from 0 to 100%.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
cpu_util_sys |
Kernel-mode CPU utilization |
% |
Host |
— |
cpu_util_usr |
User-mode CPU utilization |
% |
Host |
— |
cpu_util_total |
Total CPU utilization |
% |
Host |
— |
cpu_util_container_sys |
Kernel-mode CPU utilization |
% |
Container |
— |
cpu_util_container_usr |
User-mode CPU utilization |
% |
Container |
— |
cpu_util_container_total |
Total CPU utilization |
% |
Container |
— |
Available Cores
Container CPU capacity is the smaller of quota-derived cores and the effective CPU set size. Without a quota, it uses the effective CPU set size; if unavailable, it falls back to online host cores.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
cpu_util_container_cores |
Available CPU capacity (may be fractional) |
Cores |
Container |
— |
Throttling and Contention
Throttling statistics come from cgroup CPU interfaces and include only fields provided by the kernel. The wait ratio also requires kernel wait_sum and kernel.sched_schedstats=1.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
cpu_stat_container_nr_throttled |
Cumulative periods in which the cgroup was CPU-throttled |
Count |
Container |
— |
cpu_stat_container_throttled_time |
Cumulative time the cgroup was throttled |
Nanoseconds |
Container |
— |
cpu_stat_container_wait_sum_percent |
Cgroup wait time in the parent run queue as a share of schedulable time during the interval |
% |
Container |
— |
The interval wait ratio is wait-time delta / (wait-time delta + CPU-usage delta) × 100%. It measures waiting as a share of schedulable time, not the share spent throttled.
References:
Burst Usage
Counts periods and time using burst CPU capacity. Emitted only when the kernel provides the corresponding fields.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
cpu_stat_container_burst_time |
Cumulative time using burst CPU capacity |
Nanoseconds |
Container |
— |
cpu_stat_container_nr_bursts |
Cumulative periods using burst CPU capacity |
Count |
Container |
— |
Load
Hosts report 1-, 5-, and 15-minute load averages. Containers report current runnable and uninterruptible task counts, which use a different time basis.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
Notes |
loadavg_load1 |
System load average over the past 1 minute |
Tasks |
Host |
— |
— |
loadavg_load5 |
System load average over the past 5 minutes |
Tasks |
Host |
— |
— |
loadavg_load15 |
System load average over the past 15 minutes |
Tasks |
Host |
— |
— |
loadavg_container_nr_running |
Current runnable tasks, including running tasks and tasks waiting for CPU |
Count |
Container |
— |
cgroup v1 only |
loadavg_container_nr_uninterruptible |
Uninterruptible tasks in the container |
Count |
Container |
— |
cgroup v1 only |
Memory
Reclaim
Memory reclaim and compaction can block tasks. These metrics record host cumulative durations and container direct-reclaim event counts.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
memory_free_allocpages_stall |
Cumulative host direct-reclaim duration |
Milliseconds |
Host |
eBPF |
— |
memory_free_compaction_stall |
Cumulative host memory-compaction duration |
Milliseconds |
Host |
eBPF |
— |
memory_reclaim_container_directstall |
Container direct-reclaim event count |
Count |
Container |
eBPF |
— |
memory_others_container_directstall_time, memory_others_container_asyncreclaim_time, and memory_others_container_local_direct_reclaim_time depend on DiDi custom-kernel interfaces memory.directstall_stat, memory.asynreclaim_stat, and memory.local_direct_reclaim_time.
Mainline and common distribution kernels without these interfaces do not emit the metrics; no additional module is needed. Use memory_reclaim_container_directstall for container direct-reclaim counts on standard kernels.
Memory State
Container fields come from memory.stat; host fields from /proc/vmstat. Both are subject to MetricCollector.Vmstat filters. Field availability and meanings depend on kernel and cgroup versions.
Container memory
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_container_active_file |
Active file memory |
Bytes |
Container |
— |
memory_vmstat_container_active_anon |
Active anonymous memory |
Bytes |
Container |
— |
memory_vmstat_container_inactive_file |
Inactive file memory |
Bytes |
Container |
— |
memory_vmstat_container_inactive_anon |
Inactive anonymous memory |
Bytes |
Container |
— |
memory_vmstat_container_file_dirty |
Modified file memory not yet written to disk |
Bytes |
Container |
— |
memory_vmstat_container_file_writeback |
File memory being written back |
Bytes |
Container |
— |
memory_vmstat_container_dirty |
Modified memory not yet written to disk |
Bytes |
Container |
— |
memory_vmstat_container_writeback |
Memory being written back |
Bytes |
Container |
— |
memory_vmstat_container_pgdeactivate |
Pages moved from the active to inactive LRU |
Pages |
Container |
— |
memory_vmstat_container_pgrefill |
Total pages scanned on the active LRU |
Pages |
Container |
— |
memory_vmstat_container_pgscan_direct |
Total pages scanned on the inactive LRU during direct reclaim |
Pages |
Container |
— |
memory_vmstat_container_pgscan_kswapd |
Total pages scanned on the inactive LRU by kswapd |
Pages |
Container |
— |
memory_vmstat_container_pgsteal_direct |
Total pages reclaimed from the inactive LRU by direct reclaim |
Pages |
Container |
— |
memory_vmstat_container_pgsteal_kswapd |
Total pages reclaimed from the inactive LRU by kswapd |
Pages |
Container |
— |
memory_vmstat_container_unevictable |
Bytes in unevictable pages |
Bytes |
Container |
— |
Host memory
The names below include memory_vmstat_. Underlying values are exported unchanged rather than uniformly converted to bytes. pgpgin and pgpgout use the kernel’s KiB units; see the Linux vmstat implementation.
Page state and LRU
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_nr_free_pages |
Free pages immediately allocatable by the buddy system |
Pages |
Host |
— |
memory_vmstat_nr_inactive_anon |
Inactive anonymous pages |
Pages |
Host |
— |
memory_vmstat_nr_inactive_file |
Inactive file pages |
Pages |
Host |
— |
memory_vmstat_nr_active_anon |
Active anonymous pages |
Pages |
Host |
— |
memory_vmstat_nr_active_file |
Active file pages |
Pages |
Host |
— |
memory_vmstat_nr_unevictable |
Unevictable pages |
Pages |
Host |
— |
memory_vmstat_nr_mlock |
Pages locked by mlock() |
Pages |
Host |
— |
memory_vmstat_nr_shmem |
Pages used by tmpfs/shmem |
Pages |
Host |
— |
memory_vmstat_nr_slab_reclaimable |
Pages used by reclaimable Slab |
Pages |
Host |
— |
memory_vmstat_nr_slab_unreclaimable |
Pages used by unreclaimable Slab |
Pages |
Host |
— |
Dirty pages and writeback
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_nr_dirty |
Current dirty pages |
Pages |
Host |
— |
memory_vmstat_nr_writeback |
Pages being written back |
Pages |
Host |
— |
memory_vmstat_nr_dirty_threshold |
Dirty-page throttling threshold |
Pages |
Host |
— |
memory_vmstat_nr_dirty_background_threshold |
Background writeback threshold |
Pages |
Host |
— |
Page faults and swapping
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_pgfault |
Total page faults |
Count |
Host |
— |
memory_vmstat_pgmajfault |
Major page faults |
Count |
Host |
— |
memory_vmstat_pgpgin |
Data read from block devices |
KiB |
Host |
— |
memory_vmstat_pgpgout |
Data written to block devices |
KiB |
Host |
— |
memory_vmstat_pswpin |
Pages swapped in |
Pages |
Host |
— |
memory_vmstat_pswpout |
Pages swapped out |
Pages |
Host |
— |
Reclaim and scanning
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_pgscan_kswapd |
Pages scanned by kswapd |
Pages |
Host |
— |
memory_vmstat_pgscan_direct |
Pages scanned by direct reclaim |
Pages |
Host |
— |
memory_vmstat_pgscan_khugepaged |
Pages scanned by khugepaged |
Pages |
Host |
— |
memory_vmstat_pgsteal_kswapd |
Pages reclaimed by kswapd |
Pages |
Host |
— |
memory_vmstat_pgsteal_direct |
Pages reclaimed by direct reclaim |
Pages |
Host |
— |
memory_vmstat_pgsteal_khugepaged |
Pages reclaimed by khugepaged |
Pages |
Host |
— |
Transparent Huge Pages (THP)
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_thp_fault_alloc |
Successful THP allocations on page faults |
Count |
Host |
— |
memory_vmstat_thp_fault_fallback |
THP allocation failures on faults that fall back to ordinary pages |
Count |
Host |
— |
memory_vmstat_thp_collapse_alloc |
Successful THP collapses by khugepaged |
Count |
Host |
— |
memory_vmstat_thp_collapse_alloc_failed |
Failed THP collapses by khugepaged |
Count |
Host |
— |
NUMA
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_vmstat_numa_hit |
Pages allocated on the preferred NUMA node |
Pages |
Host |
— |
memory_vmstat_numa_miss |
Pages allocated on this node when another node was preferred |
Pages |
Host |
— |
memory_vmstat_numa_foreign |
Pages allocated elsewhere when this node was preferred |
Pages |
Host |
— |
memory_vmstat_numa_local |
Pages allocated on the current CPU’s NUMA node |
Pages |
Host |
— |
memory_vmstat_numa_other |
Pages allocated outside the current CPU’s NUMA node |
Pages |
Host |
— |
memory_vmstat_numa_pages_migrated |
Total pages successfully migrated by automatic NUMA balancing |
Pages |
Host |
— |
References:
Memory Events
These fields come from memory.events and count reclaim, memory-limit, and OOM events. Mainline kernels provide it in cgroup v2; DiDi custom kernels may also provide it in cgroup v1. Nothing is emitted if the interface is absent. Fields count different conditions and must not be added as independent events.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
memory_events_container_low |
Reclaims under pressure below memory.low, usually indicating overcommitted low-memory protection |
Count |
Container |
— |
memory_events_container_high |
Throttling and direct-reclaim events after exceeding memory.high |
Count |
Container |
— |
memory_events_container_max |
Attempts to exceed memory.max |
Count |
Container |
— |
memory_events_container_oom |
Events where memory reaches the limit, allocation is about to fail, and OOM handling is considered |
Count |
Container |
— |
memory_events_container_oom_kill |
Processes in this cgroup killed by any OOM killer |
Count |
Container |
— |
memory_events_container_oom_group_kill |
Group OOM kill events |
Count |
Container |
— |
Free Memory Blocks
Shows free block counts by NUMA node, memory zone, and order. order=n means each block contains 2^n contiguous pages. The value counts blocks, not pages.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
memory_buddyinfo_blocks |
Free blocks for the specified NUMA node, zone, and order |
Blocks |
Host |
procfs |
node, order, zone |
Container reclaim and compaction stall times
| Metric |
Description |
Unit |
Target |
Source |
Labels |
| memory_free_container_allocpages_stall |
Container task time in global direct reclaim |
milliseconds |
Container |
eBPF |
container_hostname, container_id, container_name, container_namespace, container_qos, container_type, hostname, region |
| memory_free_container_compaction_stall |
Container task time in direct compaction |
milliseconds |
Container |
eBPF |
same container labels |
These cumulative Gauge values measure task time in global direct reclaim and compaction. Host totals include container work. Missing or ambiguous container records are omitted; container collection failures preserve host output. Loading requires the container probes; a load or attachment failure disables this collector. Container recreation starts a new container total without resetting the host total. BPF reload resets both.
Host-wide memcg reclaim count
| Metric |
Description |
Unit |
Target |
Source |
Labels |
| memory_reclaim_directstall |
Cumulative host-wide memcg limit reclaim events |
count |
Host |
eBPF |
host, region |
This Gauge counts host-wide memcg reclaim events, excluding kswapd; it is not a global reclaim count or duration. Host totals include container activity and must not be added to container counts. BPF reload resets the total.
Network
TCP Memory
Reports TCP memory usage and its proportion of the limit.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
tcp_memory_limit_pages |
Total allowed TCP memory |
Pages |
Host |
— |
tcp_memory_usage_bytes |
TCP memory in use |
Bytes |
Host |
— |
tcp_memory_usage_pages |
TCP memory in use |
Pages |
Host |
— |
tcp_memory_usage_percent |
TCP memory usage as a percentage of the total TCP memory limit |
% |
Host |
— |
Connection Tracking
Host nf_conntrack table usage and capacity come from /proc/sys/net/netfilter/nf_conntrack_count and /proc/sys/net/netfilter/nf_conntrack_max. The repository configuration disables net_conntrack through BlackList by default.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
net_conntrack_entry_count |
Current nf_conntrack table entries |
Entries |
Host |
— |
net_conntrack_entry_max |
Maximum nf_conntrack table entries |
Entries |
Host |
— |
ARP Neighbors
Counts ARP neighbor entries in host and container network namespaces.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
arp_entries |
ARP entries in the host network namespace |
Count |
Host namespace |
— |
arp_total |
Total ARP entries across all network namespaces on the host |
Count |
Host |
— |
arp_container_entries |
ARP entries in the container network namespace |
Count |
Container |
— |
Transmit Queues
Qdisc metrics describe backlog, transmitted traffic, drops, and requeues, not queueing latency directly. Only root Qdiscs of matching devices are collected; noqueue is skipped. The repository configuration disables netdev_qdisc through BlackList by default.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
netdev_qdisc_backlog |
Bytes queued for transmission |
Bytes |
Host |
device, kind |
netdev_qdisc_current_queue_length |
Current queued packets |
Count |
Host |
device, kind |
netdev_qdisc_overlimits_total |
Overlimit events |
Count |
Host |
device, kind |
netdev_qdisc_requeues_total |
Requeues because the NIC/driver temporarily cannot transmit |
Count |
Host |
device, kind |
netdev_qdisc_drops_total |
Packets dropped due to full queues, rate-limit policies, or similar causes |
Count |
Host |
device, kind |
netdev_qdisc_bytes_total |
Cumulative transmitted bytes |
Bytes |
Host |
device, kind |
netdev_qdisc_packets_total |
Transmitted packets |
Count |
Host |
device, kind |
Hardware Drops
Counts receive-side hardware drops for supported NIC drivers. It prefers rx_missed_errors; otherwise it attempts to subtract eBPF software-drop counts from rx_dropped. The repository configuration disables netdev_hw through BlackList by default.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
netdev_hw_rx_dropped_total |
Cumulative receive-side hardware drops |
Count |
Host |
sysfs, eBPF |
device, driver |
RDMA Port Statistics
netdev_rdma_link_<counter> exposes per-port kernel counters; available names depend on the driver. Additional labels are device, nodeguid, index, num_ports, and port.
The new port label creates new time series, including on single-port devices. Keep it for port-level queries. For a selected counter, use sum by (region, hostname, device) (<metric>) for device totals, or sum by (region, hostname, device) (rate(<metric>[5m])) for device rates; replace <metric> with the full metric name. Grouping only by device mixes identically named devices across hosts.
NIC Statistics
Collects NIC statistics through proc or netlink. Common metrics follow Linux /proc/net/dev semantics:
receive_dropped:rx_dropped + rx_missed_errors。
receive_frame_errors:rx_length_errors + rx_over_errors + rx_crc_errors + rx_frame_errors。
transmit_carrier_errors:tx_carrier_errors + tx_aborted_errors + tx_window_errors + tx_heartbeat_errors。
Netlink also provides detailed error metrics and receive_nohandler. Detailed errors may already be included in the aggregates above and must not be added again. Tables show host names; container names insert container_ after netdev_.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
netdev_receive_bytes_total |
Total bytes successfully received |
Bytes |
Host, container |
device |
netdev_receive_packets_total |
Total packets successfully received |
Count |
Host, container |
device |
netdev_receive_multicast_total |
Received multicast packets |
Count |
Host, container |
device |
netdev_receive_compressed_total |
Received compressed packets |
Count |
Host, container |
device |
netdev_receive_frame_errors_total |
Total receive length, overflow, CRC, and frame-alignment errors |
Count |
Host, container |
device |
netdev_receive_errors_total |
Total receive errors |
Count |
Host, container |
device |
netdev_receive_dropped_total |
Receive drops, including missed errors |
Count |
Host, container |
device |
netdev_receive_fifo_errors_total |
Receive FIFO/ring-buffer overflow errors |
Count |
Host, container |
device |
netdev_transmit_bytes_total |
Total bytes successfully transmitted |
Bytes |
Host, container |
device |
netdev_transmit_packets_total |
Total packets successfully transmitted |
Count |
Host, container |
device |
netdev_transmit_collisions_total |
Transmit collisions |
Count |
Host, container |
device |
netdev_transmit_errors_total |
Total transmit errors |
Count |
Host, container |
device |
netdev_transmit_dropped_total |
Packets dropped during transmission due to full queues, policies, or similar causes |
Count |
Host, container |
device |
netdev_transmit_fifo_errors_total |
Transmit FIFO/ring-buffer errors |
Count |
Host, container |
device |
netdev_transmit_carrier_errors_total |
Total transmit carrier, aborted, window, and heartbeat errors |
Count |
Host, container |
device |
netdev_transmit_compressed_total |
Transmitted compressed packets |
Count |
Host, container |
device |
TCP Statistics
Reads network-namespace /proc/<pid>/net/netstat and snmp, subject to MetricCollector.Netstat filters. Tables show host names; container names insert container_ after netstat_.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
netstat_TcpExt_ArpFilter |
Packets dropped by ARP filtering rules |
Count |
Host, container |
— |
netstat_TcpExt_BusyPollRxPackets |
Packets received through busy polling |
Count |
Host, container |
— |
netstat_TcpExt_DelayedACKLocked |
Delayed ACK timer expirations postponed because user space holds the socket lock |
Count |
Host, container |
— |
netstat_TcpExt_DelayedACKLost |
Already-acknowledged packets received, possibly due to ACK loss or duplicate network packets |
Count |
Host, container |
— |
netstat_TcpExt_DelayedACKs |
Delayed ACK timer expirations that sent an ACK |
Count |
Host, container |
— |
netstat_TcpExt_EmbryonicRsts |
Packets with RST/SYN flags received in SYN_RECV |
Count |
Host, container |
— |
netstat_TcpExt_ListenDrops |
Packets dropped by LISTEN sockets, including accept-queue overflow and memory allocation failures |
Count |
Host, container |
— |
netstat_TcpExt_ListenOverflows |
TCP accept-queue overflows |
Count |
Host, container |
— |
netstat_TcpExt_OfoPruned |
Out-of-order queue pruning due to memory shortage |
Count |
Host, container |
— |
netstat_TcpExt_OutOfWindowIcmps |
Received ICMP errors unrelated to the current TCP window |
Count |
Host, container |
— |
netstat_TcpExt_PruneCalled |
Buffer cleanup triggered by memory shortage |
Count |
Host, container |
— |
netstat_TcpExt_RcvPruned |
Receive queue pruning (packet drops) due to memory shortage |
Count |
Host, container |
— |
netstat_TcpExt_SyncookiesFailed |
SYN cookies that failed validation |
Count |
Host, container |
— |
netstat_TcpExt_SyncookiesRecv |
Received SYN cookies |
Count |
Host, container |
— |
netstat_TcpExt_SyncookiesSent |
Sent SYN cookies |
Count |
Host, container |
— |
netstat_TcpExt_TCPACKSkippedChallenge |
Other ACKs skipped while processing Challenge ACKs |
Count |
Host, container |
— |
netstat_TcpExt_TCPACKSkippedFinWait2 |
ACKs skipped in FIN-WAIT-2 |
Count |
Host, container |
— |
netstat_TcpExt_TCPACKSkippedPAWS |
ACKs skipped after PAWS check failures |
Count |
Host, container |
— |
netstat_TcpExt_TCPACKSkippedSeq |
ACKs skipped due to sequence checks |
Count |
Host, container |
— |
netstat_TcpExt_TCPACKSkippedTimeWait |
ACKs skipped in TIME-WAIT |
Count |
Host, container |
— |
netstat_TcpExt_TCPAbortOnClose |
Connections aborted when applications close with unread data |
Count |
Host, container |
— |
netstat_TcpExt_TCPAbortOnData |
Connections aborted with data in flight, sending RST |
Count |
Host, container |
— |
netstat_TcpExt_TCPAbortOnLinger |
Connections aborted after a LINGER timeout |
Count |
Host, container |
— |
netstat_TcpExt_TCPAbortOnMemory |
Connections closed due to memory problems |
Count |
Host, container |
— |
netstat_TcpExt_TCPAbortOnTimeout |
Connections closed after timer retransmission limits are exceeded |
Count |
Host, container |
— |
netstat_TcpExt_TCPLossFailures |
Failed recovery from packet loss |
Count |
Host, container |
— |
netstat_TcpExt_TCPLossProbeRecovery |
Packet losses detected and recovered through TLP |
Count |
Host, container |
— |
netstat_TcpExt_TCPLossProbes |
Tail Loss Probe (TLP) packets sent |
Count |
Host, container |
— |
netstat_TcpExt_TCPLossUndo |
Loss-state undo operations during recovery |
Count |
Host, container |
— |
netstat_TcpExt_TCPLostRetransmit |
Lost retransmissions |
Count |
Host, container |
— |
Only selected TcpExt fields are listed. See Linux kernel documentation for other fields and version differences.
References:
Socket Usage
Reads network-namespace /proc/<pid>/net/sockstat. Tables show host names; container names insert container_ after sockstat_. mem and mem_bytes are emitted only for the host.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
sockstat_sockets_used |
Sockets currently in use |
Count |
Host, container |
— |
sockstat_TCP_inuse |
TCP sockets in connection states such as ESTABLISHED and LISTEN, excluding TIME_WAIT |
Count |
Host, container |
— |
sockstat_TCP_orphan |
TCP sockets no longer associated with user-space file handles |
Count |
Host, container |
— |
sockstat_TCP_tw |
TCP sockets in TIME_WAIT |
Count |
Host, container |
— |
sockstat_TCP_alloc |
Total allocated TCP socket objects |
Count |
Host, container |
— |
sockstat_TCP_mem |
Kernel memory pages currently used by TCP sockets |
Pages |
Host |
— |
sockstat_UDP_inuse |
UDP sockets currently bound to local ports |
Count |
Host, container |
— |
I/O
Configuration
iotracing, blk_iotrace, blk_throtl, blk_iocost, and blk_device_health are enabled
by default. Add a feature name to the global BlackList and restart Huatuo
to disable it. Disabling iotracing stops both its disk metrics and automatic
diagnosis. Disabling blk_device_health stops health events, evidence collection,
and its metrics independently of iotracing.
The following metrics describe disk performance. They use the
huatuo_bamai_iotracing_ prefix and are interval Gauges with a disk label:
| Metric suffix |
Description |
read_bps, write_bps |
Read/write throughput in bytes per second |
read_iops, write_iops |
Read/write operations per second |
read_await_ms, write_await_ms |
Mean read/write completion time in milliseconds |
io_util_percent |
Percentage of time the disk is busy |
average_queue_size |
Average IO queue length |
Metrics cover whole disks and supported logical devices, excluding partitions
and pseudo devices such as loop, ram, zram, and fd.
Latency and IO size distributions
blk_iotrace measures read/write IO latency and size distributions for SCSI/SAS,
NVMe, and virtio disks and containers. Only disks with iostats and
request-time accounting enabled at startup are included. Disabling these settings
during operation is unsupported.
If software blk-crypto fallback is initialized at startup, the entire
blk_iotrace collector remains disabled.
SCSI issued sizes use the kernel’s 16-bit sector count and wrap at 32 MiB.
When requests merge different blkcgs, container issued-size attribution is
approximate; host accounting is unaffected.
Block device additions, removals, or recreation restart blk_iotrace,
blk_throtl, and blk_iocost collection. Data for all disks may be omitted during
the transition.
Bucket values count IOs in the collection interval at or below the le upper
bound; +Inf is the total. Latency bounds are in seconds and size bounds in
bytes. Metrics are interval Gauges.
# TYPE huatuo_bamai_blk_iotrace_q2d_seconds_bucket gauge
huatuo_bamai_blk_iotrace_q2d_seconds_bucket{disk="sda",operation="read",hostname="hostname",region="dev",le="0.001"} 3
huatuo_bamai_blk_iotrace_q2d_seconds_bucket{disk="sda",operation="read",hostname="hostname",region="dev",le="+Inf"} 5
# TYPE huatuo_bamai_blk_iotrace_d2c_seconds_bucket gauge
huatuo_bamai_blk_iotrace_d2c_seconds_bucket{disk="sda",operation="read",hostname="hostname",region="dev",le="+Inf"} 5
# TYPE huatuo_bamai_blk_iotrace_q2g_seconds_bucket gauge
huatuo_bamai_blk_iotrace_q2g_seconds_bucket{disk="sda",operation="read",hostname="hostname",region="dev",le="+Inf"} 5
# TYPE huatuo_bamai_blk_iotrace_container_q2g_seconds_bucket gauge
huatuo_bamai_blk_iotrace_container_q2g_seconds_bucket{container_id="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",container_hostname="etcd-hostname",container_namespace="kube-system",container_qos="burstable",container_name="etcd",container_type="normal",disk="sda",operation="read",hostname="hostname",region="dev",le="+Inf"} 2
| Metric |
Description |
Unit |
Scope |
| blk_iotrace_q2d_seconds_bucket |
Queue-to-last-issue latency distribution |
count |
Host |
| blk_iotrace_d2c_seconds_bucket |
Last-issue-to-complete latency distribution |
count |
Host |
| blk_iotrace_q2g_seconds_bucket |
Queue-to-request-start latency distribution |
count |
Host |
| blk_iotrace_container_q2d_seconds_bucket |
Queue-to-last-issue latency distribution |
count |
Container |
| blk_iotrace_container_d2c_seconds_bucket |
Last-issue-to-complete latency distribution |
count |
Container |
| blk_iotrace_container_q2g_seconds_bucket |
Queue-to-request-start latency distribution |
count |
Container |
| blk_iotrace_queued_io_size_bytes_bucket |
Queued bio size distribution |
count |
Host |
| blk_iotrace_issued_io_size_bytes_bucket |
Request size; last dispatched size for SCSI, completion bytes for NVMe/virtio |
count |
Host |
| blk_iotrace_container_queued_io_size_bytes_bucket |
Queued bio size distribution |
count |
Container |
| blk_iotrace_container_issued_io_size_bytes_bucket |
Request size; last dispatched size for SCSI, completion bytes for NVMe/virtio |
count |
Container |
| blk_iotrace_interval_start_timestamp_seconds |
Start of the interval |
Unix seconds |
Host |
| blk_iotrace_interval_end_timestamp_seconds |
End of the interval |
Unix seconds |
Host |
The 17 latency bounds in seconds are 0.00005, 0.0001, 0.00025, 0.0005,
0.001, 0.002, 0.004, 0.008, 0.016, 0.032, 0.064, 0.128,
0.256, 0.512, 1, 2, and +Inf.
Grafana
The IO overview shows latency distributions and IO counts by collection
interval. Click a bar to view latency and size histograms for that window.
The panels use Business Charts (volkovlabs-echarts-panel).
Update custom dashboards and alerts after upgrading. The table omits the
huatuo_bamai_ prefix:
| Former metric |
Replacement |
iolatency_blkdisk_d2c |
blk_iotrace_d2c_seconds_bucket |
iolatency_container_blkdisk_d2c |
blk_iotrace_container_d2c_seconds_bucket |
iolatency_blkdisk_q2c, iolatency_container_blkdisk_q2c |
No direct equivalent; select Q2G, Q2D, or D2C for the required stage |
iolatency_blkdisk_freeze |
blk_device_health_freeze_total, still a Counter |
disk now contains names such as sda instead of device numbers such as 8:0.
The new operation label distinguishes reads and writes. Former zone
numbers are replaced by cumulative le bounds in seconds, listed above;
they cannot be mapped by index. For a range (a, b], subtract the le=a
value from the le=b value.
Former latency metrics counted only IOs of at least 20 ms. New metrics cover
all read/write IO on supported disks, and D2C starts at the last dispatch.
Adjust alerts for the new stages and bounds rather than only renaming metrics.
Latency buckets change from cumulative Counters to interval Gauges. Do not
apply rate() or increase() to them. Query directly for one interval;
for example, sum read D2C samples for a disk over the last five minutes:
sum_over_time(huatuo_bamai_blk_iotrace_d2c_seconds_bucket{disk="sda",operation="read",le="+Inf"}[5m])
Hardware
# HELP huatuo_bamai_blk_device_health_freeze_total the disk freeze event count
# TYPE huatuo_bamai_blk_device_health_freeze_total counter
huatuo_bamai_blk_device_health_freeze_total{disk="sda",hostname="hostname",region="dev"} 0
| Metric |
Description |
Unit |
Scope |
Labels |
| blk_device_health_freeze_total |
Host disk freeze count; resets on disk replacement |
count |
Host |
host, region, disk |
Select this metric under Overview → Selected Metric on the host dashboard.
blk-throttle waits
blk_throtl counts IOs delayed by blk-throttle and their mean queue wait.
Each IO is counted when it leaves the queue; its wait starts at its first
queue entry.
| Metric |
Description |
blk_throtl_delayed_io_count |
IOs that finished waiting in the collection interval |
blk_throtl_delayed_average_wait_ms |
Mean queue wait for those IOs, in milliseconds |
blk_throtl_container_delayed_io_count |
Container IOs that finished waiting in the collection interval |
blk_throtl_container_delayed_average_wait_ms |
Mean container queue wait, in milliseconds |
Metrics distinguish disk and operation (read or write). scope=host
is the host total; scope=other is its portion without container attribution.
Container series use container labels instead of scope. All four metrics
are interval Gauges.
Container discovery is optional; host collection does not require kubelet.
Failed lookups or invalid labels send the current data to other; recovered
associations do not replay past intervals. After temporary collection failure,
the first successful collection rebuilds the baseline and the next resumes
output, without filling the failed interval. Errors that stop collection
require troubleshooting and a Huatuo restart.
After cgroup release, uncollected tail wait deltas are included in Host and
Other without container attribution. Results can undercount if one series on
one CPU completes at least 67,108,864 waits, or accumulates about 2.749 million
seconds of waiting, between successful collections.
blk_iocost waits
blk_iocost measures waits caused by insufficient IOCOST budget. Waiting starts
when the IO enters the wait queue and ends at its final wakeup; the full wait
belongs to the collection interval in which it ends.
| Metric |
Description |
blk_iocost_delayed_io_count |
Read/write IOs that finished waiting in the interval |
blk_iocost_delayed_average_wait_ms |
Mean wait for those IOs, in milliseconds |
blk_iocost_container_delayed_io_count |
Container read/write IOs that finished waiting in the interval |
blk_iocost_container_delayed_average_wait_ms |
Mean container IO wait, in milliseconds |
These interval Gauges use disk (sda, nvme0n1, etc.) and operation (read or
write). scope=host includes all containers; scope=other is the portion
without container attribution.
Container discovery is optional; host collection does not require kubelet.
Failed lookups or invalid labels send the current data to other; recovered
associations do not replay past intervals. After temporary collection failure,
the first successful collection rebuilds the baseline and the next resumes
output, without filling the failed interval. Errors that stop collection
require troubleshooting and a Huatuo restart.
After cgroup release, uncollected tail wait deltas are included in Host and
Other without container attribution. Results can undercount if one series on
one CPU completes at least 67,108,864 waits, or accumulates about 2.749 million
seconds of waiting, between successful collections. For example, 10,240 waits
for one series, each lasting 270 seconds and settled on that CPU in the same
interval, exceed the wait-time capacity.
IOCOST requires a non-PREEMPT_RT Linux kernel with IOCOST functions,
BPF/BTF, and kprobes.
Device health
blk_device_health records these events:
| Event type |
Trigger |
block_error |
A normal block request completes with an error |
nvme_timeout |
An NVMe request times out |
nvme_reset |
An NVMe reset request is accepted, not necessarily completed; event only, without evidence commands |
nvme_state_change |
An NVMe controller changes state |
scsi_timeout |
A SCSI command times out |
scsi_dispatch_error |
SCSI command dispatch fails |
md_sync_action |
An MD sync action changes |
md_degraded |
The number of unavailable MD members changes |
md_member_state |
An MD member changes state or disappears |
If an NVMe state name is unavailable, new_state is unknown and
new_state_raw retains the numeric state.
Block errors, NVMe timeouts, SCSI errors, and MD members entering faulty,
blocked, write_error, or removed trigger evidence collection. A uniquely
resolved NVMe target uses read-only nvme-cli commands; SCSI uses read-only
smartctl commands. Ambiguous targets retain the event without scanning other
devices. MD monitoring does not require mdadm.
Evidence commands use the resolved physical disk or NVMe controller; the
event’s device can retain an MD member’s partition name.
Evidence commands for the same device are suppressed while running and for
a 60-second cooldown; raw events remain independent.
The huatuo_bamai_blk_device_health_ Counters track events since process startup:
| Metric suffix |
Labels |
Description |
block_errors_total |
disk, operation, status |
Block-layer errors |
nvme_timeouts_total |
disk |
NVMe timeouts |
nvme_resets_total |
disk |
Accepted NVMe reset requests |
scsi_timeouts_total |
disk |
SCSI timeouts |
scsi_dispatch_errors_total |
disk, status |
SCSI dispatch errors |
collection_errors_total |
disk, reason |
Evidence collection failures |
event_persistence_failures_total |
reason |
Event save errors |
MD and NVMe controller state changes are stored as events, without a current
state Gauge. Counters update before events are saved; save failures are
counted by event_persistence_failures_total{reason="save_error"}.
Accepted health events are stored as individual documents. Unavailable or
inapplicable optional fields are omitted:
| Field |
Description |
type |
Event type |
device |
Event device name; MD member events may retain a partition name |
array, member |
MD array and member names |
old_state, new_state |
MD state transition; NVMe provides only the new state |
new_state_raw |
Numeric NVMe controller state |
operation, io_error_status, sector |
Block operation, error, and starting sector |
collection_status |
ok, partial, unsupported, timeout, or error |
nvme, scsi |
Protocol health evidence collected after the event |
NVMe evidence includes critical_warning, media_errors_total, and up to
eight error-log entries with status code, NSID, and LBA. SCSI evidence includes
overall health, ASC/ASCQ, temperature, defect counts, read/write/verify error
counts, and pending-defect counts with up to eight sample LBAs.
Disk Statistics
blk_iostat reads /proc/diskstats and /proc/stat for per-device request counts, throughput, cumulative durations, and host CPU iowait.
The former diskio_ metric prefix changes to blk_iostat_, and the disk-name
label changes from device to disk. Update custom queries and legends;
metric types and cumulative accounting are unchanged.
The repository configuration disables blk_iostat through BlackList by default. Remove it and restart huatuo-bamai to enable it.
Request counts, bytes, and I/O durations are cumulative Counters. Use rate() to calculate IOPS, throughput, and duration growth rates. Mean request duration is the duration growth rate divided by request rate; exclude intervals with zero requests. io_in_progress and disk_iowait_percent are Gauges.
| Metric |
Description |
Unit |
Scope |
Additional Labels |
blk_iostat_read_requests_total |
Cumulative completed read requests; use rate() for read IOPS |
Count |
Host |
disk |
blk_iostat_write_requests_total |
Cumulative completed write requests; use rate() for write IOPS |
Count |
Host |
disk |
blk_iostat_read_bytes_total |
Cumulative bytes read; use rate() for read throughput |
Bytes |
Host |
disk |
blk_iostat_written_bytes_total |
Cumulative bytes written; use rate() for write throughput |
Bytes |
Host |
disk |
blk_iostat_read_time_seconds_total |
Cumulative time spent on completed reads |
Seconds |
Host |
disk |
blk_iostat_write_time_seconds_total |
Cumulative time spent on completed writes |
Seconds |
Host |
disk |
blk_iostat_io_in_progress |
Current in-flight I/O requests (queue depth) |
Count |
Host |
disk |
blk_iostat_disk_iowait_percent |
CPU time spent waiting for I/O as a share of the collection interval |
% |
Host |
— |
XFS
xfs collects per-device host statistics from sysfs with the additional label device. xfs_log_free_bytes is a Gauge; metrics ending in _total are cumulative Counters.
| Metric |
Description |
Unit |
xfs_log_free_bytes |
Free log space |
Bytes |
xfs_log_space_sleep_total |
Cumulative waits for log space |
Count |
xfs_alloc_blocks_total |
Cumulative allocated blocks |
Blocks |
xfs_alloc_extents_total |
Cumulative allocated extents |
Count |
xfs_inode_attempts_total |
Cumulative inode-cache requests |
Count |
xfs_inode_missed_total |
Cumulative inode-cache misses |
Count |
xfs_buf_busy_locked_total |
Cumulative busy-buffer lock events |
Count |
xfs_buf_locked_waited_total |
Cumulative buffer-lock waits |
Count |
xfs_log_free_bytes is omitted when free log space is unavailable. Restart huatuo-bamai after adding an XFS mount.
System Events
Soft Lockups
Records soft lockup events detected by the kernel.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
softlockup_total |
System soft lockup event count |
Count |
Host |
eBPF |
— |
Hung Tasks
Records hung-task events detected by the kernel.
| Metric |
Description |
Unit |
Scope |
Source |
Additional Labels |
hungtask_total |
System hung-task event count |
Count |
Host |
eBPF |
— |
attribute hungtask events and counts to containers
| Metric |
Description |
Unit |
Target |
Source |
Labels |
| hungtask_container_total |
Events attributed to blocked container tasks |
count |
Container |
BPF + CSS cache |
container_hostname, container_id, container_name, container_namespace, container_qos, container_type, hostname, region |
Container counts are included in the host Counter and are independent of trace backoff. Events with unresolved container attribution still contribute to the host count. Container exit removes its count; agent restart resets counts. Repeated reports of the same blocked task count as separate events.
GPU
The repository configuration disables metax_gpu through BlackList by default. Meet the device and SDK dependencies before enabling it.
| Metric |
Description |
Unit |
Additional Labels |
metax_gpu_sdk_info |
GPU SDK information |
— |
version |
metax_gpu_driver_info |
GPU driver information |
— |
version |
metax_gpu_info |
GPU identity and configuration |
— |
gpu, model, uuid, bios_version, bdf, mode, die_count |
metax_gpu_board_power_watts |
GPU board power |
W |
gpu |
metax_gpu_pcie_link_speed_gt_per_second |
Current GPU PCIe link speed |
GT/s |
gpu |
metax_gpu_pcie_link_width_lanes |
Current GPU PCIe link width |
Lanes |
gpu |
metax_gpu_pcie_receive_bytes_per_second |
GPU PCIe receive throughput |
B/s |
gpu |
metax_gpu_pcie_transmit_bytes_per_second |
GPU PCIe transmit throughput |
B/s |
gpu |
metax_gpu_metaxlink_link_speed_gt_per_second |
Current GPU MetaXLink speed |
GT/s |
gpu, metaxlink |
metax_gpu_metaxlink_link_width_lanes |
Current GPU MetaXLink width |
Lanes |
gpu, metaxlink |
metax_gpu_metaxlink_receive_bytes_per_second |
GPU MetaXLink receive throughput |
B/s |
gpu, metaxlink |
metax_gpu_metaxlink_transmit_bytes_per_second |
GPU MetaXLink transmit throughput |
B/s |
gpu, metaxlink |
metax_gpu_metaxlink_receive_bytes_total |
Total GPU MetaXLink bytes received |
Bytes |
gpu, metaxlink |
metax_gpu_metaxlink_transmit_bytes_total |
Total GPU MetaXLink bytes transmitted |
Bytes |
gpu, metaxlink |
metax_gpu_metaxlink_aer_errors_total |
GPU MetaXLink AER errors |
Count |
gpu, metaxlink, error_type |
metax_gpu_status |
GPU status |
— |
gpu, die |
metax_gpu_temperature_celsius |
GPU temperature |
°C |
gpu, die |
metax_gpu_utilization_percent |
GPU utilization (0–100) |
% |
gpu, die, ip |
metax_gpu_memory_total_bytes |
Total GPU memory |
Bytes |
gpu, die |
metax_gpu_memory_used_bytes |
Used GPU memory |
Bytes |
gpu, die |
metax_gpu_clock_mhz |
GPU clock frequency |
MHz |
gpu, die, ip |
metax_gpu_clocks_throttling |
GPU clock-throttling reasons |
— |
gpu, die, reason |
metax_gpu_dpm_performance_level |
GPU DPM performance level |
— |
gpu, die, ip |
metax_gpu_ecc_memory_errors_total |
GPU ECC memory errors |
Count |
gpu, die, memory_type, error_type |
metax_gpu_ecc_memory_retired_pages_total |
GPU ECC retired memory pages |
Count |
gpu, die |
MThreads
MThreads GPU collection requires the MTML management library. Startup searches for libmtml.so.2, then libmtml.so.
Remove mthreads_gpu from BlackList and restart huatuo-bamai to enable it. EnableHealth, EnablePCIe, and EnableMTLink in MetricCollector.Mthreads control the corresponding metric groups.
| Metric |
Description |
Unit |
Additional Labels |
mthreads_gpu_library_info |
MTML library information |
— |
version |
mthreads_gpu_device_info |
GPU information |
— |
gpu, name, brand, serial |
mthreads_gpu_device_pci_info |
GPU PCI information |
— |
gpu, sbdf |
mthreads_gpu_device_spec |
GPU specifications |
— |
gpu, cores |
mthreads_gpu_device_bios_version |
GPU BIOS version |
— |
gpu, bios |
mthreads_gpu_device_musa_capability |
GPU MUSA compute capability |
— |
gpu, musa_capability |
mthreads_gpu_memory_info |
GPU memory information |
— |
gpu, type, vendor, bus_width |
mthreads_gpu_pcie_link_max_speed_gt_per_sec |
Maximum GPU PCIe link speed (hardware capability) |
GT/s |
gpu |
mthreads_gpu_pcie_link_max_width_lanes |
Maximum GPU PCIe link width (hardware capability) |
Lanes |
gpu |
mthreads_gpu_device_power_watts |
GPU device power |
W |
gpu |
mthreads_gpu_gpu_temperature_celsius |
GPU temperature |
°C |
gpu |
mthreads_gpu_memory_temperature_celsius |
GPU memory temperature |
°C |
gpu |
mthreads_gpu_gpu_utilization_percent |
GPU utilization (0-100) |
% |
gpu |
mthreads_gpu_memory_utilization_percent |
GPU memory utilization (0-100) |
% |
gpu |
mthreads_gpu_memory_total_bytes |
Total GPU memory |
Bytes |
gpu |
mthreads_gpu_memory_used_bytes |
Used GPU memory |
Bytes |
gpu |
mthreads_gpu_gpu_clock_mhz |
GPU clock frequency |
MHz |
gpu |
mthreads_gpu_gpu_max_clock_mhz |
Maximum GPU clock frequency |
MHz |
gpu |
mthreads_gpu_memory_clock_mhz |
GPU memory clock frequency |
MHz |
gpu |
mthreads_gpu_memory_max_clock_mhz |
Maximum GPU memory clock frequency |
MHz |
gpu |
mthreads_gpu_gpu_voltage_volts |
GPU voltage |
V |
gpu |
mthreads_gpu_gpu_power_limit_watts |
Enforced GPU power limit |
W |
gpu |
mthreads_gpu_gpu_power_default_limit_watts |
Default GPU power-management limit |
W |
gpu |
mthreads_gpu_fan_rpm |
GPU fan speed |
RPM |
gpu, fan |
mthreads_gpu_fan_speed_percent |
GPU fan speed percentage |
% |
gpu, fan |
mthreads_gpu_gpu_pstate |
GPU performance state (0=P0) |
— |
gpu |
mthreads_gpu_vpu_utilization_percent |
GPU VPU utilization (0-100) |
% |
gpu |
mthreads_gpu_vpu_encoder_utilization_percent |
GPU VPU encoder utilization (0-100) |
% |
gpu |
mthreads_gpu_vpu_decoder_utilization_percent |
GPU VPU decoder utilization (0-100) |
% |
gpu |
mthreads_gpu_vpu_clock_mhz |
GPU VPU clock frequency |
MHz |
gpu |
mthreads_gpu_pcie_link_speed_gt_per_sec |
Current GPU PCIe link speed |
GT/s |
gpu |
mthreads_gpu_pcie_link_width_lanes |
Current GPU PCIe link width |
Lanes |
gpu |
mthreads_gpu_pcie_replay_total |
GPU PCIe replay counter |
Count |
gpu |
mthreads_gpu_mtlink_state |
GPU MtLink state (0=DOWN,1=UP,2=DOWNGRADE) |
— |
gpu, link |
mthreads_gpu_mtlink_link_bandwidth_gb_s |
Maximum GPU MtLink bandwidth per link (static specification, not live throughput) |
GB/s |
gpu |
mthreads_gpu_mtlink_link_count |
Maximum supported GPU MtLink links (static specification) |
Links |
gpu |
10.2 - AutoTracing Fields
This reference covers AutoTracing record fields, units, and examples. See AutoTracing for use cases and Node Configuration for settings. Thresholds below are built-in defaults that configuration files can override.
Results
Automatic tracing events are written to Elasticsearch or local files according to enabled storage settings. Filter by tracer_type=autotracing, tracer_name, host or container identifiers, and time range. The JSON examples illustrate field structure, not measured results.
CPU examples use perf. With profiler, events retain trigger metrics; profiles are stored separately in Elasticsearch with the same tracer_id. See Node Configuration for storage requirements and viewing instructions.
Common Fields
Records contain these common fields. Container fields are provided only when a container is associated.
| Field |
Description |
hostname |
Node hostname |
region |
Node region |
uploaded_timestamp |
Data upload time |
container_id |
Container ID |
container_hostname |
Container hostname |
container_namespace |
Container’s Kubernetes namespace |
container_type |
Container type |
container_qos |
Container QoS class |
tracer_name |
Event name, such as cpusys or memburst |
tracer_id |
ID of this trace |
started_timestamp |
Trace start time |
tracer_type |
Observation type; always autotracing for AutoTracing records |
tracer_data |
Event-specific data described below |
Host CPU
Tracer: cpusys. Select perf (default) or profiler with AutoTracing.CPUSys.Tool.
Periodically reads /proc/stat to detect host system, user (user + nice), and executing-total (user + nice + system + irq + softirq) CPU bursts, including container work. Any group triggers profiling when both utilization and its increase strictly exceed its thresholds. Default utilization/increase thresholds are system 45%/20 percentage points, user 75%/45 percentage points, and total 90%/55 percentage points.
All three groups share a capture and a default 30-minute cooldown. Thresholds are configured under CPUSys independently of CPUIdle; see the configuration reference. Records retain system fields and add matching user_percent* and total_percent* fields; zero-valued additional fields are omitted.
Example with some common fields omitted:
{
"tracer_name": "cpusys",
"tracer_data": {
"system_percent": 52,
"system_percent_threshold": 45,
"system_percent_delta": 25,
"system_percent_delta_threshold": 20,
"flamedata": [
{"level": 0, "value": 1000, "self": 0, "label": "all"},
{"level": 1, "value": 350, "self": 350, "label": "do_syscall_64"}
]
}
}
| Field |
Description |
system_percent |
Host system-mode CPU utilization at trigger time (%) |
system_percent_threshold |
System-mode utilization threshold (%) |
system_percent_delta |
Increase between consecutive samples (percentage points) |
system_percent_delta_threshold |
Increase threshold (percentage points) |
flamedata |
perf: flame graph frames, with fields listed below. profiler: null; query the separate profile using the event tracer_id |
flamedata.level |
Stack depth |
flamedata.value |
Sample count for the frame, including children |
flamedata.self |
Sample count for the frame alone, excluding children |
flamedata.label |
Function or process name |
Container CPU
Tracer: cpuidle. Select perf (default) or profiler with AutoTracing.CPUIdle.Tool.
Periodically reads container cgroup CPU statistics. Container-level CPU sampling starts when user, system, or total utilization exceeds both its utilization threshold and its increase threshold between consecutive samples.
The default cooldown is 30 minutes per container. AutoTracing.CPUIdle.Filter controls target scope. Built-in thresholds:
| Metric |
Utilization Threshold |
Increase Threshold |
| User |
75% |
45 percentage points |
| System |
45% |
20 percentage points |
| Total |
90% |
55 percentage points |
Example with some common fields omitted:
{
"tracer_name": "cpuidle",
"tracer_data": {
"user_percent": 80,
"user_percent_threshold": 75,
"user_percent_delta": 48,
"user_percent_delta_threshold": 45,
"system_percent": 12,
"system_percent_threshold": 45,
"system_percent_delta": 5,
"system_percent_delta_threshold": 20,
"total_percent": 92,
"total_percent_threshold": 90,
"total_percent_delta": 53,
"total_percent_delta_threshold": 55,
"flamedata": [
{"level": 0, "value": 1000, "self": 0, "label": "all"},
{"level": 1, "value": 800, "self": 800, "label": "java/com.example.App.main"}
]
}
}
| Field |
Description |
user_percent / user_percent_threshold |
Container user-mode CPU utilization at trigger time (%) and its threshold |
user_percent_delta / user_percent_delta_threshold |
User-mode utilization increase (percentage points) and its threshold |
system_percent / system_percent_threshold |
Container system-mode CPU utilization at trigger time (%) and its threshold |
system_percent_delta / system_percent_delta_threshold |
System-mode utilization increase (percentage points) and its threshold |
total_percent / total_percent_threshold |
Container total CPU utilization at trigger time (%) and its threshold |
total_percent_delta / total_percent_delta_threshold |
Total utilization increase (percentage points) and its threshold |
flamedata |
perf: container flame graph frames, with the same fields as cpusys. profiler: null; query the separate profile using the event tracer_id |
Container D-State Load
Tracer: dload.
Reads container process states through netlink and cgroups to calculate an exponential moving average (EMA) of uninterruptible (D-state) process load. It triggers when the EMA exceeds the threshold (default: 5), with a default 30-minute cooldown per container.
Results include kernel stacks of container and host D-state processes. AutoTracing.IssuesList labels known issues.
Example with some common fields omitted:
{
"tracer_name": "dload",
"tracer_data": {
"threshold": 5,
"nr_sleeping": 120,
"nr_running": 4,
"nr_stopped": 0,
"nr_uninterruptible": 8,
"nr_iowait": 3,
"load_avg": 7.23,
"dload_avg": 6.81,
"known_issue": "",
"stack": "task:java state:D stack: 0 pid: 12345 tgid: 12345 ...\n io_schedule+0x18/0x40\n ext4_file_write_iter+0x..."
}
}
| Field |
Description |
threshold |
D-state load EMA trigger threshold |
nr_sleeping |
Sleeping processes in the container |
nr_running |
Running processes in the container |
nr_stopped |
Stopped processes in the container |
nr_uninterruptible |
Uninterruptible (D-state) processes in the container |
nr_iowait |
Processes waiting for I/O in the container |
load_avg |
Container load average at trigger time |
dload_avg |
Container D-state load EMA at trigger time |
known_issue |
Matched known-issue description; empty if none matched |
stack |
Kernel stacks of D-state processes as multiline text |
Disk I/O
Tracer: iotracing.
Reads /proc/diskstats every 5 seconds. A trigger condition must hold for two consecutive intervals. Non-NVMe devices check utilization; NVMe devices require both utilization and either read or write throughput to exceed thresholds. Each device also checks mean read and write wait times independently. Results include process and file I/O rates and I/O scheduling wait stacks.
When running iotracing directly, --enable-pprof (disabled by default) serves profiles at http://127.0.0.1:6000/debug/pprof/; if the address is already in use, the command fails to start. These profiles describe only the iotracing process’s Go runtime, not huatuo-bamai or the application processes performing disk I/O. Automatic tracing does not enable this option.
Example with some common fields omitted:
{
"tracer_name": "iotracing",
"tracer_data": {
"reason_snapshot": {
"type": "ioutil",
"device": "sda",
"major_num": 8,
"minor_num": 0,
"iostatus": {
"read_bps": 125829120,
"read_iops": 450,
"read_await": 12,
"write_bps": 2202009600,
"write_iops": 890,
"write_await": 145,
"io_util": 95,
"queue_size": 32
}
},
"process_file_io_stats": [
{
"pid": 12345,
"comm": "java",
"container_hostname": "app-pod-xxx",
"total_fs_read_bps": 0,
"total_fs_write_bps": 52428800,
"total_disk_read_bps": 0,
"total_disk_write_bps": 49152000,
"total_files": [
{
"path": "/data/logs/app.log",
"dev_name": "sda",
"fs_write_bps": 52428800,
"disk_write_bps": 49152000
}
],
"total_file_count": 1
}
],
"io_schedule_timeout_stacks": [
{
"pid": 12345,
"tid": 12346,
"cpu": 2,
"comm": "java",
"container_hostname": "app-pod-xxx",
"schedule_latency_us": 250000,
"stack": [
"io_schedule+0x18/0x40",
"ext4_file_write_iter+0x2a0/0x4c0"
]
}
]
}
}
| Field |
Description |
reason_snapshot |
Trigger reason, device, and disk metrics at that time; type is ioutil, read_bps, write_bps, read_await, or write_await |
reason_snapshot.iostatus |
*_bps: bytes/s; *_iops: operations/s; *_await: milliseconds; io_util: percentage; queue_size: mean queue depth |
process_file_io_stats |
File I/O in the collection window grouped by process, including PID, process name, and container hostname |
total_fs_read_bps / total_fs_write_bps |
Filesystem read/write rates (bytes/s) |
total_disk_read_bps / total_disk_write_bps |
Disk read/write rates (bytes/s) |
total_files / total_file_count |
A subset of file details and the untruncated total file count for the window; *_bps in file details uses bytes/s, and *_us uses microseconds |
io_schedule_timeout_stacks |
I/O scheduling wait events with PID, TID, CPU, process name, and container hostname |
schedule_latency_us / stack |
I/O scheduling wait duration (microseconds) and kernel stack frames |
Host Anonymous Memory
Tracer: memburst.
By default, samples host anonymous memory every 10 seconds and evaluates after filling a 60-sample sliding window. It triggers when current anonymous memory reaches twice the oldest window value and at least 70% of total host memory. The default cooldown is 30 minutes.
Results list the top N processes by descending RSS (default: 10) and attempt runtime snapshots serially for the first min(N, 3) processes. Go, HotSpot, and CPython use their respective providers. Unsupported runtimes report unavailable and retain process memory counters when available. A failed capture does not mean zero memory usage.
Each process has a two-second capture budget. Each snapshot retains at most 10 memory object entries and 512 KiB of JSON. Timeouts are cooperative and cannot interrupt synchronous system calls, so capture may take longer than two seconds.
The complete tracer_data is limited to 2 MiB, with at most 1,000 persisted ranking entries. When limits are exceeded, the lowest-ranked snapshots are removed first, then ranking tails if needed, and snapshot_reason is set. Cancellation and fallback records follow the same limits.
Example (some common fields omitted):
{
"tracer_name": "memburst",
"tracer_data": {
"top_memory_usage": [
{
"PID": 3456,
"ProcessName": "go-service",
"MemSize": 268435456
}
],
"process_snapshots": [
{
"pid": 3456,
"process_name": "go-service",
"language": "go",
"snapshot": {
"runtime_version": "go1.24.0",
"status": "complete",
"duration_ms": 25,
"entries": [
{
"kind": "inuse_space_objects",
"name": "main.allocate",
"bytes": 1048576,
"objects": 16,
"stack": [
"main.allocate fixture.go:42"
]
}
]
},
"process_memory": {
"status": "complete",
"rss_bytes": 268435456,
"rss_anon_bytes": 260046848
}
}
]
}
}
| Field |
Description |
top_memory_usage |
Processes ranked by descending RSS |
top_memory_usage.PID |
Process PID |
top_memory_usage.ProcessName |
Process name |
top_memory_usage.MemSize |
Process RSS (bytes) |
process_snapshots |
Optional process snapshots in rank order; each contains pid, process_name, language, snapshot, and optional process_memory |
snapshot_reason |
Optional explanation of cancellation, a full queue, or whole-event truncation; per-process failures use snapshot.status_reason |
snapshot fields:
| Field |
Description |
runtime_version |
Optional target runtime version |
status / status_reason |
Status and optional explanation; status is complete, partial, unavailable, or failed |
duration_ms |
Capture duration (milliseconds) |
output_truncated |
Optional flag indicating truncated snapshot output |
entries |
Optional ranked memory object entries |
entries.kind / entries.name |
Entry type and name; their meaning depends on the runtime |
entries.bytes / entries.objects |
Entry memory size (bytes) and object count |
entries.average_bytes / entries.stack |
Optional average object size (bytes) and call stack |
process_memory contains language-independent process memory counters. Its status and optional status_reason describe availability. All counters below are optional; missing values mean unavailable, not zero:
| Field |
Meaning (bytes) |
virtual_bytes / rss_bytes |
Virtual memory / RSS |
rss_anon_bytes / rss_file_bytes / rss_shmem_bytes |
Anonymous / file-backed / shared memory in RSS |
swap_bytes / page_table_bytes |
Swap space / page table memory |
10.3 - Abnormal Event Fields
This reference covers abnormal event structures, fields, and limitations. See Abnormal Event Diagnosis for capabilities and Node Configuration for collection settings.
Event Records
Results are written to Elasticsearch or local files according to enabled storage settings. Filter by tracer_type=event, event name, host or container, and time range. The JSON examples illustrate structure and omit some common fields. Threshold descriptions use built-in defaults.
Container fields are provided only when a container is associated. Event-specific data is in tracer_data.
| Field |
Description |
hostname |
Node hostname |
region |
Node region |
uploaded_timestamp |
Data upload time |
container_id |
Container ID |
container_name |
Container name |
container_hostname |
Container hostname |
container_namespace |
Container’s Kubernetes namespace |
container_type |
Container type, such as normal or sidecar |
container_qos |
Container QoS class |
tracer_name |
Event name, such as sched_tick or memory_oom_kill |
tracer_id |
ID of this trace |
observed_timestamp |
User-space observation time |
tracer_type |
Observation type; always event for these records |
tracer_data |
Event-specific data described below |
CPU Scheduling
Scheduling Tick Intervals
Observer: sched_tick.
Measures the total interval between consecutive scheduling ticks. When the interval reaches the threshold, it records the current kernel stack and process information. This can reveal prolonged IRQ disabling, CPU stalls, or virtualization scheduling delays, but does not alone prove that softirqs were disabled. comm and pid identify the task interrupted by the reporting tick, not the task responsible for the delay.
Use cases
- Kernel or driver code disables local interrupts for a long time, or hardirq/NMI work occupies the CPU for too long.
- The host preempts a VM’s vCPU for an extended period, including high steal time and scheduling stalls.
- Low-level anomalies such as SMI, firmware stalls, or delayed or lost clockevent delivery.
Limitations
Normal tick suppression after successfully entering NO_HZ is filtered out. High CPU load or a softirq backlog alone does not imply tick delay.
Set the threshold above the machine’s normal tick interval. The event stack captures only the first tick after the delay ends; use IRQ, steal-time, and hardware metrics to investigate the cause.
Example with some common fields omitted:
{
"uploaded_timestamp": "2025-06-11T16:05:16.251152703+08:00",
"hostname": "***",
"tracer_data": {
"tick_interval_ns": 237328905,
"tick_interval_threshold_ns": 10000000,
"comm": "***-agent",
"pid": 688073,
"cpu": 1,
"stack": "scheduler_tick/..."
},
"observed_timestamp": "2025-06-11T16:05:16.251+08:00",
"tracer_type": "event",
"region": "***",
"tracer_name": "sched_tick"
}
| Field |
Description |
comm |
Process name of the task interrupted by the reporting tick |
stack |
Kernel stack captured at the first scheduling tick after the delay |
tick_interval_ns |
Total interval between consecutive scheduling ticks (nanoseconds) |
cpu |
CPU ID where the event occurred |
tick_interval_threshold_ns |
Tick interval threshold (nanoseconds); reaching it records an event |
pid |
Process ID of the task interrupted by the reporting tick |
Soft Lockups
Observer: softlockup.
Records the process, CPU, and NMI backtraces when the kernel reports a soft lockup. These details alone cannot identify the responsible process. Kernel watchdog settings determine trigger timing.
The reporting interval for repeated events increases from 10 minutes to at most 3 hours. Events are still counted during this interval.
Example with some common fields omitted:
{
"tracer_data": {
"cpu": 15,
"pid": 12345,
"comm": "kworker/15:0",
"cpus_stack": "2025-06-10 14:30:22 sysrq: Show backtrace of all active CPUs\nNMI backtrace for cpu 15\n..."
}
}
| Field |
Description |
cpu |
CPU ID where the soft lockup occurred |
pid |
Process PID when the soft lockup was reported |
comm |
Process name when the soft lockup was reported |
cpus_stack |
NMI backtraces from all CPUs as multiline text with timestamps and stacks |
Hung Tasks
Observer: hungtask.
Matched hungtask events carry a container ID; unresolved events retain host output. Stack snapshots remain system-wide. See container counts.
Detects system hung-task events and collects kernel stacks of D-state (uninterruptible sleep) processes and CPU backtraces. The repeat reporting interval increases from 10 minutes to at most 3 hours, while events continue to be counted. The observer is not registered if the kernel does not provide hung_task_timeout_secs. Setting that value to 0 disables kernel hung-task detection.
Example with some common fields omitted:
{
"tracer_data": {
"tid": 2567042,
"comm": "kworker/u48:2",
"cpus_stack": "2025-06-10 09:57:14 sysrq: Show backtrace of all active CPUs\nNMI backtrace for cpu 33\n...",
"blocked_processes_stack": "task:java state:D stack: 0 pid: 12345 ..."
}
}
| Field |
Description |
tid |
TID of the task that triggered hung-task detection |
comm |
Name of the task that triggered hung-task detection |
cpus_stack |
NMI backtraces from all CPUs as multiline text with timestamps and stacks |
blocked_processes_stack |
Kernel stacks of D-state processes |
hung_task_timeout_secs |
Kernel hung-task detection timeout in seconds |
Memory
OOM Kills
Observer: memory_oom_kill.
Records the process that triggered the OOM Killer (trigger), the killed process (victim), and available container, cgroup, and host memory information. The triggering process is not necessarily the main memory consumer; analyze usage and memory limits together.
Example with some fields omitted:
{
"tracer_name": "memory_oom_kill",
"tracer_data": {
"trigger": {
"memory_cgroup_css_addr": "0xff4b8d8be3818000",
"container_id": "example-container",
"container_hostname": "app-pod",
"pid": 3218804,
"comm": "java"
},
"victim": {
"memory_cgroup_css_addr": "0xff4b8d8be3818000",
"container_id": "example-container",
"container_hostname": "app-pod",
"pid": 3218745,
"comm": "java",
"cgroup": {
"path": "kubepods.slice/...",
"current": 2143289344,
"max": 2147483648,
"stat": {
"anon": 1509949440,
"file": 83886080
},
"events": {
"oom": 1,
"oom_kill": 1
}
}
},
"memory_snapshot": {
"host_meminfo": {
"MemAvailable": 3355443200,
"Cached": 1073741824,
"Slab": 268435456
}
}
}
}
| Field |
Description |
trigger / victim |
Triggering and killed processes, both using the process fields below |
pid / comm |
PID and process command name |
container_id / container_hostname |
Associated container ID and hostname; omitted without an association |
memory_cgroup_css_addr |
Hexadecimal memory cgroup pointer |
cgroup.path |
Container cgroup path |
cgroup.current / cgroup.max |
Memory usage and limit at snapshot time, in bytes |
cgroup.stat / cgroup.events |
Raw cgroup memory statistics and event counts; fields depend on the cgroup version |
memory_snapshot.host_meminfo |
Selected host /proc/meminfo fields, converted to bytes |
cgroup appears inside trigger or victim only when container attribution and snapshot reads succeed. The host snapshot may also be absent. These values are read in user space and are not strictly synchronized with the OOM event.
Direct Reclaim
Observer: memory_reclaim_events.
Records the duration of an individual direct memory reclaim by a thread. When try_to_free_pages returns after exceeding the threshold (default: 900 milliseconds), it reports process, thread, and container details. Events without a resolved container are retained in the host stream. Blacklists use the registration name memory_reclaim_events; stored records use tracer_name=memory_reclaim.
Example with some common fields omitted:
{
"tracer_name": "memory_reclaim",
"tracer_data": {
"pid": 1896137,
"tid": 1896138,
"comm": "java",
"reclaim_duration_ns": 1412702917
}
}
| Field |
Description |
comm |
Process name that triggered direct reclaim |
pid |
Triggering process PID |
tid |
Triggering thread TID |
reclaim_duration_ns |
Direct reclaim duration (nanoseconds) |
An empty container ID can mean a host task or unresolved container attribution. Resolved container events are unaffected and are not duplicated in the host stream.
Network
Protocol Stack Drops
Observer: dropwatch.
Detects packet drops in the kernel network stack and reports kernel stacks, network five-tuples, TCP state, and other details. An optional stack filter can suppress noise patterns verified on the local system. type is reserved for TCP drop-type compatibility and is currently unset.
Example with some common fields omitted:
{
"observed_timestamp": "2026-07-23T02:14:40.304775546Z",
"tracer_data": {
"drop_reason": "SKB_DROP_REASON_NOT_SPECIFIED",
"source": "events",
"comm": "kubelet",
"pid": 1687046,
"net_namespace_cookie": 123456789,
"net_namespace_inum": 402653184,
"netdev_queue_mapping": 3,
"netdev_linkstatus": ["linkStatusUp"],
"netdev_name": "eth0",
"netdev_ifindex": 2,
"packet_eth_proto": "0x0800",
"packet_len_bytes": 1460,
"layers": {
"label": "IPv4/TCP",
"ipv4": {
"saddr": "10.79.68.62",
"daddr": "10.134.72.4",
"protocol": "TCP"
},
"tcp": {
"sport": 8080,
"dport": 49000,
"seq": 1009085774,
"ack_seq": 689410995,
"sk_state": "ESTABLISHED"
}
},
"stack": "kfree_skb/..."
}
}
| Field |
Description |
type |
Reserved drop type, currently unset and absent from JSON. Reserved codes: 1 general drop, 2 SYN flood, 3 SYN backlog overflow, 4 accept queue overflow |
drop_reason |
Kernel packet-drop reason |
source |
tools for standalone dropwatch, events when started by huatuo-bamai |
comm |
Process name at the drop |
pid |
Process ID |
net_namespace_cookie / net_namespace_inum |
Network namespace values for container attribution |
netdev_queue_mapping |
NIC queue index |
netdev_linkstatus |
NIC link-state flags |
netdev_name |
NIC device name |
netdev_ifindex |
NIC interface index |
packet_len_bytes |
Packet length (bytes) |
packet_eth_proto |
Ethernet protocol type in hexadecimal |
layers.ipv4.saddr / layers.ipv4.daddr |
Source and destination IP addresses |
layers.tcp.sport / layers.tcp.dport |
Source and destination ports |
layers.tcp.seq / layers.tcp.ack_seq |
TCP sequence and acknowledgment numbers |
layers.tcp.sk_state |
TCP connection state at the drop |
stack |
Kernel stack at the drop |
Receive Latency
Observer: net_rx_latency.
Records TCP packet latency from the driver receive point to __netif_receive_skb, tcp_v4_rcv, and the user-copy point. All three durations start at the driver, not at the preceding observation point. Default thresholds are 5, 10, and 115 milliseconds, respectively. Reaching a threshold records endpoints, TCP state, sequence numbers, and latency.
The host network namespace is excluded by default; only container networking is observed.
Example with some common fields omitted:
{
"observed_timestamp": "2025-06-11T00:00:00Z",
"tracer_data": {
"comm": "nginx",
"pid": 2921092,
"latency_stage": "RX_STAGE_USERCOPY",
"latency_ms": 95973,
"latency_threshold_ms": 115,
"tcp_state": "ESTABLISHED",
"tcp_saddr": "10.156.248.76",
"tcp_daddr": "10.134.72.4",
"tcp_sport": 9213,
"tcp_dport": 49000,
"tcp_seq": 1009085774,
"tcp_ack_seq": 689410995,
"net_namespace_cookie": 123456789,
"net_namespace_inum": 402653184,
"packet_len_bytes": 26064
}
}
| Field |
Description |
comm |
Process name at the event |
pid |
Process ID at the event |
latency_stage |
Stage: RX_STAGE_NETIF (NIC to kernel), RX_STAGE_TCPV4 (driver to TCP), or RX_STAGE_USERCOPY (driver to user copy) |
latency_ms |
Measured latency (milliseconds) |
latency_threshold_ms |
Trigger threshold (milliseconds) |
tcp_state |
TCP connection state; all states are supported, including ESTABLISHED, SYN_SENT, FIN_WAIT, and TIME_WAIT |
tcp_saddr / tcp_daddr |
Source/destination IP addresses |
tcp_sport / tcp_dport |
Source/destination ports |
tcp_seq / tcp_ack_seq |
TCP sequence/acknowledgment numbers |
net_namespace_cookie |
Network namespace cookie, available on kernels >= 5.14 for efficient container association |
net_namespace_inum |
Network namespace inum |
packet_len_bytes |
Packet length (bytes) |
NIC State
Observer: netdev_events.
Subscribes to kernel netlink RTM_NEWLINK messages to detect NIC link-flag changes such as AdminDown or CarrierDown. It reports interface name, link state, MAC address, and driver details. At startup, it scans devices in EventTracing.Netdev.DeviceList to establish a baseline, then reports only state changes.
Example with some common fields omitted:
{
"tracer_data": {
"ifname": "eth1",
"index": 3,
"linkstatus": "linkStatusAdminDown, linkStatusCarrierDown",
"mac": "5c:6f:69:34:dc:72",
"start": false,
"driver": "ixgbe",
"driver_version": "5.1.0-k",
"firmware_version": "3.25 0x80000421 1.2163.0"
}
}
| Field |
Description |
ifname |
Network interface name, such as eth1 |
index |
Interface index |
linkstatus |
Link-state change description, possibly containing multiple states |
mac |
NIC MAC address |
start |
Startup-scan flag; currently false because only live changes are saved |
driver |
NIC driver name |
driver_version |
NIC driver version |
firmware_version |
NIC firmware version |
LACP State
Observer: netdev_bonding_lacp.
Enabled only when the system has an IEEE 802.3ad bonding interface. On LACP (Link Aggregation Control Protocol) state changes, it reads and records all bonding interfaces under /proc/net/bonding/, including mode, MII state, Actor/Partner negotiation parameters, and slave link states.
Stored records use tracer_name=lacp; configuration blacklists use the registration name netdev_bonding_lacp.
Example with some common fields omitted:
{
"tracer_name": "lacp",
"tracer_data": {
"content": "/proc/net/bonding/bond0\nEthernet Channel Bonding Driver: v4.18.0...\nBonding Mode: IEEE 802.3ad Dynamic link aggregation\nMII Status: down\n..."
}
}
| Field |
Description |
content |
Complete bonding interface status as multiline text, including all slaves’ LACP negotiation details; equivalent to /proc/net/bonding/bondX contents |
Transmit Queue Timeouts
Observer: netdev_txqueue_timeout.
Detects NIC TX queue timeouts and records the affected queue index, device name, and driver name to investigate transmit-side device, driver, or link anomalies.
Example with some common fields omitted:
{
"tracer_data": {
"queue_index": 3,
"device_name": "eth0",
"driver_name": "ixgbe"
}
}
| Field |
Description |
queue_index |
Transmit queue index that timed out |
device_name |
NIC device name |
driver_name |
NIC driver name |
Compatibility
OOM Name Migration
The OOM kill tracer is now memory_oom_kill, previously memory_oom and earlier oom. Update blacklists, event filters, and alert queries together.
The metric prefix is now huatuo_bamai_memory_oom_kill_, replacing huatuo_bamai_memory_oom_ and the earlier huatuo_bamai_oom_. Update metric dashboards and recording rules accordingly.
Historical events retain their original names. Cross-version queries must match all three; the built-in event dashboard already covers them.
10.4 - Hardware Event Fields
This reference covers RAS metrics, event structures, severity, and source fields. See Hardware Fault Diagnosis for coverage and enablement.
EventTracing.Ras.MceThrBackoff controls the save interval for threshold-interrupt events. Events are still counted during cooldown, so counter increases need not equal the number of saved records.
Results
Error Counts
huatuo_bamai_ras_hw_err_total counts received RAS events by type: mce, edac, acpi, aer, thr, and arm_ghes. The presence of a label does not prove that the current platform supports its probe.
huatuo_bamai_ras_hw_err_total{hostname="node-01",region="region-01",type="edac"} 12
These are example values. The unit is events, not the sum of EDAC err_count values. See Kernel-Wide Insight for NIC hardware drops and PFC metrics, and Abnormal Event Diagnosis for NIC state changes.
Event Records
Query with tracer_name=ras and tracer_type=event. This EDAC example omits some fields:
{
"hostname": "node-01",
"observed_timestamp": "2026-05-11T08:58:47.329Z",
"kernel_observed_timestamp": "2026-05-11T08:58:47.328548319Z",
"tracer_name": "ras",
"tracer_type": "event",
"tracer_data": {
"dev": "MEM",
"event": "EDAC",
"type": "Corrected",
"info": "{\"err_count\":1,\"err_type\":\"Corrected\",\"err_msg\":\"memory read error\",\"label\":\"CPU_SrcID#0_Ha#0_Chan#0_DIMM#0\",\"mc_index\":0,\"addr\":7860269056,\"grain\":128}"
}
}
| Field |
Description |
tracer_data.dev |
Device or component identifier, such as CPU/MEM, MEM, ACPI, or PCIe 0000:03:00.0 |
tracer_data.event |
Error source; see Coverage |
tracer_data.type |
Normalized severity; see below |
tracer_data.info |
JSON string containing details; parse it again. Its structure depends on the event source |
observed_timestamp |
Time when user space receives the event |
kernel_observed_timestamp |
Timestamp converted from kernel observation time |
Severity
Severity classifies the event. It does not establish successful recovery, absence of application impact, or a need to reboot.
type |
Meaning |
Current Mapping |
Corrected |
Corrected |
MCE without UC/DEFERRED flags, EDAC 0, ACPI 1, AER 2, THR |
UncorrectedRecoverable |
Uncorrected, recoverable category |
MCE UC, EDAC 1, ACPI 2, AER 0 |
UncorrectedDeferred |
Uncorrected, deferred category |
MCE DEFERRED, EDAC 2 |
UncorrectedFatal |
Uncorrected, fatal category |
EDAC 3, ACPI 3, AER 1 |
Info |
Informational record |
EDAC 4, ACPI 0 |
unknown |
Unmapped severity |
Unrecognized raw values or sources without severity |
If MCE sets both DEFERRED and UC, UncorrectedDeferred takes precedence.
Event Details
The following fields are in the parsed tracer_data.info.
MCE
Register and bank meanings depend on the CPU model. Use the corresponding processor manual for diagnosis.
| Field |
Description |
mcg_cpu_cap / mcg_msr_status |
Global capability register MCG_CAP and status register MCG_STATUS |
banks_msr_status |
Bank status register MCi_STATUS, including error codes and UC, DEFERRED, ADDRV, and MISCV flags |
banks_msr_addr |
MCi_ADDR error address; interpret only when ADDRV is valid |
banks_msr_misc |
MCi_MISC details; interpret only when MISCV is valid |
mca_synd_msr / mca_ipid_msr |
AMD syndrome and instance ID registers |
instr_pointer / code_seg |
Instruction pointer and code segment; check MCG_STATUS for instruction-pointer validity |
tsc_timestamp |
CPU timestamp counter, not directly usable as a Unix timestamp |
walltime |
Unix timestamp in seconds |
cpu / cpuid / apicid / socketid |
Logical CPU, CPUID, APIC ID, and CPU socket ID |
bank |
Machine Check Bank ID; component mapping is platform-dependent |
cpuvendor |
CPU vendor code recorded by the kernel |
MCE Threshold Interrupts
| Field |
Description |
vector |
Interrupt vector |
cpu |
Logical CPU ID |
EDAC
| Field |
Description |
err_count |
Error count reported by this event |
err_type / err_msg |
Normalized severity and error description |
label |
Driver-reported memory location label; confirm the physical slot using machine topology |
mc_index |
Memory controller index, starting at 0 |
top_layer / mid_layer / low_layer |
Driver-defined memory topology indexes; -1 means unspecified |
addr |
Error address reported by the kernel |
grain |
Address granularity in bytes |
syndrome |
ECC syndrome value |
driver |
Additional error information from the driver, not necessarily its name |
ACPI GHES
| Field |
Description |
severity |
Raw severity value; see the severity table for current mappings |
sec_type |
Error section GUID as a 16-byte hexadecimal string |
fru_id / fru_text |
Replaceable component identifier and description, if supplied by firmware |
data_len |
Reported data length in bytes |
raw_data |
Hex dump; interpret using the platform and vendor format |
Non-standard sections (NVDIMM, CXL, and vendor payloads) can exceed the copied window. raw_data contains only the bytes available after the section offset: the length is capped by the remaining window, so with a valid record length unused bytes at the end are not reported as payload. The window also holds the record’s fixed fields and any data before the section, so it is not a per-record raw_data capacity. data_len still reports the length the kernel put in the record. Both values come from the kernel record and are bounded before use, so a malformed event cannot expose bytes outside the copied window.
PCIe AER
| Field |
Description |
dev_name |
PCIe BDF address, such as 0000:03:00.0 (Domain:Bus:Device.Function) |
err_type |
Corrected, UncorrectedRecoverable, UncorrectedFatal, or unknown |
err_reason |
Error name for the AER status value; the parser matches a single status value and uses unknown if unmatched |
tlp_header |
Four hexadecimal words of the TLP header; not available if absent |
Error names describe the reported condition and do not prove device damage. The current parser recognizes the following status values.
Correctable Errors
| Status Value |
err_reason |
0x00000001 |
Receiver Error |
0x00000040 |
Bad TLP |
0x00000080 |
Bad DLLP |
0x00000100 |
REPLAY_NUM Rollover |
0x00001000 |
Replay Timer Timeout |
0x00002000 |
Advisory Non-Fatal Error |
0x00004000 |
Corrected Internal Error |
0x00008000 |
Header Log Overflow |
Uncorrectable Errors
| Status Value |
err_reason |
0x00000001 |
Undefined |
0x00000010 |
Data Link Protocol Error |
0x00000020 |
Surprise Down Error |
0x00001000 |
Poisoned TLP |
0x00002000 |
Flow Control Protocol Error |
0x00004000 |
Completion Timeout |
0x00008000 |
Completer Abort |
0x00010000 |
Unexpected Completion |
0x00020000 |
Receiver Overflow |
0x00040000 |
Malformed TLP |
0x00080000 |
ECRC Error |
0x00100000 |
Unsupported Request Error |
0x00200000 |
ACS Violation |
0x00400000 |
Uncorrectable Internal Error |
0x00800000 |
MC Blocked TLP |
0x01000000 |
AtomicOp Egress Blocked |
0x02000000 |
TLP Prefix Blocked Error |
ARM GHES
ARM_GHES records use severity unknown. See Coverage for platform limitations.
| Field |
Description |
mpidr / midr |
Hexadecimal processor identifiers; mpidr=0x0 may also mean the kernel did not supply a value |
running_state |
running, stopped, or N/A |
psci_state |
Hexadecimal PSCI state when stopped; N/A when inapplicable |
affinity_level |
Decimal affinity level; N/A when unavailable |
10.5 - Profiling API
This reference covers profiling task requests, responses, and states. For a first collection, see the Profiling Guide.
huatuo-apiserver creates, supervises, and stops profiling tasks through /v1/profiling. Each HTTP creation request is an independent execution. Profiling tasks are persisted as Jobs in huatuo-apiserver; the node keeps only in-memory operations and profiling tool processes.
Task control does not depend on Elasticsearch. Raw-result queries and dashboard links require it. huatuo-bamai and huatuo-apiserver must use the same index.
Request Conventions
huatuo-apiserver listens on :12740 by default. These examples set the address and Bearer token through environment variables:
API_BASE="http://127.0.0.1:12740"
API_TOKEN="REPLACE_WITH_RANDOM_HEX"
Every request must supply the configured Bearer token in Authorization:
Authorization: Bearer REPLACE_WITH_RANDOM_HEX
Non-admin users need permissions for /v1/profiling and /v1/profiling/**. Permissions may include an HTTP method prefix, such as GET /v1/profiling/**. Successful responses contain only data:
Error responses contain a stable error code and a readable message:
{
"error": {
"code": "result_unavailable",
"message": "Job state does not provide a complete Profiling result"
}
}
Clients should branch on error.code, not parse error.message.
Query Capabilities
Before creating a task, query supported profiling types, languages, CPU and memory modes, and runtime parameters:
curl -sS \
-H "Authorization: Bearer ${API_TOKEN}" \
"${API_BASE}/v1/profiling/capabilities"
data.items is a static capability table shipped with each version. Entries contain:
| Field |
Description |
type |
Profiling type: cpu, memory, or irq |
language |
Target language for CPU and memory; omitted for IRQ |
modes |
Allowed mode values for this type/language combination |
supports_binary_match |
Whether binary_match_path is allowed |
supported_scopes |
Allowed scope values |
CPU profiling for c, c++, and go supports oncpu and offcpu; java and python support only oncpu. Memory profiling supports:
| Language |
mode |
Description |
c, c++, go |
virtual_alloc |
Virtual address space allocations |
c, c++, go |
physical_alloc |
Physical-page allocations |
c, c++, go |
physical_usage |
Live bytes of physical pages tracked in this collection |
java |
object_alloc |
JVM object allocations |
java |
object_usage |
JVM live objects |
Create a Task
JSON parameters for POST /v1/profiling:
| Parameter |
Required |
Description |
type |
Yes |
Profiling type: cpu, memory, or irq |
language |
CPU and memory only |
Target process language; omit for IRQ |
mode |
Yes |
Mode declared by the capability table for the type and language |
duration_seconds |
Yes |
Collection duration in seconds |
hostname |
Yes |
Hostname of the node running the target process, used for scheduling |
scope |
Yes |
host or container, as allowed by the capability table |
container_id |
For container scope |
Target container ID |
binary_match_path |
No |
Executable-path match, when allowed by the capability table |
host_cpu_list |
No |
Target host logical CPU list, such as "1,3-10"; omitted or empty means all CPUs |
host_cpu_list uses the target host’s logical CPU IDs for both host and container scopes. Container and CPU filters are intersected without changing the container cpuset or process affinity. It accepts one ID, comma-separated lists and inclusive ranges. Lists are sorted, deduplicated and adjacent IDs merged before storage. Leading and trailing whitespace is allowed; internal whitespace, negative IDs, reversed ranges and empty components are rejected. Input is limited to 65536 bytes and 65536 expanded entries before deduplication; IDs must be between 0 and 2147483647. The target node checks that selected CPUs are online at startup.
Native CPU oncpu/offcpu supports multiple CPUs; offcpu attribution uses the switch-out CPU. IRQ currently supports one CPU, including equivalent singleton forms such as "1,1" and "1-1". Java, Python and memory CPU targeting are unsupported. Valid lists are accepted at creation even when unsupported by the backend; backend rejection terminates the task with a failure and reports the reason in terminal.message.
Every request creates a new task, even with identical content. Exceeding per-node or process-wide active task quotas returns HTTP 429.
Create a host Go CPU profiling task:
curl -sS -i \
-X POST \
-H "Authorization: Bearer ${API_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"type": "cpu",
"language": "go",
"mode": "oncpu",
"scope": "host",
"duration_seconds": 60,
"hostname": "node-01"
}' \
"${API_BASE}/v1/profiling"
Create a Java live-object profiling task in a container:
curl -sS -i \
-X POST \
-H "Authorization: Bearer ${API_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"type": "memory",
"language": "java",
"mode": "object_usage",
"scope": "container",
"duration_seconds": 60,
"container_id": "9f4c2f1a8b7d",
"hostname": "node-01"
}' \
"${API_BASE}/v1/profiling"
Create a host softirq profiling task:
curl -sS -i \
-X POST \
-H "Authorization: Bearer ${API_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"hostname":"node-01","duration_seconds":10,"scope":"host","type":"irq","mode":"softirq"}' \
"${API_BASE}/v1/profiling"
IRQ supports only scope=host and mode=softirq; omit language, container_id,
and binary_match_path. It traces all CPUs by default; host_cpu_list selects one CPU. The limits are 500 source and 500 victim
samples per CPU per second, with no rate-limit parameter.
Results are published once after collection with profile type
irqtracing:irq:count:irq:count and count units. Hardware interrupt stacks are not collected.
Success returns 201 Created, a Location header pointing to the new task, and the task ID needed for later queries:
{
"data": {
"request_id": "<profile-job-id>",
"hostname": "node-01",
"duration_seconds": 60,
"scope": "host",
"type": "cpu",
"language": "go",
"mode": "oncpu",
"status": "pending",
"created_at": "2026-08-24T10:00:00Z",
"updated_at": "2026-08-24T10:00:00Z"
}
}
JOB_ID="<profile-job-id>"
Query Tasks
Task list
GET /v1/profiling supports these query parameters:
| Parameter |
Default |
Description |
limit |
100 |
Page size from 1 to 1000 |
offset |
0 |
Starting offset, at least 0 |
Query the 20 most recent profiling tasks:
curl -sS -G \
-H "Authorization: Bearer ${API_TOKEN}" \
--data-urlencode "limit=20" \
--data-urlencode "offset=0" \
"${API_BASE}/v1/profiling"
The server returns only profiling tasks, ordered by created_at descending. data.items is the task array; data.limit and data.offset are the effective pagination parameters; data.has_more indicates another page. Non-admin users see only their own tasks.
Task details
GET /v1/profiling/:request_id returns one task:
curl -sS \
-H "Authorization: Bearer ${API_TOKEN}" \
"${API_BASE}/v1/profiling/${JOB_ID}"
Task information is in data:
| Field |
Description |
request_id |
Profiling task ID used in all subsequent requests |
container_id |
Target container ID; omitted for host tasks |
hostname |
Target node hostname |
duration_seconds |
Requested profiling duration in seconds |
scope |
host or container |
type |
cpu, memory, or irq |
language |
Target process language; omitted for IRQ |
mode |
Profiling mode selected from the capability table |
binary_match_path |
Executable match path; omitted when unused |
host_cpu_list |
Normalized CPU selection; omitted when unrestricted |
status |
Current task status |
terminal |
Terminal details {outcome, reason, message}; omitted before termination |
created_at |
Task creation time |
updated_at |
Last task status update time |
started_at |
Actual start time; omitted until execution is observed |
ended_at |
Time of entering a terminal state; omitted while running |
result_url |
Dashboard link returned by the single-task detail endpoint when complete results are available |
Task states:
| State |
Description |
pending |
Created and waiting for agent execution |
running |
Agent is collecting profile data |
stopping |
Stop intent is persisted and being processed asynchronously |
terminal |
Task ended; see terminal.outcome |
terminal.outcome is completed, failed, stopped, or unknown. For failed, inspect terminal.reason and terminal.message. stopped means an explicit stop and possibly incomplete results. unknown means huatuo-apiserver cannot confirm the final operation state, although durably published results may still be available.
operation_lost and execution_timed_out are terminal.reason codes, not task states. Other reasons include startup or stop timeouts, unavailable nodes, execution-capacity limits, startup or runtime failure, invalid_node_request for an invalid node request constructed by huatuo-apiserver, and protocol errors.
Get Results
GET /v1/profiling/:request_id/raw returns raw windows for tasks with terminal.outcome of completed or unknown only while the durable publication marker exists. A missing or expired marker returns result_not_found. Active states return result_not_ready; failed and stopped return result_unavailable.
Responses may be large; save them directly to a file:
curl -sS \
-H "Authorization: Bearer ${API_TOKEN}" \
-o profile-raw.json \
"${API_BASE}/v1/profiling/${JOB_ID}/raw?limit=100&offset=0"
Windows are in data.items; data.limit, data.offset, and data.has_more describe pagination. Each record includes uploaded_timestamp, started_timestamp, profile_type, and pprof-compatible profile data.
Memory profiles use memory:<mode>:bytes:space:bytes, where <mode> is
virtual_alloc, physical_alloc, physical_usage, object_alloc, or object_usage.
The mode is also the pprof sample name.
Optional dropped_samples records losses by reason; zero values may be omitted.
A nonzero collection count indicates incomplete results due to rate limiting
or collection capacity. The Grafana timeline shows this count on the right axis;
label filters affect only the flame graph.
A durably published empty result succeeds with an empty items array. Explicit limit=0 is invalid; only omission uses the default. limit defaults to 20 and is capped at 100. Encoded Profile data above 64 MiB returns 413 result_too_large; reduce limit and retry.
Each flame graph request can query at most 100000 windows, 1000000 samples, and 10000000 labels, counted before sample filtering. If a limit is exceeded, narrow the time range or add document filters. Query failures return no partial results. Raw Profile page limits do not cap flame graph aggregation.
Stop a Task
Stopping is an asynchronous intent accepted for tasks in pending, running, or stopping:
curl -sS \
-X POST \
-H "Authorization: Bearer ${API_TOKEN}" \
"${API_BASE}/v1/profiling/${JOB_ID}/stop"
Success returns 200 OK with the current task snapshot. Terminal tasks return 409 Conflict. Because results may be incomplete, stopped tasks do not support result queries.
Unified flame graph queries
Grafana uses the Pyroscope-compatible endpoints under /v1/profiling/flamegraph/querier.v1.QuerierService/.
Requests and successful responses use binary application/proto and require administrator access. The id condition filters data without enforcing task ownership.
SelectMergeStacktraces selectors require scope="host" or scope="container".
region is the Agent’s configured region; hostname is only the collection node.
Container queries require container_id or one task id. Host queries cannot include container filters.
For example: {region="example",hostname="node-01",scope="container",container_id="…",id="…"}.
Document labels (node, container, task, and similar metadata) accept one equality condition. On this endpoint the wildcard values *, all,
and the empty string only drop the restriction for that label, so
{scope="host",hostname="*",id="job-1"} still selects one task; scope is still required.
Container filters also support container_name, container_hostname, container_namespace, container_type, and container_qos, each matching the complete field value. Names and namespaces do not replace the container ID.
Repeating a label with the same value is accepted, while contradictory duplicates such as
{hostname="host-a",hostname="host-b"} are rejected with 400 and the error reports both
values, because one query cannot select two hosts. A document matcher that uses any operator other
than = is rejected as well, including hostname!="*".
Sample labels pid, comm, cpu, and extension labels support = and =~, combined with AND.
For example, {scope="host",id="job-1",pid="1234",cpu="0"} filters by host PID and CPU 0.
Native on-CPU cpu identifies the CPU at sampling time. Native off-CPU cpu identifies the
original switch-out CPU, preserved across blocked/runqueue phases even if the thread wakes
or resumes on another CPU. pid is the host TGID; comm is the sampled thread’s name,
captured at switch-out for off-CPU. Historical samples without cpu are not assigned CPU 0.
Omit a condition or use =~".*" for all values,
including missing labels. Values all, *, and empty strings are literal. Multi-valued labels
match their value sets; numeric labels use forms such as 4096 bytes.
Physical usage selects the latest snapshot before filtering, without falling back to older snapshots.
Native off-CPU samples use offcpu_reason to attribute time away from the CPU:
| Value |
Meaning |
blocked |
Blocked time from switch-out to wakeup |
runqueue |
Waiting for CPU after wakeup |
runqueue_preempted |
Waiting for CPU after preemption |
runqueue_yielded |
Waiting for CPU after a non-preemptive switch-out while runnable |
runqueue_missed_wakeup |
No wakeup was observed, so blocked and run queue time cannot be separated |
unknown |
Unrecognized event kind |
For example, {scope="host",id="job-1",offcpu_reason="blocked"} selects blocked time.
offcpu_reason=~"runqueue.*" selects all reasons with the runqueue prefix;
runqueue_missed_wakeup does not establish that the interval was spent on a run queue.
Sample weights are in nanoseconds.
Label queries use LabelNames and LabelValues:
| Field |
Constraints |
matchers |
One selector string. LabelValues requires __profile_type__; for physical_usage sample labels, both methods require the type and one task id. |
name |
Required label name for LabelValues, such as pid. |
start, end |
Unix milliseconds, with end >= start. Omitted fields become 0, not an unbounded range. |
Example request fields; encode as Protobuf before sending:
{
"name": "pid",
"matchers": ["{__profile_type__=\"process_cpu:cpu:nanoseconds:cpu:nanoseconds\",id=\"job-1\"}"],
"start": "1787565600000",
"end": "1787565660000"
}
Responses contain a names list, such as {"names":["1234","5678"]}. Sample-label results are sorted and deduplicated; unknown sample labels return an empty list. Without matchers, LabelNames returns the document-label list; with conditions, it returns that list plus observed sample labels. More than 1000 sample-label names or values for one sample label returns an error. Document-label queries return at most 100 values and reject sample filters. scope always returns host and container; unknown labels beginning with __ are rejected.
result_url includes the stored windows’ Region and actual profile type. Results without windows do not provide a dashboard link.
For Grafana label-filter controls, see View the Flame Graph.
10.6 - profiler CLI Parameters
This reference lists profiler parameters, defaults, and applicability. See CLI Collection for prerequisites and examples, and Output Formats to choose a format.
Specify --output-format explicitly when collecting samples. You can omit --output-path with --output-format=tui. Other formats require an output path.
General
| Parameter |
Default |
Applies To |
Description |
--type, -t |
None |
Collection |
Observation type: cpu or memory; required |
--language, -l |
None |
Collection |
Target language: c, c++, go, java, or python; required |
--pid, -p |
None |
Collection |
Target PID; Java and Python accept comma-separated PIDs, native collection accepts at most one |
--container-id |
None |
Collection |
Target container ID; native CPU combines it with --pid as an AND filter using the host PID; otherwise mutually exclusive with --pid |
--duration, -d |
10 |
Collection |
Total collection duration in seconds, minimum 1 |
--aggr-interval |
10 |
Collection |
Aggregation interval in seconds; cannot exceed duration |
--freq, -F |
99 |
CPU |
Samples per second; Java maximum: 1000 |
--output-path |
Optional for TUI |
Collection |
Local file, directory, or stdout. Use a Unix socket for remote-store. End new directory paths with /. Specify a path explicitly for other formats |
--output-format |
Required |
Collection |
collapsed, flamegraph, svg, tui, json, speedscope, chrometrace or remote-store. chrometrace requires a time-based profile |
--tui-report FILE |
None |
Report replay |
Open a saved terminal flame graph report |
--max-concurrent-procs |
0 |
Java, Python |
Maximum concurrent collection child processes; 0 is unlimited |
--tool-path |
None |
Java, Python |
Shared root directory for external tools; required |
--binary-match-path |
None |
Java, Python |
Match target container processes by executable path |
--task-id |
Empty; generated internally for local output |
Collection (required for remote-store) |
Stable collection task ID shared by toolstream and remote storage |
--enable-pprof |
false |
Collection |
Serve this process’s Go runtime profiles on 127.0.0.1:6000 |
--version-format |
text |
Version queries |
Format for --version: text, json, or short |
--help, -h |
- |
All |
Show command help |
--version, -v |
- |
All |
Show version and build information |
These pprof endpoints describe the profiler process’s own Go runtime, not the --pid target or Java/Python collector subprocesses. The listener is now restricted to loopback rather than all interfaces; an occupied port fails startup.
Terminal flame graph and replay
--output-format=tui opens the flame graph in an interactive terminal after collection. Press v to cycle through the flame graph, the full frame list, and Top Table. Press r to return to the root of the current flame graph. Top Table sorts by descending Self by default. Press s to switch to descending Total.
The flame graph starts with call stacks alone. Press g (Group by) in the graph or frame list to enter a comma-separated list of cpu, comm, and pid fields, then press Enter to apply it. For example, cpu,comm groups by CPU, then by task name within each CPU. A missing label appears as field=?. Press Ctrl+U then Enter to clear the grouping, or Esc to cancel editing.
Top Table covers the entire collection. Self counts weight at the stack leaf. Total counts weight for every occurrence of the function in a stack, including recursive calls.
Use --output-path to save a gob report when you exit with q. A file path replaces the existing result at that path. A directory gets an automatically named profile_*.gob file. Omit the path or use stdout or - for terminal viewing only.
profiler --tui-report p.gob
--tui-report p.gob opens the report at p.gob in an interactive terminal. Use this option on its own. Replay requires a HuaTuo gob report and identifies it by its file header, regardless of the filename extension. Open reports only from trusted sources.
Collection
Native on-CPU and memory collection require Linux MEMBARRIER_CMD_GLOBAL support (CONFIG_MEMBARRIER enabled and NO_HZ_FULL inactive). Ring swaps depend on this command providing a sched-RCU grace period on Linux 4.18 and a unified RCU grace period on Linux 5.0 and later; expedited membarrier commands cannot replace it. An RCU stall can delay a swap and collection shutdown.
| Parameter |
Default |
Applies To |
Description |
--memory-mode |
None |
Native and Java memory |
Memory measurement; required with --type memory |
--cpu-list |
All CPUs |
Native CPU |
CPU list or ranges; off-CPU filtering uses the CPU where the task switches out |
--cpu-mode |
oncpu |
Native CPU |
oncpu samples by frequency; offcpu attributes blocked and runnable scheduling delays |
--require-hardware-pmu |
false |
Native on-CPU |
Require hardware PMU sampling; fail if unavailable without falling back to software CPU clock |
--offcpu-phase |
all |
Native off-CPU |
Accumulate all, blocked, or runqueue time |
--offcpu-min-duration-us |
1000 |
Native off-CPU |
Discard phases shorter than this duration in microseconds |
--offcpu-stats |
false |
Native off-CPU |
Collect BPF diagnostic statistics; adds overhead to error and cleanup paths |
--thread-group |
false |
Native |
Also collect other threads in the target PID’s thread group |
--physical-memory-probability |
100 |
Native physical memory |
Physical-memory event sampling probability from 1 to 100 |
--log-bpf-debug |
false |
Native |
Emit BPF debug events; not recommended for routine collection |
When the hardware PMU event or sampling is unsupported, the command exits with code 1 and identifies the error on stderr with Error: hardware_pmu_unavailable:. Permission and other startup errors do not use this marker.
--cpu-list replaces --cpuid without an alias. The IRQ tool also uses --cpu-list; its former --target-cpu option is removed. Upgrade calling scripts together with the tools.
Logging
| Parameter |
Default |
Description |
--log-level |
error |
trace, debug, info, warn, or error |
--log-file |
stdout |
Log file path or stdout |
--log-size |
100 |
Log rotation size in MB; 0 disables rotation. File output only |
--verbose |
false |
Equivalent to --log-level debug --log-file stdout, overriding explicit log settings |
11 - Changelog
Browse feature changes, fixes, and compatibility notes by release: