Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- `--metrics-protocol` / `METRICS_PROTOCOL`: set `otlp` to send metrics as OTLP/HTTP
instead of Prometheus remote write (the default). Metric names and the `job` and
`instance` labels are the same over both.
- Open-source release of the Nudgebee Node Agent, forked from
[coroot/coroot-node-agent](https://github.com/coroot/coroot-node-agent).
- LLM observability pipeline: detects and parses LLM API traffic
Expand Down
31 changes: 27 additions & 4 deletions docs/fleet-install.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ an SSH loop.
- **Hosts:** Linux with systemd, amd64 or arm64, kernel 5.8 or newer. Windows and
macOS aren't supported.
- **Where the data goes:** the agent pushes to storage you run. Have these ready:
- a Prometheus remote-write receiver for metrics (`METRICS_ENDPOINT`)
- a Prometheus remote-write receiver for metrics, or an OTLP/HTTP one (`METRICS_ENDPOINT`)
- an OTLP/HTTP endpoint for traces and logs (`TRACES_ENDPOINT`, `LOGS_ENDPOINT`)
- an `API_KEY`, if your endpoints need one
- **Network:** each host needs outbound access to GitHub to download the release, and to
Expand All @@ -29,15 +29,38 @@ The ones a fleet usually sets:

| Variable | What it does |
|---|---|
| `METRICS_ENDPOINT` | Prometheus remote-write URL. |
| `METRICS_ENDPOINT` | Full URL metrics are sent to. |
| `METRICS_PROTOCOL` | `prometheus` (remote write, the default) or `otlp` (OTLP/HTTP). |
| `TRACES_ENDPOINT`, `LOGS_ENDPOINT` | OTLP/HTTP URLs. |
| `API_KEY` | Sent to the endpoints. |
| `TRACES_SAMPLING` | Fraction of traces kept, `0.0` to `1.0`. Default `1.0`. |
| `CA_FILE` | CA bundle for endpoints signed by a private CA. |

Set `METRICS_ENDPOINT`, `TRACES_ENDPOINT` and `LOGS_ENDPOINT` individually. `COLLECTOR_ENDPOINT`
sets all of them from one base URL, but it sends metrics to `<base>/v1/metrics` as Prometheus
remote-write, which an otel-collector doesn't accept.
sets all of them from one base URL and sends metrics to `<base>/v1/metrics`. An otel-collector
accepts that only with `METRICS_PROTOCOL=otlp`.

### Metrics over OTLP

Set `METRICS_PROTOCOL=otlp` and point `METRICS_ENDPOINT` at the receiver's metrics path:

| Receiver | `METRICS_ENDPOINT` |
|---|---|
| OpenTelemetry Collector | `http://<host>:4318/v1/metrics` |
| Prometheus 3.x, started with `--web.enable-otlp-receiver` | `http://<host>:9090/api/v1/otlp/v1/metrics` |
| VictoriaMetrics (single node) | `http://<host>:8428/opentelemetry/v1/metrics` |

Metric names are the same as over remote write, and so are `job` and `instance`:

- Names are already Prometheus names, so the default name translation in Prometheus and
VictoriaMetrics leaves them unchanged.
- Counters whose name doesn't end in `_total` are sent as gauges, so no suffix is added to them.
- VictoriaMetrics also stores `service.name` and `service.instance.id` as labels on every
series. Switching an existing host to OTLP therefore starts new series there.

Each protocol has its own buffer under `WAL_DIR` (`spool` and `spool-otlp`). Data not yet
delivered when you switch stays on disk and is sent only if you switch back. Delete the old
directory to reclaim the space.

When a metrics endpoint is set, the agent serves its own `/metrics` on `127.0.0.1:10300`.
This can't be changed with `LISTEN`.
Expand Down
3 changes: 3 additions & 0 deletions examples/ansible/vars.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ node_agent_version: v0.1.9 # pin a release; "latest" follows new releases on ev
node_agent_env:
# Metrics: Prometheus remote-write receiver (VictoriaMetrics, Prometheus, Mimir).
METRICS_ENDPOINT: "http://metrics.example.com:8428/api/v1/write"
# To send OTLP/HTTP instead (see docs/fleet-install.md for each receiver's path):
# METRICS_PROTOCOL: "otlp"
# METRICS_ENDPOINT: "http://otel.example.com:4318/v1/metrics"
# Traces and logs: OTLP/HTTP, normally an otel-collector.
TRACES_ENDPOINT: "http://otel.example.com:4318/v1/traces"
LOGS_ENDPOINT: "http://otel.example.com:4318/v1/logs"
Expand Down
1 change: 1 addition & 0 deletions flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ var (
CollectorEndpoint = kingpin.Flag("collector-endpoint", "A base endpoint URL for metrics, traces, logs, and profiles").Envar("COLLECTOR_ENDPOINT").URL()
ApiKey = kingpin.Flag("api-key", "API key for the upstream collector").Envar("API_KEY").String()
MetricsEndpoint = kingpin.Flag("metrics-endpoint", "The URL of the endpoint to send metrics to").Envar("METRICS_ENDPOINT").URL()
MetricsProtocol = kingpin.Flag("metrics-protocol", "How metrics are sent to the metrics endpoint: prometheus (remote write) or otlp (OTLP/HTTP)").Default("prometheus").Envar("METRICS_PROTOCOL").Enum("prometheus", "otlp")
TracesEndpoint = kingpin.Flag("traces-endpoint", "The URL of the endpoint to send traces to").Envar("TRACES_ENDPOINT").URL()
TracesSampling = kingpin.Flag("traces-sampling", "Trace sampling rate (0.0 to 1.0)").Default("1.0").Envar("TRACES_SAMPLING").Float64()
LogsEndpoint = kingpin.Flag("logs-endpoint", "The URL of the endpoint to send logs to").Envar("LOGS_ENDPOINT").URL()
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ require (
github.com/gobwas/glob v0.2.3
github.com/klauspost/compress v1.20.3
github.com/moby/moby/client v0.6.2
go.opentelemetry.io/proto/otlp v1.11.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.12
gotest.tools v2.2.0+incompatible
Expand Down Expand Up @@ -170,7 +171,6 @@ require (
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/dig v1.17.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
Expand Down
2 changes: 1 addition & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ SYSTEMD_SERVICE=${SYSTEM_NAME}.service
UNINSTALL_SH=${BIN_DIR}/${SYSTEM_NAME}-uninstall.sh
FILE_SERVICE=${SYSTEMD_DIR}/${SYSTEMD_SERVICE}
FILE_ENV=${SYSTEMD_DIR}/${SYSTEMD_SERVICE}.env
ENV_VARS="^(LISTEN|CGROUPFS_ROOT|DISABLE_LOG_PARSING|DISABLE_PINGER|DISABLE_L7_TRACING|DISABLE_GPU_MONITORING|TRACK_PUBLIC_NETWORK|EPHEMERAL_PORT_RANGE|PROVIDER|REGION|AVAILABILITY_ZONE|INSTANCE_TYPE|INSTANCE_LIFE_CYCLE|LOG_PER_SECOND|LOG_BURST|COLLECTOR_ENDPOINT|API_KEY|METRICS_ENDPOINT|TRACES_ENDPOINT|LOGS_ENDPOINT|PROFILES_ENDPOINT|SCRAPE_INTERVAL|WAL_DIR)"
ENV_VARS="^(LISTEN|CGROUPFS_ROOT|DISABLE_LOG_PARSING|DISABLE_PINGER|DISABLE_L7_TRACING|DISABLE_GPU_MONITORING|TRACK_PUBLIC_NETWORK|EPHEMERAL_PORT_RANGE|PROVIDER|REGION|AVAILABILITY_ZONE|INSTANCE_TYPE|INSTANCE_LIFE_CYCLE|LOG_PER_SECOND|LOG_BURST|COLLECTOR_ENDPOINT|API_KEY|METRICS_ENDPOINT|METRICS_PROTOCOL|TRACES_ENDPOINT|LOGS_ENDPOINT|PROFILES_ENDPOINT|SCRAPE_INTERVAL|WAL_DIR)"

info()
{
Expand Down
195 changes: 195 additions & 0 deletions prom/otlp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package prom

import (
"bytes"
"compress/gzip"
"io"
"math"
"sort"
"strings"

dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
collectorpb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/klog/v2"
)

// encodeOTLP builds a gzipped OTLP/HTTP request body.
//
// A store must end up with the same series as over remote write, because queries
// select by exact name and by `job` and `instance`. So names are sent as they are
// with no unit (stores derive suffixes from units), and `job` and `instance` are
// set on every data point (not every store derives them from service.*).
func encodeOTLP(mfs []*dto.MetricFamily, timestampMs int64, extraLabels map[string]string) ([]byte, error) {
data, err := proto.Marshal(buildOTLPRequest(mfs, timestampMs, extraLabels))
if err != nil {
return nil, err
}
buf := &bytes.Buffer{}
w := gzip.NewWriter(buf)
if _, err = w.Write(data); err != nil {
return nil, err
}
if err = w.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
Comment on lines +3 to +42

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To avoid high CPU overhead and excessive memory allocations on every scrape/encode cycle, reuse gzip.Writer instances using a sync.Pool.

import (
	"bytes"
	"compress/gzip"
	"io"
	"math"
	"sort"
	"strings"
	"sync"

	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/model"
	collectorpb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
	"k8s.io/klog/v2"
)

var gzipWriterPool = sync.Pool{
	New: func() interface{} {
		return gzip.NewWriter(io.Discard)
	},
}

// encodeOTLP builds a gzipped OTLP/HTTP request body.
//
// A store must end up with the same series as over remote write, because queries
// select by exact name and by 'job' and 'instance'. So names are sent as they are
// with no unit (stores derive suffixes from units), and 'job' and 'instance' are
// set on every data point (not every store derives them from service.*).
func encodeOTLP(mfs []*dto.MetricFamily, timestampMs int64, extraLabels map[string]string) ([]byte, error) {
	data, err := proto.Marshal(buildOTLPRequest(mfs, timestampMs, extraLabels))
	if err != nil {
		return nil, err
	}
	buf := &bytes.Buffer{}
	w := gzipWriterPool.Get().(*gzip.Writer)
	w.Reset(buf)
	defer gzipWriterPool.Put(w)
	if _, err = w.Write(data); err != nil {
		return nil, err
	}
	if err = w.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}


func buildOTLPRequest(mfs []*dto.MetricFamily, timestampMs int64, extraLabels map[string]string) *collectorpb.ExportMetricsServiceRequest {
ts := uint64(timestampMs) * 1e6
metrics := make([]*metricspb.Metric, 0, len(mfs))
for _, mf := range mfs {
if m := otlpMetric(mf, ts, extraLabels); m != nil {
metrics = append(metrics, m)
}
}
// No service.version and no instrumentation scope: VictoriaMetrics puts both on
// every series, so each agent upgrade would start new ones. node_agent_info has
// the version.
resource := &resourcepb.Resource{Attributes: otlpAttributes(map[string]string{
"service.name": extraLabels[model.JobLabel],
"service.instance.id": extraLabels[model.InstanceLabel],
})}
return &collectorpb.ExportMetricsServiceRequest{
ResourceMetrics: []*metricspb.ResourceMetrics{{
Resource: resource,
ScopeMetrics: []*metricspb.ScopeMetrics{{Metrics: metrics}},
}},
}
}

func otlpMetric(mf *dto.MetricFamily, ts uint64, extraLabels map[string]string) *metricspb.Metric {
var numbers []*metricspb.NumberDataPoint
var histograms []*metricspb.HistogramDataPoint
for _, m := range mf.Metric {
attrs := otlpAttributes(otlpLabels(m, extraLabels))
switch {
case m.Gauge != nil:
numbers = append(numbers, numberPoint(attrs, 0, ts, m.GetGauge().GetValue()))
case m.Counter != nil:
numbers = append(numbers, numberPoint(attrs, startTime(m.GetCounter().GetCreatedTimestamp()), ts, m.GetCounter().GetValue()))
case m.Histogram != nil:
histograms = append(histograms, histogramPoint(attrs, startTime(m.GetHistogram().GetCreatedTimestamp()), ts, m.GetHistogram()))
}
}

res := &metricspb.Metric{Name: mf.GetName(), Description: mf.GetHelp()}
switch {
case len(histograms) > 0:
res.Data = &metricspb.Metric_Histogram{Histogram: &metricspb.Histogram{
DataPoints: histograms,
AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
}}
case len(numbers) == 0:
return nil
// A store appends `_total` to a monotonic sum that lacks it, which would
// rename the series. Such a counter goes as a gauge to keep its name.
case mf.GetType() == dto.MetricType_COUNTER && strings.HasSuffix(mf.GetName(), "_total"):
res.Data = &metricspb.Metric_Sum{Sum: &metricspb.Sum{
DataPoints: numbers,
AggregationTemporality: metricspb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,
IsMonotonic: true,
}}
default:
res.Data = &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{DataPoints: numbers}}
}
return res
}

// startTime is when a cumulative series began, or 0 (unknown) for one the agent
// only reads, such as a kernel or cgroup counter. The agent's own start time would
// be wrong for both: host counters outlive it, and a series can be deleted and
// recreated while it runs.
func startTime(created *timestamppb.Timestamp) uint64 {
if created == nil {
return 0
}
return uint64(created.AsTime().UnixNano())
}

// otlpLabels gives the metric's own labels precedence, as makeLabelsMap does for
// remote write. Empty values are dropped: Prometheus treats them as absent.
func otlpLabels(m *dto.Metric, extraLabels map[string]string) map[string]string {
labels := make(map[string]string, len(m.Label)+len(extraLabels))
for k, v := range extraLabels {
labels[k] = v
}
for _, l := range m.Label {
labels[l.GetName()] = l.GetValue()
}
for k, v := range labels {
if v == "" {
delete(labels, k)
}
}
return labels
}

func otlpAttributes(labels map[string]string) []*commonpb.KeyValue {
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys)
res := make([]*commonpb.KeyValue, 0, len(keys))
for _, k := range keys {
// protobuf refuses to marshal invalid UTF-8, which would lose the whole scrape.
v := strings.ToValidUTF8(labels[k], "�")
res = append(res, &commonpb.KeyValue{Key: k, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: v}}})
}
return res
}

func numberPoint(attrs []*commonpb.KeyValue, start, ts uint64, value float64) *metricspb.NumberDataPoint {
return &metricspb.NumberDataPoint{
Attributes: attrs,
StartTimeUnixNano: start,
TimeUnixNano: ts,
Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: value},
}
}

// histogramPoint turns Prometheus cumulative buckets into OTLP per-bucket counts,
// whose last entry is the implicit +Inf bucket.
func histogramPoint(attrs []*commonpb.KeyValue, start, ts uint64, h *dto.Histogram) *metricspb.HistogramDataPoint {
sum := h.GetSampleSum()
p := &metricspb.HistogramDataPoint{
Attributes: attrs,
StartTimeUnixNano: start,
TimeUnixNano: ts,
Count: h.GetSampleCount(),
Sum: &sum,
}
var previous uint64
for _, b := range h.Bucket {
if math.IsInf(b.GetUpperBound(), 1) {
continue
}
p.ExplicitBounds = append(p.ExplicitBounds, b.GetUpperBound())
p.BucketCounts = append(p.BucketCounts, b.GetCumulativeCount()-previous)
previous = b.GetCumulativeCount()
}
p.BucketCounts = append(p.BucketCounts, h.GetSampleCount()-previous)
return p
}

// logRejectedPoints reports data points a receiver refused while accepting the request.
func logRejectedPoints(body io.Reader) {
data, err := io.ReadAll(io.LimitReader(body, 64*1024))
if err != nil {
return
}
res := &collectorpb.ExportMetricsServiceResponse{}
if err = proto.Unmarshal(data, res); err != nil {
return
}
if ps := res.GetPartialSuccess(); ps.GetRejectedDataPoints() > 0 {
klog.Warningf("the receiver rejected %d data points: %s", ps.GetRejectedDataPoints(), ps.GetErrorMessage())
}
}
Comment on lines +182 to +195

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Add a helper function readErrorBody to read a short summary of the response body. This will be used in remote_writer.go to log detailed rejection reasons from the collector.

// logRejectedPoints reports data points a receiver refused while accepting the request.
func logRejectedPoints(body io.Reader) {
	data, err := io.ReadAll(io.LimitReader(body, 64*1024))
	if err != nil {
		return
	}
	res := &collectorpb.ExportMetricsServiceResponse{}
	if err = proto.Unmarshal(data, res); err != nil {
		return
	}
	if ps := res.GetPartialSuccess(); ps.GetRejectedDataPoints() > 0 {
		klog.Warningf("the receiver rejected %d data points: %s", ps.GetRejectedDataPoints(), ps.GetErrorMessage())
	}
}

// readErrorBody reads a short summary of the response body for error reporting.
func readErrorBody(body io.Reader) string {
	data, err := io.ReadAll(io.LimitReader(body, 1024))
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

Loading