|
| 1 | +package insights |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/prometheus/client_golang/prometheus" |
| 8 | + |
| 9 | + "github.com/coder/coder/v2/coderd/database" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + activeUsersDesc = prometheus.NewDesc("coderd_insights_active_users", "The number of active users of the template.", []string{"template_name"}, nil) |
| 14 | + applicationsUsageSecondsDesc = prometheus.NewDesc("coderd_insights_applications_usage_seconds", "The application usage per template.", []string{"application_name", "template_name"}, nil) |
| 15 | + parametersDesc = prometheus.NewDesc("coderd_insights_parameters", "The parameter usage per template.", []string{"template_name", "name", "value"}, nil) |
| 16 | +) |
| 17 | + |
| 18 | +type MetricsCollector struct { |
| 19 | + database database.Store |
| 20 | + duration time.Duration |
| 21 | +} |
| 22 | + |
| 23 | +var _ prometheus.Collector = new(MetricsCollector) |
| 24 | + |
| 25 | +func NewMetricsCollector(db database.Store, duration time.Duration) *MetricsCollector { |
| 26 | + if duration == 0 { |
| 27 | + duration = 5 * time.Minute |
| 28 | + } |
| 29 | + |
| 30 | + return &MetricsCollector{ |
| 31 | + database: db, |
| 32 | + duration: duration, |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +func (mc *MetricsCollector) Run(ctx context.Context) (func(), error) { |
| 37 | + ctx, closeFunc := context.WithCancel(ctx) |
| 38 | + done := make(chan struct{}) |
| 39 | + |
| 40 | + // Use time.Nanosecond to force an initial tick. It will be reset to the |
| 41 | + // correct duration after executing once. |
| 42 | + ticker := time.NewTicker(time.Nanosecond) |
| 43 | + doTick := func() { |
| 44 | + defer ticker.Reset(mc.duration) |
| 45 | + } |
| 46 | + |
| 47 | + go func() { |
| 48 | + defer close(done) |
| 49 | + defer ticker.Stop() |
| 50 | + for { |
| 51 | + select { |
| 52 | + case <-ctx.Done(): |
| 53 | + return |
| 54 | + case <-ticker.C: |
| 55 | + doTick() |
| 56 | + } |
| 57 | + } |
| 58 | + }() |
| 59 | + return func() { |
| 60 | + closeFunc() |
| 61 | + <-done |
| 62 | + }, nil |
| 63 | +} |
| 64 | + |
| 65 | +func (*MetricsCollector) Describe(descCh chan<- *prometheus.Desc) { |
| 66 | + descCh <- activeUsersDesc |
| 67 | + descCh <- applicationsUsageSecondsDesc |
| 68 | + descCh <- parametersDesc |
| 69 | +} |
| 70 | + |
| 71 | +func (mc *MetricsCollector) Collect(metricsCh chan<- prometheus.Metric) { |
| 72 | +} |
0 commit comments