This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Practical Guides

Choose a guide by troubleshooting or integration goal. See Key Features for an overview.

Goal Guide
Configure event storage and verify writes Storage Services
Configure metric collection and Grafana dashboards Data Sources
Stream events over HTTP Kernel Event Subscription
Collect CPU and memory profiles Profiling Guide
Interpret collapsed stacks and flame graphs Flame Graph Formats
Analyze packet drops Packet Drops
Analyze TCP retransmissions and correlated drops Retransmission Tracing
Analyze softirq sources and preempted tasks IRQ Tracing
Run SchedBlame independently Standalone SchedBlame
Chart and compare scheduling contention SchedBlame Analysis

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:

docker logs opensearch

3. Configure huatuo-bamai

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"
}

3. Configure huatuo-bamai

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"
}

3. Configure huatuo-bamai

[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.

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.

Preconfigured Data Sources

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

Preconfigured Dashboards

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:

selector:
  app: huatuo

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:

  1. Open Dashboards -> Import in Grafana.
  2. Upload or paste build/docker/grafana/dashboards/*.json.
  3. Click Load.
  4. Select the huatuo-bamai-prom and huatuo-bamai-es data sources.
  5. Click Import.

You can also export dashboards from the HUATUO console:

  1. Visit http://console.huatuo.tech/dashboards.
  2. Log in and select a dashboard.
  3. Click Export -> Export as JSON.
  4. Select “Export the dashboard to use in another instance”.
  5. 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.

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

POST /v1/events/watch

Request Headers

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.

Response Format (SSE)

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:

: ping\n

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.

Event Format

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

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.

Choose a Format

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

Line Format

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.

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
# 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

dropwatch [flags]
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 - 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.

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:

make build

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.

Profile the tool’s Go runtime

--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.

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.

Goal Section
Run a remote CPU profile Quick Start
Collect directly on the target node CLI Collection
Choose output formats and analyze data Results
Manage tasks programmatically Profiling API
Look up defaults and limits CLI Parameters

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:

  1. Select a time range in the upper-right corner covering the collection period.
  2. Select Region, the node hostname, scope host, and this Task ID, then choose process_cpu:cpu:nanoseconds:cpu:nanoseconds as type.
  3. Inspect aggregated stacks for the task and time range; use Focus block to focus on a frame.
  4. Choose Both to show the flame graph and function statistics together.

Host CPU flame graph and function statistics

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:

make build

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.

  1. Confirm that the command finishes successfully, and check for collection errors, output errors, or sample-loss warnings.
  2. 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.
  3. 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

Output Formats

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.

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:

make build

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

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