Files
team/server/channels/app/platform/metrics_test.go
2d5af65601 MM Build 2025 - Skadoosh - Serve plugin metrics to standard /metrics endpoint (#34678)
* gather plugin metrics and serve on /metrics

* tests

* fix recent conflicts from master

* fix linting

* address review feedback: feature flag, route guard, and unit tests for plugin metrics

- Add PluginMetricsCollection feature flag (default true) to allow disabling plugin metric collection without a deploy
- Only wrap the /metrics handler with plugin metric collection (not arbitrary plugin routes, which would cause double-listing)
- Extract wrapping logic into wrapMetricsHandler for clarity
- Add unit tests for addPluginLabelToMetrics covering no-label, existing-label, comments, empty lines, and multiple metrics cases

* fix integration tests to use /metrics route so wrapMetricsHandler runs

* switch addPluginLabelToMetrics to use expfmt for correct label injection

Replace string manipulation with expfmt parse→mutate→re-encode, which
correctly handles all metric types, timestamps, and malformed input.
Output is normalized: blank lines are dropped and TYPE headers are
injected for undeclared metrics. Update unit tests accordingly.

* refine addPluginLabelToMetrics: log warnings, drop sort, use assert.Contains

- Log a warning (instead of silently discarding) on parse or encode errors,
  returning empty string in both cases
- Remove name sorting — metric family order is irrelevant to Prometheus scrapers
- Switch unit test assertions to assert.Contains per line so tests are
  order-independent

* replace strPtr helper with model.NewPointer

* fix gofmt: remove extra blank line

* replace existing plugin_id label instead of appending a duplicate

If a plugin already exports a plugin_id label, overwrite it rather than
appending a second one, which would produce invalid Prometheus output.
Add test coverage for the replace path.

* add missing test coverage per mattermost-build feedback

- Unit test: malformed input returns empty string without panicking
- Integration: PluginMetricsCollection=false excludes plugin metrics
- Integration: plugin returning non-200 status excluded from response
- Integration: plugin returning empty body excluded from response

* rename PluginMetricsCollection to AggregatePluginMetrics, default false

---------

Co-authored-by: Jesse Hallam <[email protected]>
2026-04-22 15:04:13 +00:00

169 lines
5.1 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package platform
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMetricsRouter(t *testing.T) {
logger := mlog.CreateTestLogger(t)
cfg := &model.Config{}
cfg.SetDefaults()
metrics := &platformMetrics{
cfgFn: func() *model.Config { return cfg },
logger: logger,
}
err := metrics.initMetricsRouter()
require.NoError(t, err)
server := httptest.NewServer(metrics.router)
t.Cleanup(server.Close)
client := server.Client()
for name, tc := range map[string]struct {
path string
method string
ExpectedBodyContains string
ExpectedCode int
}{
"root": {path: "", ExpectedBodyContains: "<div><a href=\"/debug/pprof/\">Profiling Root</a></div>"},
"root with slash": {path: "/", ExpectedBodyContains: "<div><a href=\"/debug/pprof/\">Profiling Root</a></div>"},
"debug redirect": {path: "/debug", ExpectedBodyContains: "<div><a href=\"/debug/pprof/\">Profiling Root</a></div>"},
"debug redirect with slash": {path: "/debug/", ExpectedBodyContains: "<div><a href=\"/debug/pprof/\">Profiling Root</a></div>"},
"pprof index page": {path: "/debug/pprof", ExpectedBodyContains: "<p>Set debug=1 as a query parameter to export in legacy text format</p>"},
"pprof index page with slash": {path: "/debug/pprof/", ExpectedBodyContains: "<p>Set debug=1 as a query parameter to export in legacy text format</p>"},
"pprof allocs": {path: "/debug/pprof/allocs"},
"pprof block": {path: "/debug/pprof/block"},
"pprof cmdline": {path: "/debug/pprof/cmdline"},
"pprof goroutine": {path: "/debug/pprof/goroutine"},
"pprof heap": {path: "/debug/pprof/heap"},
"pprof mutex": {path: "/debug/pprof/mutex"},
"pprof profile": {path: "/debug/pprof/profile?seconds=1"},
"pprof symbol": {path: "/debug/pprof/symbol"},
"pprof threadcreate": {path: "/debug/pprof/threadcreate"},
"pprof trace": {path: "/debug/pprof/trace"},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
method := http.MethodGet
if tc.method != "" {
method = tc.method
}
url := server.URL + tc.path
req, err := http.NewRequest(method, url, nil)
require.NoError(t, err, name)
resp, err := client.Do(req)
require.NoError(t, err, name)
t.Cleanup(func() {
err := resp.Body.Close()
assert.NoError(t, err)
})
expectedCode := 200
if tc.ExpectedCode != 0 {
expectedCode = tc.ExpectedCode
}
assert.Equal(t, expectedCode, resp.StatusCode)
if tc.ExpectedBodyContains != "" {
b, err := io.ReadAll(resp.Body)
require.NoError(t, err, name)
assert.Contains(t, string(b), tc.ExpectedBodyContains)
}
})
}
}
func TestAddPluginLabelToMetrics(t *testing.T) {
for name, tc := range map[string]struct {
input []string
pluginID string
expected []string
}{
"metric without labels": {
input: []string{"my_metric 42"},
pluginID: "com.example.plugin",
expected: []string{
"# TYPE my_metric untyped",
`my_metric{plugin_id="com.example.plugin"} 42`,
},
},
"metric with existing labels": {
input: []string{`my_metric{env="prod"} 42`},
pluginID: "com.example.plugin",
expected: []string{
"# TYPE my_metric untyped",
`my_metric{env="prod",plugin_id="com.example.plugin"} 42`,
},
},
"help and type comments are preserved": {
input: []string{
"# HELP my_metric A metric",
"# TYPE my_metric gauge",
"my_metric 42",
},
pluginID: "my-plugin",
expected: []string{
"# HELP my_metric A metric",
"# TYPE my_metric gauge",
`my_metric{plugin_id="my-plugin"} 42`,
},
},
"empty lines are dropped": {
// blank lines carry no semantic meaning in Prometheus text format
input: []string{"", "my_metric 1"},
pluginID: "p",
expected: []string{
"# TYPE my_metric untyped",
`my_metric{plugin_id="p"} 1`,
},
},
"existing plugin_id label is replaced not duplicated": {
input: []string{`my_metric{plugin_id="old-plugin"} 42`},
pluginID: "new-plugin",
expected: []string{
`my_metric{plugin_id="new-plugin"} 42`,
},
},
"multiple metrics are sorted and separated": {
input: []string{"metric_a 1", "metric_b 2"},
pluginID: "plug",
expected: []string{
"# TYPE metric_a untyped",
`metric_a{plugin_id="plug"} 1`,
"# TYPE metric_b untyped",
`metric_b{plugin_id="plug"} 2`,
},
},
} {
t.Run(name, func(t *testing.T) {
result := addPluginLabelToMetrics(strings.Join(tc.input, "\n")+"\n", tc.pluginID)
for _, line := range tc.expected {
assert.Contains(t, result, line)
}
})
}
}
func TestAddPluginLabelToMetricsMalformedInput(t *testing.T) {
result := addPluginLabelToMetrics("not valid prometheus text {{{", "my-plugin")
assert.Equal(t, "", result)
}