-
Notifications
You must be signed in to change notification settings - Fork 816
OTLP Ingestion #5813
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
OTLP Ingestion #5813
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b46ff9f
Initial OTLP ingest support
Aneurysm9 da38947
Add resoure attribute conversion
Aneurysm9 b4046d5
Fix lint
friedrichg 95b754f
Put under /api/v1/otlp
friedrichg 5107edf
Re-use DecodeOTLPWriteRequest
friedrichg 11be7a8
Tests
friedrichg cc3d30f
Integration test
friedrichg c7cda19
Fix lint and minimal docs
friedrichg 88e23e8
Catch error
friedrichg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
//go:build requires_docker | ||
// +build requires_docker | ||
|
||
package integration | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
"time" | ||
|
||
"github.com/prometheus/common/model" | ||
"github.com/prometheus/prometheus/prompb" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
|
||
"github.com/cortexproject/cortex/integration/e2e" | ||
e2edb "github.com/cortexproject/cortex/integration/e2e/db" | ||
"github.com/cortexproject/cortex/integration/e2ecortex" | ||
) | ||
|
||
func TestOTLP(t *testing.T) { | ||
s, err := e2e.NewScenario(networkName) | ||
require.NoError(t, err) | ||
defer s.Close() | ||
|
||
// Start dependencies. | ||
minio := e2edb.NewMinio(9000, bucketName) | ||
require.NoError(t, s.StartAndWaitReady(minio)) | ||
|
||
// Start Cortex components. | ||
require.NoError(t, copyFileToSharedDir(s, "docs/configuration/single-process-config-blocks.yaml", cortexConfigFile)) | ||
|
||
// Start Cortex in single binary mode, reading the config from file and overwriting | ||
// the backend config to make it work with Minio. | ||
flags := map[string]string{ | ||
"-blocks-storage.s3.access-key-id": e2edb.MinioAccessKey, | ||
"-blocks-storage.s3.secret-access-key": e2edb.MinioSecretKey, | ||
"-blocks-storage.s3.bucket-name": bucketName, | ||
"-blocks-storage.s3.endpoint": fmt.Sprintf("%s-minio-9000:9000", networkName), | ||
"-blocks-storage.s3.insecure": "true", | ||
} | ||
|
||
cortex := e2ecortex.NewSingleBinaryWithConfigFile("cortex-1", cortexConfigFile, flags, "", 9009, 9095) | ||
require.NoError(t, s.StartAndWaitReady(cortex)) | ||
|
||
c, err := e2ecortex.NewClient(cortex.HTTPEndpoint(), cortex.HTTPEndpoint(), "", "", "user-1") | ||
require.NoError(t, err) | ||
|
||
// Push some series to Cortex. | ||
now := time.Now() | ||
series, expectedVector := generateSeries("series_1", now, prompb.Label{Name: "foo", Value: "bar"}) | ||
|
||
res, err := c.OTLP(series) | ||
require.NoError(t, err) | ||
require.Equal(t, 200, res.StatusCode) | ||
|
||
// Query the series. | ||
result, err := c.Query("series_1", now) | ||
require.NoError(t, err) | ||
require.Equal(t, model.ValVector, result.Type()) | ||
assert.Equal(t, expectedVector, result.(model.Vector)) | ||
|
||
labelValues, err := c.LabelValues("foo", time.Time{}, time.Time{}, nil) | ||
require.NoError(t, err) | ||
require.Equal(t, model.LabelValues{"bar"}, labelValues) | ||
|
||
labelNames, err := c.LabelNames(time.Time{}, time.Time{}) | ||
require.NoError(t, err) | ||
require.Equal(t, []string{"__name__", "foo"}, labelNames) | ||
|
||
// Check that a range query does not return an error to sanity check the queryrange tripperware. | ||
_, err = c.QueryRange("series_1", now.Add(-15*time.Minute), now, 15*time.Second) | ||
require.NoError(t, err) | ||
|
||
//TODO(friedrichg): test histograms | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
package push | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/go-kit/log/level" | ||
"github.com/prometheus/prometheus/model/labels" | ||
"github.com/prometheus/prometheus/prompb" | ||
"github.com/prometheus/prometheus/storage/remote" | ||
"github.com/prometheus/prometheus/storage/remote/otlptranslator/prometheusremotewrite" | ||
"github.com/weaveworks/common/httpgrpc" | ||
"github.com/weaveworks/common/middleware" | ||
"go.opentelemetry.io/collector/pdata/pcommon" | ||
"go.opentelemetry.io/collector/pdata/pmetric" | ||
|
||
"github.com/cortexproject/cortex/pkg/cortexpb" | ||
"github.com/cortexproject/cortex/pkg/util" | ||
"github.com/cortexproject/cortex/pkg/util/log" | ||
) | ||
|
||
// OTLPHandler is a http.Handler which accepts OTLP metrics. | ||
func OTLPHandler(sourceIPs *middleware.SourceIPExtractor, push Func) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
ctx := r.Context() | ||
logger := log.WithContext(ctx, log.Logger) | ||
if sourceIPs != nil { | ||
source := sourceIPs.Get(r) | ||
if source != "" { | ||
ctx = util.AddSourceIPsToOutgoingContext(ctx, source) | ||
logger = log.WithSourceIPs(source, logger) | ||
} | ||
} | ||
req, err := remote.DecodeOTLPWriteRequest(r) | ||
if err != nil { | ||
level.Error(logger).Log("err", err.Error()) | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
tsMap, err := prometheusremotewrite.FromMetrics(convertToMetricsAttributes(req.Metrics()), prometheusremotewrite.Settings{DisableTargetInfo: true}) | ||
if err != nil { | ||
level.Error(logger).Log("err", err.Error()) | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
prwReq := cortexpb.WriteRequest{ | ||
Source: cortexpb.API, | ||
Metadata: nil, | ||
SkipLabelNameValidation: false, | ||
} | ||
|
||
tsList := []cortexpb.PreallocTimeseries(nil) | ||
for _, v := range tsMap { | ||
tsList = append(tsList, cortexpb.PreallocTimeseries{TimeSeries: &cortexpb.TimeSeries{ | ||
Labels: makeLabels(v.Labels), | ||
Samples: makeSamples(v.Samples), | ||
Exemplars: makeExemplars(v.Exemplars), | ||
}}) | ||
} | ||
prwReq.Timeseries = tsList | ||
|
||
if _, err := push(ctx, &prwReq); err != nil { | ||
resp, ok := httpgrpc.HTTPResponseFromError(err) | ||
if !ok { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
if resp.GetCode()/100 == 5 { | ||
level.Error(logger).Log("msg", "push error", "err", err) | ||
} else if resp.GetCode() != http.StatusAccepted && resp.GetCode() != http.StatusTooManyRequests { | ||
level.Warn(logger).Log("msg", "push refused", "err", err) | ||
} | ||
http.Error(w, string(resp.Body), int(resp.Code)) | ||
} | ||
}) | ||
} | ||
|
||
func makeLabels(in []prompb.Label) []cortexpb.LabelAdapter { | ||
out := make(labels.Labels, 0, len(in)) | ||
for _, l := range in { | ||
out = append(out, labels.Label{Name: l.Name, Value: l.Value}) | ||
} | ||
return cortexpb.FromLabelsToLabelAdapters(out) | ||
} | ||
|
||
func makeSamples(in []prompb.Sample) []cortexpb.Sample { | ||
out := make([]cortexpb.Sample, 0, len(in)) | ||
for _, s := range in { | ||
out = append(out, cortexpb.Sample{ | ||
Value: s.Value, | ||
TimestampMs: s.Timestamp, | ||
}) | ||
} | ||
return out | ||
} | ||
|
||
func makeExemplars(in []prompb.Exemplar) []cortexpb.Exemplar { | ||
out := make([]cortexpb.Exemplar, 0, len(in)) | ||
for _, e := range in { | ||
out = append(out, cortexpb.Exemplar{ | ||
Labels: makeLabels(e.Labels), | ||
Value: e.Value, | ||
TimestampMs: e.Timestamp, | ||
}) | ||
} | ||
return out | ||
} | ||
|
||
func convertToMetricsAttributes(md pmetric.Metrics) pmetric.Metrics { | ||
cloneMd := pmetric.NewMetrics() | ||
md.CopyTo(cloneMd) | ||
rms := cloneMd.ResourceMetrics() | ||
for i := 0; i < rms.Len(); i++ { | ||
resource := rms.At(i).Resource() | ||
|
||
ilms := rms.At(i).ScopeMetrics() | ||
for j := 0; j < ilms.Len(); j++ { | ||
ilm := ilms.At(j) | ||
metricSlice := ilm.Metrics() | ||
for k := 0; k < metricSlice.Len(); k++ { | ||
addAttributesToMetric(metricSlice.At(k), resource.Attributes()) | ||
} | ||
} | ||
} | ||
return cloneMd | ||
} | ||
|
||
// addAttributesToMetric adds additional labels to the given metric | ||
func addAttributesToMetric(metric pmetric.Metric, labelMap pcommon.Map) { | ||
switch metric.Type() { | ||
case pmetric.MetricTypeGauge: | ||
addAttributesToNumberDataPoints(metric.Gauge().DataPoints(), labelMap) | ||
case pmetric.MetricTypeSum: | ||
addAttributesToNumberDataPoints(metric.Sum().DataPoints(), labelMap) | ||
case pmetric.MetricTypeHistogram: | ||
addAttributesToHistogramDataPoints(metric.Histogram().DataPoints(), labelMap) | ||
case pmetric.MetricTypeSummary: | ||
addAttributesToSummaryDataPoints(metric.Summary().DataPoints(), labelMap) | ||
case pmetric.MetricTypeExponentialHistogram: | ||
addAttributesToExponentialHistogramDataPoints(metric.ExponentialHistogram().DataPoints(), labelMap) | ||
} | ||
} | ||
|
||
func addAttributesToNumberDataPoints(ps pmetric.NumberDataPointSlice, newAttributeMap pcommon.Map) { | ||
for i := 0; i < ps.Len(); i++ { | ||
joinAttributeMaps(newAttributeMap, ps.At(i).Attributes()) | ||
} | ||
} | ||
|
||
func addAttributesToHistogramDataPoints(ps pmetric.HistogramDataPointSlice, newAttributeMap pcommon.Map) { | ||
for i := 0; i < ps.Len(); i++ { | ||
joinAttributeMaps(newAttributeMap, ps.At(i).Attributes()) | ||
} | ||
} | ||
|
||
func addAttributesToSummaryDataPoints(ps pmetric.SummaryDataPointSlice, newAttributeMap pcommon.Map) { | ||
for i := 0; i < ps.Len(); i++ { | ||
joinAttributeMaps(newAttributeMap, ps.At(i).Attributes()) | ||
} | ||
} | ||
|
||
func addAttributesToExponentialHistogramDataPoints(ps pmetric.ExponentialHistogramDataPointSlice, newAttributeMap pcommon.Map) { | ||
for i := 0; i < ps.Len(); i++ { | ||
joinAttributeMaps(newAttributeMap, ps.At(i).Attributes()) | ||
} | ||
} | ||
|
||
func joinAttributeMaps(from, to pcommon.Map) { | ||
from.Range(func(k string, v pcommon.Value) bool { | ||
v.CopyTo(to.PutEmpty(k)) | ||
return true | ||
}) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.