2022-10-29 11:15:39 +08:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
metric "github.com/usememos/memos/plugin/metrics"
|
|
|
|
"github.com/usememos/memos/plugin/metrics/segment"
|
|
|
|
"github.com/usememos/memos/server/profile"
|
|
|
|
"github.com/usememos/memos/server/version"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MetricCollector is the metric collector.
|
|
|
|
type MetricCollector struct {
|
2023-01-05 20:56:50 +08:00
|
|
|
collector metric.Collector
|
|
|
|
ID string
|
2022-11-26 09:23:38 +08:00
|
|
|
Enabled bool
|
|
|
|
Profile *profile.Profile
|
2022-10-29 11:15:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2023-01-05 20:56:50 +08:00
|
|
|
segmentMetricWriteKey = "NbPruMMmfqfD2AMCw3pkxZTsszVS3hKq"
|
2022-10-29 11:15:39 +08:00
|
|
|
)
|
|
|
|
|
2023-01-05 20:56:50 +08:00
|
|
|
func (s *Server) registerMetricCollector() {
|
2022-10-29 11:15:39 +08:00
|
|
|
c := segment.NewCollector(segmentMetricWriteKey)
|
2023-01-05 20:56:50 +08:00
|
|
|
mc := &MetricCollector{
|
|
|
|
collector: c,
|
|
|
|
ID: s.ID,
|
2023-01-14 08:00:07 +08:00
|
|
|
Enabled: false,
|
2023-01-05 20:56:50 +08:00
|
|
|
Profile: s.Profile,
|
2022-10-29 11:15:39 +08:00
|
|
|
}
|
2023-01-05 20:56:50 +08:00
|
|
|
s.Collector = mc
|
2022-10-29 11:15:39 +08:00
|
|
|
}
|
|
|
|
|
2023-01-05 20:56:50 +08:00
|
|
|
func (mc *MetricCollector) Identify(_ context.Context) {
|
2022-11-26 09:23:38 +08:00
|
|
|
if !mc.Enabled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-01-05 20:56:50 +08:00
|
|
|
err := mc.collector.Identify(mc.ID)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to request segment, error: %+v\n", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mc *MetricCollector) Collect(_ context.Context, metric *metric.Metric) {
|
|
|
|
if !mc.Enabled {
|
2022-10-29 11:15:39 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if metric.Labels == nil {
|
|
|
|
metric.Labels = map[string]string{}
|
|
|
|
}
|
2023-01-05 20:56:50 +08:00
|
|
|
metric.Labels["mode"] = mc.Profile.Mode
|
2022-11-26 09:23:38 +08:00
|
|
|
metric.Labels["version"] = version.GetCurrentVersion(mc.Profile.Mode)
|
2023-01-05 20:56:50 +08:00
|
|
|
metric.ID = mc.ID
|
|
|
|
err := mc.collector.Collect(metric)
|
2022-10-29 11:15:39 +08:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to request segment, error: %+v\n", err)
|
|
|
|
}
|
|
|
|
}
|