Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: initial the segment (#1293)
ecmadaof2080cb4278d
diff --git a/api/metric.go b/api/metric.gonew file mode 100644index 0000000000..c012ab44ae--- /dev/null+++ b/api/metric.go@@ -0,0 +1,16 @@+package api++import "github.com/bytebase/bytebase/plugin/db"++// InstanceCountMetric is the API message for instance count metric+type InstanceCountMetric struct {+ Engine db.Type+ EnvironmentID int+ Count int+}++// IssueCountMetric is the API message for issue count metric+type IssueCountMetric struct {+ Type IssueType+ Count int+}diff --git a/api/setting.go b/api/setting.goindex ff3bbf8ad9..b94e108e4c 100644--- a/api/setting.go+++ b/api/setting.go@@ -12,6 +12,8 @@ const (SettingAuthSecret SettingName = "bb.auth.secret"// SettingBrandingLogo is the setting name for branding logo.SettingBrandingLogo SettingName = "bb.branding.logo"+ // SettingWorkspaceID is the setting name for workspace identifier.+ SettingWorkspaceID SettingName = "bb.workspace.id")// Setting is the API message for a setting.diff --git a/api/workspace.go b/api/workspace.gonew file mode 100644index 0000000000..7839fdb666--- /dev/null+++ b/api/workspace.go@@ -0,0 +1,7 @@+package api++// Workspace is the instance for console application.+type Workspace struct {+ Plan string+ ID string+}diff --git a/bin/server/cmd/profile_dev.go b/bin/server/cmd/profile_dev.goindex 1f4ea0995a..69cf6d4b1a 100644--- a/bin/server/cmd/profile_dev.go+++ b/bin/server/cmd/profile_dev.go@@ -30,6 +30,7 @@ func activeProfile(dataDir string) server.Profile {BackupRunnerInterval: 10 * time.Second,Version: version,PgURL: flags.pgURL,+ MetricConnectionKey: "Q4krM9MitLvUSlty7TAt9kAcThp2GfMH",}}diff --git a/bin/server/cmd/profile_release.go b/bin/server/cmd/profile_release.goindex 060c0c566b..c4c5e31f6c 100644--- a/bin/server/cmd/profile_release.go+++ b/bin/server/cmd/profile_release.go@@ -34,5 +34,6 @@ func activeProfile(dataDir string) server.Profile {BackupRunnerInterval: 10 * time.Minute,Version: version,PgURL: flags.pgURL,+ MetricConnectionKey: "",}}diff --git a/go.mod b/go.modindex ee526399e9..3618d3a783 100644--- a/go.mod+++ b/go.mod@@ -6,6 +6,7 @@ require (github.com/ClickHouse/clickhouse-go/v2 v2.0.7github.com/VictoriaMetrics/fastcache v1.6.0github.com/blang/semver/v4 v4.0.0+ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirectgithub.com/casbin/casbin/v2 v2.40.6github.com/github/gh-ost v1.1.4github.com/go-sql-driver/mysql v1.6.0@@ -22,11 +23,14 @@ require (github.com/pingcap/tidb/parser v0.0.0-20211209055157-9f744cdf8266github.com/pkg/errors v0.9.1github.com/qiangmzsx/string-adapter/v2 v2.1.0+ github.com/segmentio/analytics-go v3.1.0+incompatible+ github.com/segmentio/backo-go v1.0.0 // indirectgithub.com/snowflakedb/gosnowflake v1.6.3github.com/spf13/cobra v1.2.0github.com/stretchr/testify v1.7.0github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8github.com/xo/dburl v0.9.1+ github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirectgo.uber.org/zap v1.19.1golang.org/x/crypto v0.0.0-20210817164053-32db794688a5golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirectdiff --git a/go.sum b/go.sumindex 850ee74aab..50848c024b 100644--- a/go.sum+++ b/go.sum@@ -159,6 +159,8 @@ github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOgithub.com/blacktear23/go-proxyprotocol v0.0.0-20180807104634-af7a81e8dd0d/go.mod h1:VKt7CNAQxpFpSDz3sXyj9hY/GbVsQCr0sB3w59nE7lU=github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM=github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ=+github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=+github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=github.com/bytebase/gh-ost v1.1.4 h1:mn8VQSu9i/Uu/0fDv3OXC6t/MlodN43c2iY2IpaAcN8=github.com/bytebase/gh-ost v1.1.4/go.mod h1:qSgDrOa8CXEr6gjZJn3H/uW/+Sx7kXf0cu//ci7cNHQ=github.com/cakturk/go-netstat v0.0.0-20200220111822-e5b49efee7a5 h1:BjkPE3785EwPhhyuFkbINB+2a1xATwk8SNDWnJiD41g=@@ -874,6 +876,10 @@ github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw=github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=+github.com/segmentio/analytics-go v3.1.0+incompatible h1:IyiOfUgQFVHvsykKKbdI7ZsH374uv3/DfZUo9+G0Z80=+github.com/segmentio/analytics-go v3.1.0+incompatible/go.mod h1:C7CYBtQWk4vRk2RyLu0qOcbHJ18E3F1HV2C/8JvKN48=+github.com/segmentio/backo-go v1.0.0 h1:kbOAtGJY2DqOR0jfRkYEorx/b18RgtepGtY3+Cpe6qA=+github.com/segmentio/backo-go v1.0.0/go.mod h1:kJ9mm9YmoWSkk+oQ+5Cj8DEoRCX2JT6As4kEtIIOp1M=github.com/sergi/go-diff v1.0.1-0.20180205163309-da645544ed44/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=@@ -1012,6 +1018,8 @@ github.com/xitongsys/parquet-go-source v0.0.0-20200817004010-026bad9b25d0/go.modgithub.com/xo/dburl v0.9.1 h1:y771capKup7TLEQBbc1NzY+NkHRD5DdHITeswr79JpM=github.com/xo/dburl v0.9.1/go.mod h1:7Uupe87dIDxNrbKFRrpw6bAf2l3/rqU42iwlpq1nyjY=github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=+github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c h1:3lbZUMbMiGUW/LMkfsEABsc5zNT9+b1CvsJx47JzJ8g=+github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c/go.mod h1:UrdRz5enIKZ63MEE3IF9l2/ebyx59GyGgPi+tICQdmM=github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=github.com/yookoala/realpath v1.0.0/go.mod h1:gJJMA9wuX7AcqLy1+ffPatSCySA1FQ2S8Ya9AIoYBpE=github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=diff --git a/plugin/metric/collector/collector.go b/plugin/metric/collector/collector.gonew file mode 100644index 0000000000..02dc4ed4b8--- /dev/null+++ b/plugin/metric/collector/collector.go@@ -0,0 +1,25 @@+package collector++import "context"++// MetricName is the metric name.+type MetricName string++var (+ // instanceMetricName is the MetricName for instance count+ instanceCountMetricName MetricName = "bb.instance.count"+ // issueCountMetricName is the MetricName for issue count+ issueCountMetricName MetricName = "bb.issue.count"+)++// Metric is the API message for metric+type Metric struct {+ Name MetricName+ Value int+ Labels map[string]string+}++// MetricCollector is the API message for metric collector.+type MetricCollector interface {+ Collect(ctx context.Context) ([]*Metric, error)+}diff --git a/plugin/metric/collector/instance_count.go b/plugin/metric/collector/instance_count.gonew file mode 100644index 0000000000..9e52afa591--- /dev/null+++ b/plugin/metric/collector/instance_count.go@@ -0,0 +1,52 @@+package collector++import (+ "context"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/store"+ "go.uber.org/zap"+)++// instanceCollector is the metric data collector for instance.+type instanceCollector struct {+ l *zap.Logger+ store *store.Store+}++// NewInstanceCollector creates a new instance of instanceCollector+func NewInstanceCollector(l *zap.Logger, store *store.Store) MetricCollector {+ return &instanceCollector{+ l: l,+ store: store,+ }+}++// Collect will collect the netric for instance+func (c *instanceCollector) Collect(ctx context.Context) ([]*Metric, error) {+ var res []*Metric++ instanceCountMetricList, err := c.store.CountInstanceGroupByEngineAndEnvironmentID(ctx, api.Normal)+ if err != nil {+ return nil, err+ }++ for _, instanceCountMetric := range instanceCountMetricList {+ env, err := c.store.GetEnvironmentByID(ctx, instanceCountMetric.EnvironmentID)+ if err != nil {+ c.l.Debug("failed to get environment by id", zap.Int("id", instanceCountMetric.EnvironmentID))+ continue+ }++ res = append(res, &Metric{+ Name: instanceCountMetricName,+ Value: instanceCountMetric.Count,+ Labels: map[string]string{+ "engine": string(instanceCountMetric.Engine),+ "environment": env.Name,+ },+ })+ }++ return res, nil+}diff --git a/plugin/metric/collector/issue_count.go b/plugin/metric/collector/issue_count.gonew file mode 100644index 0000000000..6b634c1d92--- /dev/null+++ b/plugin/metric/collector/issue_count.go@@ -0,0 +1,44 @@+package collector++import (+ "context"++ "github.com/bytebase/bytebase/store"+ "go.uber.org/zap"+)++// issueCollector is the metric data collector for issue.+type issueCollector struct {+ l *zap.Logger+ store *store.Store+}++// NewIssueCollector creates a new instance of issueCollector+func NewIssueCollector(l *zap.Logger, store *store.Store) MetricCollector {+ return &issueCollector{+ l: l,+ store: store,+ }+}++// Collect will collect the metric for issue+func (c *issueCollector) Collect(ctx context.Context) ([]*Metric, error) {+ var res []*Metric++ issueCountMetricList, err := c.store.CountIssueGroupByType(ctx)+ if err != nil {+ return nil, err+ }++ for _, issueCountMetric := range issueCountMetricList {+ res = append(res, &Metric{+ Name: issueCountMetricName,+ Value: issueCountMetric.Count,+ Labels: map[string]string{+ "type": string(issueCountMetric.Type),+ },+ })+ }++ return res, nil+}diff --git a/plugin/metric/reporter/reporter.go b/plugin/metric/reporter/reporter.gonew file mode 100644index 0000000000..d374b0f8b6--- /dev/null+++ b/plugin/metric/reporter/reporter.go@@ -0,0 +1,13 @@+package reporter++import (+ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/metric/collector"+)++// MetricReporter is the API message for metric reporter.+type MetricReporter interface {+ Close()+ Report(metric *collector.Metric) error+ Identify(workspace *api.Workspace) error+}diff --git a/plugin/metric/reporter/segment.go b/plugin/metric/reporter/segment.gonew file mode 100644index 0000000000..944ed422db--- /dev/null+++ b/plugin/metric/reporter/segment.go@@ -0,0 +1,67 @@+package reporter++import (+ "time"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/metric/collector"++ "github.com/segmentio/analytics-go"+ "go.uber.org/zap"+)++// Segment is the metrics collector https://segment.com/.+type segment struct {+ l *zap.Logger+ identifier string+ client analytics.Client+}++const (+ // identifyTraitForPlan is the trait key for subscription plan.+ identifyTraitForPlan = "plan"+ // metricValueField is the property key for value+ metricValueField = "value"+)++// NewSegmentReporter creates a new instance of segment+func NewSegmentReporter(l *zap.Logger, key string, identifier string) MetricReporter {+ client := analytics.New(key)++ return &segment{+ l: l,+ identifier: identifier,+ client: client,+ }+}++// Close will close the segment client.+func (s *segment) Close() {+ s.client.Close()+}++// Report will exec all the segment reporter.+func (s *segment) Report(metric *collector.Metric) error {+ properties := analytics.NewProperties().+ Set(metricValueField, metric.Value)++ for key, value := range metric.Labels {+ properties.Set(key, value)+ }++ return s.client.Enqueue(analytics.Track{+ Event: string(metric.Name),+ UserId: s.identifier,+ Properties: properties,+ Timestamp: time.Now().UTC(),+ })+}++// Identify will identify the workspace with license.+func (s *segment) Identify(workspace *api.Workspace) error {+ return s.client.Enqueue(analytics.Identify{+ UserId: s.identifier,+ Traits: analytics.NewTraits().Set(identifyTraitForPlan, workspace.Plan),+ Timestamp: time.Now().UTC(),+ })+}diff --git a/server/config.go b/server/config.goindex 4298ec4aa1..86b15e4725 100644--- a/server/config.go+++ b/server/config.go@@ -15,6 +15,8 @@ const (type config struct {// secret used to sign the JWT auth tokensecret string+ // workspaceID used to initial the identify for a new workspace.+ workspaceID string}// Profile is the configuration to start main server.@@ -53,6 +55,8 @@ type Profile struct {Version string// PgURL is the optional external PostgreSQL instance connection urlPgURL string+ // MetricConnectionKey is the connection key for metric.+ MetricConnectionKey string}func (prof *Profile) useEmbedDB() bool {diff --git a/server/metric_reporter.go b/server/metric_reporter.gonew file mode 100644index 0000000000..36267ad8e7--- /dev/null+++ b/server/metric_reporter.go@@ -0,0 +1,124 @@+package server++import (+ "context"+ "fmt"+ "reflect"+ "sync"+ "time"++ "github.com/bytebase/bytebase/api"+ enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"+ "github.com/bytebase/bytebase/plugin/metric/collector"+ "github.com/bytebase/bytebase/plugin/metric/reporter"++ "go.uber.org/zap"+)++const (+ metricSchedulerInterval = time.Duration(1) * time.Hour+)++// MetricReporter is the metric reporter.+type MetricReporter struct {+ l *zap.Logger++ // subscription is the pointer to the server.subscription.+ // the subscription can be updated by users so we need the pointer to get the latest value.+ subscription *enterpriseAPI.Subscription+ reporter reporter.MetricReporter+ workspaceID string+ collectorList []collector.MetricCollector+}++// NewMetricReporter creates a new metric scheduler.+func NewMetricReporter(logger *zap.Logger, server *Server, workspaceID string) *MetricReporter {+ reporter := reporter.NewSegmentReporter(logger, server.profile.MetricConnectionKey, workspaceID)+ collectorList := []collector.MetricCollector{+ collector.NewInstanceCollector(logger, server.store),+ collector.NewIssueCollector(logger, server.store),+ }++ return &MetricReporter{+ l: logger,+ subscription: &server.subscription,+ workspaceID: workspaceID,+ reporter: reporter,+ collectorList: collectorList,+ }+}++// Run will run the metric reporter.+func (m *MetricReporter) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(metricSchedulerInterval)+ defer ticker.Stop()+ defer wg.Done()++ m.l.Debug(fmt.Sprintf("Metrics reporter started and will run every %v", metricSchedulerInterval))++ for {+ // identify will be triggered in every schedule loop so that we can update the latest workspace profile like subscription plan.+ m.identify()++ select {+ case <-ticker.C:+ func() {+ defer func() {+ if r := recover(); r != nil {+ err, ok := r.(error)+ if !ok {+ err = fmt.Errorf("%v", r)+ }+ m.l.Error("Metrics reporter PANIC RECOVER", zap.Error(err), zap.Stack("stack"))+ }+ }()++ ctx := context.Background()+ for _, collector := range m.collectorList {+ collectorName := reflect.TypeOf(collector).String()+ m.l.Debug("Run metric collector", zap.String("collector", collectorName))++ metricList, err := collector.Collect(ctx)+ if err != nil {+ m.l.Error(+ "Failed to collect metric",+ zap.String("collector", collectorName),+ zap.Error(err),+ )+ continue+ }+ for _, metric := range metricList {+ if err := m.reporter.Report(metric); err != nil {+ m.l.Error(+ "Failed to report metric",+ zap.String("metric", string(metric.Name)),+ zap.Error(err),+ )+ }+ }+ }+ }()+ case <-ctx.Done(): // if cancel() execute+ return+ }+ }+}++// Close will close the metric reporter.+func (m *MetricReporter) Close() {+ m.reporter.Close()+}++// Identify will identify the workspace and update the subscription plan.+func (m *MetricReporter) identify() {+ plan := api.FREE.String()+ if m.subscription != nil {+ plan = m.subscription.Plan.String()+ }+ if err := m.reporter.Identify(&api.Workspace{+ Plan: plan,+ ID: m.workspaceID,+ }); err != nil {+ m.l.Debug("reporter identify failed", zap.Error(err))+ }+}diff --git a/server/server.go b/server/server.goindex 7a34f27a4f..5fe8719cda 100644--- a/server/server.go+++ b/server/server.go@@ -11,6 +11,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/store"+ "github.com/google/uuid"// embed will embeds the acl policy._ "embed"@@ -31,6 +32,7 @@ type Server struct {// Asynchronous runners.TaskScheduler *TaskSchedulerTaskCheckScheduler *TaskCheckScheduler+ MetricReporter *MetricReporterSchemaSyncer *SchemaSyncerBackupRunner *BackupRunnerAnomalyScanner *AnomalyScanner@@ -39,7 +41,7 @@ type Server struct {ActivityManager *ActivityManagerLicenseService enterpriseAPI.LicenseService- subscription *enterpriseAPI.Subscription+ subscription enterpriseAPI.Subscriptionprofile Profilee *echo.Echo@@ -133,11 +135,6 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLeve}s.secret = config.secret- err = s.initBranding(ctx, storeInstance)- if err != nil {- return nil, fmt.Errorf("failed to init branding: %w", err)- }-e := echo.New()e.Debug = prof.Debuge.HideBanner = true@@ -218,6 +215,9 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLeve// Anomaly scanners.AnomalyScanner = NewAnomalyScanner(logger, s)++ // Metric reporter+ s.initMetricReporter(config.workspaceID)}// Middleware@@ -298,47 +298,66 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLevereturn nil, fmt.Errorf("failed to create license service, error: %w", err)}- s.InitSubscription()+ s.initSubscription()logger.Debug(fmt.Sprintf("All registered routes: %v", string(allRoutes)))s.boot = truereturn s, nil}-// InitSubscription will initial the subscription cache in memory.-func (server *Server) InitSubscription() {+// initSubscription will initial the subscription cache in memory.+func (server *Server) initSubscription() {server.subscription = server.loadSubscription()}+// initMetricReporter will initial the metric scheduler.+func (server *Server) initMetricReporter(workspaceID string) {+ enabled := server.profile.Mode == common.ReleaseModeProd && !server.profile.Demo+ if enabled {+ metricReporter := NewMetricReporter(server.l, server, workspaceID)+ server.MetricReporter = metricReporter+ }+}+func (server *Server) initSetting(ctx context.Context, store *store.Store) (*config, error) {+ // initial branding+ _, err := store.CreateSettingIfNotExist(ctx, &api.SettingCreate{+ CreatorID: api.SystemBotID,+ Name: api.SettingBrandingLogo,+ Value: "",+ Description: "The branding logo image in base64 string format.",+ })+ if err != nil {+ return nil, err+ }+conf := &config{}- configCreate := &api.SettingCreate{++ // initial JWT token+ authSetting, err := store.CreateSettingIfNotExist(ctx, &api.SettingCreate{CreatorID: api.SystemBotID,Name: api.SettingAuthSecret,Value: common.RandomString(secreatLength),Description: "Random string used to sign the JWT auth token.",- }- config, err := store.CreateSettingIfNotExist(ctx, configCreate)+ })if err != nil {return nil, err}- conf.secret = config.Value+ conf.secret = authSetting.Value- return conf, nil-}--func (server *Server) initBranding(ctx context.Context, store *store.Store) error {- configCreate := &api.SettingCreate{+ // initial workspace+ workspaceSetting, err := store.CreateSettingIfNotExist(ctx, &api.SettingCreate{CreatorID: api.SystemBotID,- Name: api.SettingBrandingLogo,- Value: "",- Description: "The branding logo image in base64 string format.",- }- _, err := store.CreateSettingIfNotExist(ctx, configCreate)+ Name: api.SettingWorkspaceID,+ Value: uuid.New().String(),+ Description: "The workspace identifier",+ })if err != nil {- return err+ return nil, err}- return nil+ conf.workspaceID = workspaceSetting.Value++ return conf, nil}// Run will run the server.@@ -357,6 +376,11 @@ func (server *Server) Run(ctx context.Context) error {server.runnerWG.Add(1)go server.AnomalyScanner.Run(ctx, &server.runnerWG)server.runnerWG.Add(1)++ if server.MetricReporter != nil {+ go server.MetricReporter.Run(ctx, &server.runnerWG)+ server.runnerWG.Add(1)+ }}// Sleep for 1 sec to make sure port is released between runs.@@ -370,6 +394,11 @@ func (server *Server) Shutdown(ctx context.Context) error {server.l.Info("Trying to stop Bytebase ....")server.l.Info("Trying to gracefully shutdown server")+ // Close the metric reporter+ if server.MetricReporter != nil {+ server.MetricReporter.Close()+ }+ctx, cancel := context.WithTimeout(ctx, 10*time.Second)defer cancel()diff --git a/server/subscription.go b/server/subscription.goindex 4e0d3d9fda..22a0061c31 100644--- a/server/subscription.go+++ b/server/subscription.go@@ -16,7 +16,7 @@ import (func (s *Server) registerSubscriptionRoutes(g *echo.Group) {g.GET("/subscription", func(c echo.Context) error {c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, s.subscription); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, &s.subscription); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal subscription response").SetInternal(err)}return nil@@ -35,7 +35,7 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {s.subscription = s.loadSubscription()c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, s.subscription); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, &s.subscription); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal subscription response").SetInternal(err)}return nil@@ -44,8 +44,8 @@ func (s *Server) registerSubscriptionRoutes(g *echo.Group) {// loadLicense will load current subscription by license.// Return subscription with free plan if no license found.-func (s *Server) loadSubscription() *enterpriseAPI.Subscription {- subscription := &enterpriseAPI.Subscription{+func (s *Server) loadSubscription() enterpriseAPI.Subscription {+ subscription := enterpriseAPI.Subscription{Plan: api.FREE,// -1 means not expire, just for free planExpiresTs: -1,@@ -53,7 +53,7 @@ func (s *Server) loadSubscription() *enterpriseAPI.Subscription {}license, _ := s.loadLicense()if license != nil {- subscription = &enterpriseAPI.Subscription{+ subscription = enterpriseAPI.Subscription{Plan: license.Plan,ExpiresTs: license.ExpiresTs,StartedTs: license.IssuedTs,diff --git a/store/instance.go b/store/instance.goindex 6d5deca73a..63fd854e08 100644--- a/store/instance.go+++ b/store/instance.go@@ -152,6 +152,40 @@ func (s *Store) CountInstance(ctx context.Context, find *api.InstanceFind) (int,return count, nil}+// CountInstanceGroupByEngineAndEnvironmentID counts the number of instances and group by engine and environment_id.+// Used by the metric collector.+func (s *Store) CountInstanceGroupByEngineAndEnvironmentID(ctx context.Context, rowStatus api.RowStatus) ([]*api.InstanceCountMetric, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.PTx.Rollback()++ rows, err := tx.PTx.QueryContext(ctx, `+ SELECT engine, environment_id, COUNT(*)+ FROM instance+ WHERE row_status = $1+ GROUP BY engine, environment_id`,+ rowStatus,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ var res []*api.InstanceCountMetric++ for rows.Next() {+ var metric api.InstanceCountMetric+ if err := rows.Scan(&metric.Engine, &metric.EnvironmentID, &metric.Count); err != nil {+ return nil, FormatError(err)+ }+ res = append(res, &metric)+ }++ return res, nil+}+// GetInstanceAdminPasswordByID gets admin password of instancefunc (s *Store) GetInstanceAdminPasswordByID(ctx context.Context, instanceID int) (string, error) {dataSourceFind := &api.DataSourceFind{diff --git a/store/issue.go b/store/issue.goindex c40bff4f2e..aa6900c85b 100644--- a/store/issue.go+++ b/store/issue.go@@ -140,6 +140,38 @@ func (s *Store) PatchIssue(ctx context.Context, patch *api.IssuePatch) (*api.Issreturn issue, nil}+// CountIssueGroupByType counts the number of issue and group by type.+// Used by the metric collector.+func (s *Store) CountIssueGroupByType(ctx context.Context) ([]*api.IssueCountMetric, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.PTx.Rollback()++ rows, err := tx.PTx.QueryContext(ctx, `+ SELECT type, COUNT(*)+ FROM issue+ GROUP BY type`,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ var res []*api.IssueCountMetric++ for rows.Next() {+ var metric api.IssueCountMetric+ if err := rows.Scan(&metric.Type, &metric.Count); err != nil {+ return nil, FormatError(err)+ }+ res = append(res, &metric)+ }++ return res, nil+}+// CreateIssueValidateOnly creates an issue for validation purpose// Do NOT write to the databasefunc (s *Store) CreateIssueValidateOnly(ctx context.Context, pipeline *api.Pipeline, create *api.IssueCreate, creatorID int) (*api.Issue, error) {