-
Notifications
You must be signed in to change notification settings - Fork 894
feat: expose user seat limits as Prometheus metrics #10169
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 11 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
3fa3258
WIP
mtojek 4048965
WIP
mtojek fef0939
doTick
mtojek d1e1bab
Remove fetchEntitlements
mtojek 395d64b
Fix: nolint
mtojek 157cbe1
Unit test
mtojek 3e7cb97
imports
mtojek 4abcd00
Fix: lint
mtojek 9ee99d5
entitled
mtojek 77bd93d
Merge branch 'main' into 9983-license-prometheus
mtojek b16f1c0
fix: sigsegv
mtojek 366f33a
WIP
mtojek 88cf939
Merge branch 'main' into 9983-license-prometheus-2
mtojek f1f24be
WIP
mtojek 46d190c
WIP
mtojek 630a115
fix: db
mtojek cadbaa8
fix
mtojek d221c46
cleanup
mtojek 073dce9
fix
mtojek 0c6d00e
Collector adjustments
mtojek b8a969d
Fix tests
mtojek c4c434e
Given-When-Then
mtojek 433fb7a
Merge branch 'main' into 9983-license-prometheus
mtojek 8845fb3
Use const metrics
mtojek 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
package prometheusmetrics | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"sync/atomic" | ||
"time" | ||
|
||
"github.com/prometheus/client_golang/prometheus" | ||
|
||
"cdr.dev/slog" | ||
|
||
"github.com/coder/coder/v2/codersdk" | ||
) | ||
|
||
type LicenseMetrics struct { | ||
interval time.Duration | ||
logger slog.Logger | ||
registry *prometheus.Registry | ||
|
||
Entitlements atomic.Pointer[codersdk.Entitlements] | ||
} | ||
|
||
type LicenseMetricsOptions struct { | ||
Interval time.Duration | ||
Logger slog.Logger | ||
Registry *prometheus.Registry | ||
} | ||
|
||
func NewLicenseMetrics(opts *LicenseMetricsOptions) (*LicenseMetrics, error) { | ||
if opts.Interval == 0 { | ||
opts.Interval = 1 * time.Minute | ||
} | ||
if opts.Registry == nil { | ||
opts.Registry = prometheus.NewRegistry() | ||
} | ||
|
||
return &LicenseMetrics{ | ||
interval: opts.Interval, | ||
logger: opts.Logger, | ||
registry: opts.Registry, | ||
}, nil | ||
} | ||
|
||
func (lm *LicenseMetrics) Collect(ctx context.Context) (func(), error) { | ||
activeUsersGauge := NewCachedGaugeVec(prometheus.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "license", | ||
Name: "active_users", | ||
Help: `The number of active users.`, | ||
}, []string{"entitled"})) | ||
mtojek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
err := lm.registry.Register(activeUsersGauge) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
userLimitGauge := NewCachedGaugeVec(prometheus.NewGaugeVec(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "license", | ||
Name: "user_limit", | ||
Help: "The user seats limit based on the active Coder license.", | ||
}, []string{"entitled"})) | ||
err = lm.registry.Register(userLimitGauge) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
ctx, cancelFunc := context.WithCancel(ctx) | ||
done := make(chan struct{}) | ||
ticker := time.NewTicker(time.Nanosecond) | ||
|
||
doTick := func() { | ||
mtojek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
defer ticker.Reset(lm.interval) | ||
|
||
entitlements := lm.Entitlements.Load() | ||
if entitlements == nil { | ||
lm.logger.Warn(ctx, `entitlements have not been loaded yet`) | ||
return | ||
} | ||
|
||
if entitlements.Features == nil { | ||
lm.logger.Warn(ctx, `entitlements features are undefined`) | ||
return | ||
} | ||
|
||
userLimitEntitlement, ok := entitlements.Features[codersdk.FeatureUserLimit] | ||
if !ok { | ||
lm.logger.Warn(ctx, `"user_limit" entitlement is not present`) | ||
return | ||
} | ||
|
||
enabled := fmt.Sprintf("%v", userLimitEntitlement.Enabled) | ||
if userLimitEntitlement.Actual != nil { | ||
activeUsersGauge.WithLabelValues(VectorOperationSet, float64(*userLimitEntitlement.Actual), enabled) | ||
} else { | ||
activeUsersGauge.WithLabelValues(VectorOperationSet, 0, enabled) | ||
} | ||
|
||
if userLimitEntitlement.Limit != nil { | ||
userLimitGauge.WithLabelValues(VectorOperationSet, float64(*userLimitEntitlement.Limit), enabled) | ||
} else { | ||
userLimitGauge.WithLabelValues(VectorOperationSet, 0, enabled) | ||
} | ||
|
||
activeUsersGauge.Commit() | ||
userLimitGauge.Commit() | ||
} | ||
|
||
go func() { | ||
defer close(done) | ||
defer ticker.Stop() | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-ticker.C: | ||
doTick() | ||
} | ||
} | ||
}() | ||
return func() { | ||
cancelFunc() | ||
<-done | ||
}, nil | ||
} |
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,89 @@ | ||
package prometheusmetrics_test | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"os" | ||
"reflect" | ||
"testing" | ||
"time" | ||
|
||
"github.com/aws/smithy-go/ptr" | ||
"github.com/prometheus/client_golang/prometheus" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
|
||
"cdr.dev/slog" | ||
"cdr.dev/slog/sloggers/slogtest" | ||
|
||
"github.com/coder/coder/v2/coderd/prometheusmetrics" | ||
"github.com/coder/coder/v2/codersdk" | ||
"github.com/coder/coder/v2/testutil" | ||
) | ||
|
||
func TestCollectLicenseMetrics(t *testing.T) { | ||
t.Parallel() | ||
|
||
// Given | ||
registry := prometheus.NewRegistry() | ||
sut, err := prometheusmetrics.NewLicenseMetrics(&prometheusmetrics.LicenseMetricsOptions{ | ||
Interval: time.Millisecond, | ||
Logger: slogtest.Make(t, nil).Leveled(slog.LevelDebug), | ||
Registry: registry, | ||
}) | ||
require.NoError(t, err) | ||
|
||
ctx, cancelFunc := context.WithCancel(context.Background()) | ||
t.Cleanup(cancelFunc) | ||
|
||
const ( | ||
actualUsers = 4 | ||
userLimit = 7 | ||
) | ||
sut.Entitlements.Store(&codersdk.Entitlements{ | ||
Features: map[codersdk.FeatureName]codersdk.Feature{ | ||
codersdk.FeatureUserLimit: { | ||
Enabled: true, | ||
Actual: ptr.Int64(actualUsers), | ||
Limit: ptr.Int64(userLimit), | ||
}, | ||
}, | ||
}) | ||
|
||
// When | ||
closeFunc, err := sut.Collect(ctx) | ||
require.NoError(t, err) | ||
t.Cleanup(closeFunc) | ||
|
||
// Then | ||
goldenFile, err := os.ReadFile("testdata/license-metrics.json") | ||
require.NoError(t, err) | ||
golden := map[string]int{} | ||
err = json.Unmarshal(goldenFile, &golden) | ||
require.NoError(t, err) | ||
|
||
collected := map[string]int{} | ||
|
||
assert.Eventually(t, func() bool { | ||
metrics, err := registry.Gather() | ||
assert.NoError(t, err) | ||
|
||
if len(metrics) < 1 { | ||
return false | ||
} | ||
|
||
for _, metric := range metrics { | ||
switch metric.GetName() { | ||
case "coderd_license_active_users", "coderd_license_user_limit": | ||
for _, m := range metric.Metric { | ||
collected[m.Label[0].GetName()+"="+m.Label[0].GetValue()+":"+metric.GetName()] = int(m.Gauge.GetValue()) | ||
} | ||
default: | ||
require.FailNowf(t, "unexpected metric collected", "metric: %s", metric.GetName()) | ||
} | ||
} | ||
return reflect.DeepEqual(golden, collected) | ||
}, testutil.WaitShort, testutil.IntervalFast) | ||
|
||
assert.EqualValues(t, golden, collected) | ||
} |
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,4 @@ | ||
{ | ||
"entitled=true:coderd_license_active_users": 4, | ||
"entitled=true:coderd_license_user_limit": 7 | ||
mtojek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
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
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.