-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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
Add instrumentation handler to collector endpoints #2664
Merged
yurishkuro
merged 19 commits into
jaegertracing:master
from
dimitarvdimitrov:metric-for-unparsable-zipkin-spans
Nov 30, 2020
Merged
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
20fbdf7
Add instrumentation handler to collector endpoints
dimitarvdimitrov 0bb4540
Fix static check problems
dimitarvdimitrov 8888520
Add godoc for NewMetricsHandler
dimitarvdimitrov 274c17c
Fix import formatting
dimitarvdimitrov a521fa8
Up test coverage
dimitarvdimitrov d3a7adb
Rename packages and update license statements
dimitarvdimitrov e27b434
Up test coverage for server package
dimitarvdimitrov 042bcd7
Cache metric timers in httpmetrics
dimitarvdimitrov c0a283f
Add synchronisation in httpmetrics
dimitarvdimitrov ce04b38
Change server tests to use ephemeral ports
dimitarvdimitrov 17739dc
Replace string with struct keys in httpmetrics
dimitarvdimitrov 73f5086
Increase await timeout in httmetrics test
dimitarvdimitrov f683323
Merge branch 'master' into metric-for-unparsable-zipkin-spans
dimitarvdimitrov 056ccaa
Merge branch 'master' into metric-for-unparsable-zipkin-spans
dimitarvdimitrov 739a444
Simplify network calls in server tests
dimitarvdimitrov 9602149
Consolidate port strings in server tests
dimitarvdimitrov 84b1966
Clean up a Stringer.String() and zero value init
dimitarvdimitrov 00ff54b
Use httptest in collector/app/server tests
dimitarvdimitrov 9fbafb7
Merge branch 'master' into metric-for-unparsable-zipkin-spans
dimitarvdimitrov 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 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 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 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,67 @@ | ||||||
// Copyright (c) 2020 The Jaeger Authors. | ||||||
// | ||||||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
// you may not use this file except in compliance with the License. | ||||||
// You may obtain a copy of the License at | ||||||
// | ||||||
// http://www.apache.org/licenses/LICENSE-2.0 | ||||||
// | ||||||
// Unless required by applicable law or agreed to in writing, software | ||||||
// distributed under the License is distributed on an "AS IS" BASIS, | ||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
// See the License for the specific language governing permissions and | ||||||
// limitations under the License. | ||||||
|
||||||
package server | ||||||
|
||||||
import ( | ||||||
"fmt" | ||||||
"net" | ||||||
"net/http" | ||||||
"testing" | ||||||
"time" | ||||||
|
||||||
"github.com/stretchr/testify/assert" | ||||||
"github.com/stretchr/testify/require" | ||||||
"github.com/uber/jaeger-lib/metrics/metricstest" | ||||||
"go.uber.org/zap" | ||||||
|
||||||
"github.com/jaegertracing/jaeger/cmd/collector/app/handler" | ||||||
"github.com/jaegertracing/jaeger/pkg/healthcheck" | ||||||
) | ||||||
|
||||||
// test wrong port number | ||||||
func TestFailToListenHttp(t *testing.T) { | ||||||
logger, _ := zap.NewDevelopment() | ||||||
server, err := StartHTTPServer(&HTTPServerParams{ | ||||||
HostPort: ":-1", | ||||||
Logger: logger, | ||||||
}) | ||||||
assert.Nil(t, server) | ||||||
assert.EqualError(t, err, "listen tcp: address -1: invalid port") | ||||||
} | ||||||
|
||||||
func TestSpanCollectorHttp(t *testing.T) { | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
logger, _ := zap.NewDevelopment() | ||||||
params := &HTTPServerParams{ | ||||||
Handler: handler.NewJaegerSpanHandler(logger, &mockSpanProcessor{}), | ||||||
SamplingStore: &mockSamplingStore{}, | ||||||
MetricsFactory: metricstest.NewFactory(time.Hour), | ||||||
HealthCheck: healthcheck.New(), | ||||||
Logger: logger, | ||||||
} | ||||||
|
||||||
listener, err := net.Listen("tcp", ":0") | ||||||
require.NoError(t, err) | ||||||
defer listener.Close() | ||||||
|
||||||
server := &http.Server{Addr: listener.Addr().String()} | ||||||
defer server.Close() | ||||||
dimitarvdimitrov marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
serveHTTP(server, listener, params) | ||||||
|
||||||
url := fmt.Sprintf("http://%s", listener.Addr()) | ||||||
response, err := http.Post(url, "", nil) | ||||||
assert.NoError(t, err) | ||||||
assert.NotNil(t, response) | ||||||
} |
This file contains 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 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,66 @@ | ||
// Copyright (c) 2020 The Jaeger Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package server | ||
|
||
import ( | ||
"fmt" | ||
"net" | ||
"net/http" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"github.com/uber/jaeger-lib/metrics/metricstest" | ||
"go.uber.org/zap" | ||
|
||
"github.com/jaegertracing/jaeger/cmd/collector/app/handler" | ||
"github.com/jaegertracing/jaeger/pkg/healthcheck" | ||
) | ||
|
||
// test wrong port number | ||
func TestFailToListenZipkin(t *testing.T) { | ||
logger, _ := zap.NewDevelopment() | ||
server, err := StartZipkinServer(&ZipkinServerParams{ | ||
HostPort: ":-1", | ||
Logger: logger, | ||
}) | ||
assert.Nil(t, server) | ||
assert.EqualError(t, err, "listen tcp: address -1: invalid port") | ||
} | ||
|
||
func TestSpanCollectorZipkin(t *testing.T) { | ||
logger, _ := zap.NewDevelopment() | ||
params := &ZipkinServerParams{ | ||
Handler: handler.NewZipkinSpanHandler(logger, nil, nil), | ||
MetricsFactory: metricstest.NewFactory(time.Hour), | ||
HealthCheck: healthcheck.New(), | ||
Logger: logger, | ||
} | ||
|
||
listener, err := net.Listen("tcp", ":0") | ||
require.NoError(t, err) | ||
defer listener.Close() | ||
|
||
server := &http.Server{Addr: listener.Addr().String()} | ||
defer server.Close() | ||
|
||
serveZipkin(server, listener, params) | ||
|
||
url := fmt.Sprintf("http://%s", listener.Addr()) | ||
response, err := http.Post(url, "", nil) | ||
assert.NoError(t, err) | ||
assert.NotNil(t, response) | ||
} |
This file contains 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,120 @@ | ||
// Copyright (c) 2020 The Jaeger Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package httpmetrics | ||
|
||
import ( | ||
"net/http" | ||
"strconv" | ||
"sync" | ||
"time" | ||
|
||
"github.com/uber/jaeger-lib/metrics" | ||
) | ||
|
||
type statusRecorder struct { | ||
http.ResponseWriter | ||
status int | ||
wroteHeader bool | ||
} | ||
|
||
func (r *statusRecorder) WriteHeader(status int) { | ||
if r.wroteHeader { | ||
return | ||
} | ||
r.status = status | ||
r.wroteHeader = true | ||
r.ResponseWriter.WriteHeader(status) | ||
} | ||
|
||
// Wrap returns a handler that wraps the provided one and emits metrics based on the HTTP requests and responses. | ||
// It will record the HTTP response status, HTTP method, duration and path of the call. | ||
// The duration will be reported in metrics.Timer and the rest will be labels on that timer. | ||
dimitarvdimitrov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// | ||
// Do not use with HTTP endpoints that take parameters from URL path, such as `/user/{user_id}`, | ||
// because they will result in high cardinality metrics. | ||
func Wrap(h http.Handler, metricsFactory metrics.Factory) http.Handler { | ||
timers := newRequestDurations(metricsFactory) | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
start := time.Now() | ||
recorder := &statusRecorder{ResponseWriter: w} | ||
|
||
h.ServeHTTP(recorder, r) | ||
|
||
req := recordedRequest{ | ||
key: recordedRequestKey{ | ||
status: strconv.Itoa(recorder.status), | ||
path: r.URL.Path, | ||
method: r.Method, | ||
}, | ||
duration: time.Since(start), | ||
} | ||
timers.record(req) | ||
}) | ||
} | ||
|
||
type recordedRequestKey struct { | ||
method string | ||
path string | ||
status string | ||
} | ||
|
||
type recordedRequest struct { | ||
key recordedRequestKey | ||
duration time.Duration | ||
} | ||
|
||
type requestDurations struct { | ||
lock sync.RWMutex | ||
metrics metrics.Factory | ||
timers map[recordedRequestKey]metrics.Timer | ||
} | ||
|
||
func newRequestDurations(metricsFactory metrics.Factory) *requestDurations { | ||
return &requestDurations{ | ||
timers: make(map[recordedRequestKey]metrics.Timer), | ||
metrics: metricsFactory, | ||
} | ||
} | ||
|
||
func (r *requestDurations) record(request recordedRequest) { | ||
cacheKey := request.key | ||
|
||
r.lock.RLock() | ||
timer, ok := r.timers[cacheKey] | ||
r.lock.RUnlock() | ||
if !ok { | ||
r.lock.Lock() | ||
timer, ok = r.timers[cacheKey] | ||
if !ok { | ||
timer = buildTimer(r.metrics, cacheKey) | ||
r.timers[cacheKey] = timer | ||
} | ||
r.lock.Unlock() | ||
} | ||
|
||
timer.Record(request.duration) | ||
} | ||
|
||
func buildTimer(metricsFactory metrics.Factory, key recordedRequestKey) metrics.Timer { | ||
return metricsFactory.Timer(metrics.TimerOptions{ | ||
Name: "http.request.duration", | ||
Help: "Duration of HTTP requests", | ||
Tags: map[string]string{ | ||
"status": key.status, | ||
"path": key.path, | ||
"method": key.method, | ||
}, | ||
}) | ||
} |
This file contains 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,50 @@ | ||
// Copyright (c) 2020 The Jaeger Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package httpmetrics | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/uber/jaeger-lib/metrics/metricstest" | ||
) | ||
|
||
func TestNewMetricsHandler(t *testing.T) { | ||
dummyHandlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | ||
time.Sleep(time.Millisecond) | ||
w.WriteHeader(http.StatusAccepted) | ||
w.WriteHeader(http.StatusTeapot) // any subsequent statuses should be ignored | ||
}) | ||
|
||
mb := metricstest.NewFactory(time.Hour) | ||
handler := Wrap(dummyHandlerFunc, mb) | ||
|
||
req, err := http.NewRequest(http.MethodGet, "/subdir/qwerty", nil) | ||
assert.NoError(t, err) | ||
handler.ServeHTTP(httptest.NewRecorder(), req) | ||
|
||
for i := 0; i < 1000; i++ { | ||
_, gauges := mb.Snapshot() | ||
if _, ok := gauges["http.request.duration|method=GET|path=/subdir/qwerty|status=202.P999"]; ok { | ||
return | ||
} | ||
time.Sleep(15 * time.Millisecond) | ||
} | ||
|
||
assert.Fail(t, "gauge hasn't been updated within a reasonable amount of time") | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.