-
Notifications
You must be signed in to change notification settings - Fork 8
feat: add Prometheus metrics for observability #177
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
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5f9a942
feat: add Prometheus metrics for observability
kacpersaw 15c7735
feat: update Helm chart for metrics, default to disabled for backward…
kacpersaw d866562
test: add end-to-end metrics endpoint test
kacpersaw c781727
fix: initialize metric labels so they appear at zero in /metrics
kacpersaw 2b15e2e
fix: handle errcheck lint for resp.Body.Close in test
kacpersaw b596302
refactor: move metrics into instrumentedClient wrapper, remove errors…
kacpersaw 927b65f
fix: remove redundant embedded field from selector (staticcheck QF1008)
kacpersaw cd7784a
refactor: use custom prometheus registry and method enum
kacpersaw f4b1ebe
fix: goimports formatting in logger_test.go
kacpersaw 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,86 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/url" | ||
|
|
||
| "github.com/coder/coder/v2/codersdk" | ||
| "github.com/coder/coder/v2/codersdk/agentsdk" | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promhttp" | ||
| "storj.io/drpc" | ||
| ) | ||
|
|
||
| var ( | ||
| requestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
| Name: "coder_logstream_requests_total", | ||
| Help: "Total number of requests to the Coder API.", | ||
| }, []string{"method", "status"}) | ||
| ) | ||
|
|
||
| func init() { | ||
| prometheus.MustRegister(requestsTotal) | ||
|
|
||
| // Initialize label combinations so they appear in /metrics at zero. | ||
| for _, method := range []string{"PostLogSource", "ConnectRPC", "SendLog"} { | ||
| requestsTotal.WithLabelValues(method, "success") | ||
| requestsTotal.WithLabelValues(method, "failure") | ||
| } | ||
| } | ||
|
|
||
| func metricsHandler() http.Handler { | ||
| return promhttp.Handler() | ||
| } | ||
|
|
||
| // record is a helper that increments the appropriate request counter. | ||
| func record(method string, err error) { | ||
| if err != nil { | ||
| requestsTotal.WithLabelValues(method, "failure").Inc() | ||
| } else { | ||
| requestsTotal.WithLabelValues(method, "success").Inc() | ||
| } | ||
| } | ||
|
|
||
| // instrumentedClient wraps agentsdk.Client to record Prometheus metrics | ||
| // on every API call. This keeps metric instrumentation in one place | ||
| // rather than scattered across call sites. | ||
| type instrumentedClient struct { | ||
| *agentsdk.Client | ||
| } | ||
|
|
||
| func newInstrumentedClient(coderURL *url.URL, token string) *instrumentedClient { | ||
| return &instrumentedClient{ | ||
| Client: agentsdk.New(coderURL, agentsdk.WithFixedToken(token)), | ||
| } | ||
| } | ||
|
|
||
| func (c *instrumentedClient) PostLogSource(ctx context.Context, req agentsdk.PostLogSourceRequest) (codersdk.WorkspaceAgentLogSource, error) { | ||
| resp, err := c.Client.PostLogSource(ctx, req) | ||
| record("PostLogSource", err) | ||
| return resp, err | ||
| } | ||
|
|
||
| // connectLogDest establishes the appropriate RPC connection based on | ||
| // server capabilities, recording metrics for the attempt. | ||
| func (c *instrumentedClient) connectLogDest(ctx context.Context, supportsRole bool) (agentsdk.LogDest, drpc.Conn, error) { | ||
| if supportsRole { | ||
| arpc, _, err := c.ConnectRPC28WithRole(ctx, "logstream-kube") | ||
| record("ConnectRPC", err) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| return arpc, arpc.DRPCConn(), nil | ||
| } | ||
| arpc, err := c.ConnectRPC20(ctx) | ||
| record("ConnectRPC", err) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| return arpc, arpc.DRPCConn(), nil | ||
| } | ||
|
|
||
| // recordSendResult records the result of a log send operation. | ||
| func recordSendResult(err error) { | ||
| record("SendLog", err) | ||
| } | ||
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,91 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "io" | ||
| "net" | ||
| "net/http" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| dto "github.com/prometheus/client_model/go" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func getCounterValue(t *testing.T, cv *prometheus.CounterVec, labels ...string) float64 { | ||
| t.Helper() | ||
| m := &dto.Metric{} | ||
| c, err := cv.GetMetricWithLabelValues(labels...) | ||
| require.NoError(t, err) | ||
| require.NoError(t, c.Write(m)) | ||
| return m.GetCounter().GetValue() | ||
| } | ||
|
|
||
| func TestMetricsIncrement(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| // Record baseline values (metrics are global and may have been | ||
| // incremented by other tests running in the same process). | ||
|
kacpersaw marked this conversation as resolved.
Outdated
|
||
| baseSuccess := getCounterValue(t, requestsTotal, "PostLogSource", "success") | ||
| baseFailure := getCounterValue(t, requestsTotal, "PostLogSource", "failure") | ||
| baseSendSuccess := getCounterValue(t, requestsTotal, "SendLog", "success") | ||
|
|
||
| // Simulate success via record helper | ||
| record("PostLogSource", nil) | ||
| require.Equal(t, baseSuccess+1, getCounterValue(t, requestsTotal, "PostLogSource", "success")) | ||
|
|
||
| // Simulate failure via record helper | ||
| record("PostLogSource", io.ErrUnexpectedEOF) | ||
| require.Equal(t, baseFailure+1, getCounterValue(t, requestsTotal, "PostLogSource", "failure")) | ||
|
|
||
| // Simulate send success | ||
| recordSendResult(nil) | ||
| require.Equal(t, baseSendSuccess+1, getCounterValue(t, requestsTotal, "SendLog", "success")) | ||
| } | ||
|
|
||
| func TestMetricsHandler(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| handler := metricsHandler() | ||
| require.NotNil(t, handler) | ||
| } | ||
|
|
||
| func TestMetricsEndpoint(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| // Pick a random free port. | ||
| listener, err := net.Listen("tcp", "127.0.0.1:0") | ||
| require.NoError(t, err) | ||
| addr := listener.Addr().String() | ||
| _ = listener.Close() | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.Handle("/metrics", metricsHandler()) | ||
| srv := &http.Server{Addr: addr, Handler: mux} | ||
| go func() { _ = srv.ListenAndServe() }() | ||
| t.Cleanup(func() { _ = srv.Close() }) | ||
|
|
||
| // Wait for the server to be ready. | ||
| require.Eventually(t, func() bool { | ||
| resp, err := http.Get("http://" + addr + "/metrics") | ||
| if err != nil { | ||
| return false | ||
| } | ||
| _ = resp.Body.Close() | ||
| return resp.StatusCode == http.StatusOK | ||
| }, 2*time.Second, 50*time.Millisecond) | ||
|
|
||
| // Bump a counter and verify it appears in the output. | ||
| record("PostLogSource", nil) | ||
|
|
||
| resp, err := http.Get("http://" + addr + "/metrics") | ||
| require.NoError(t, err) | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| require.NoError(t, err) | ||
|
|
||
| require.True(t, strings.Contains(string(body), "coder_logstream_requests_total"), | ||
| "expected coder_logstream_requests_total in metrics output") | ||
| } | ||
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.