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: add database metric (#1396)
qsliu48e53ce58c34
diff --git a/metric/collector/database_count.go b/metric/collector/database_count.gonew file mode 100644index 0000000000..4559363c0d--- /dev/null+++ b/metric/collector/database_count.go@@ -0,0 +1,57 @@+package collector++import (+ "context"+ "strconv"++ metricAPI "github.com/bytebase/bytebase/metric"+ "github.com/bytebase/bytebase/plugin/metric"+ "github.com/bytebase/bytebase/store"+ "go.uber.org/zap"+)++var _ metric.Collector = (*databaseCountCollector)(nil)++// databaseCountCollector is the metric data collector for database.+type databaseCountCollector struct {+ l *zap.Logger+ store *store.Store+}++// NewDatabaseCountCollector creates a new instance of databaseCountCollector+func NewDatabaseCountCollector(l *zap.Logger, store *store.Store) metric.Collector {+ return &databaseCountCollector{+ l: l,+ store: store,+ }+}++// Collect will collect the metric for database+func (c *databaseCountCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {+ var res []*metric.Metric++ databaseCountMetricList, err := c.store.CountDatabaseGroupByBackupScheduleAndEnabled(ctx)+ if err != nil {+ return nil, err+ }++ for _, databaseCountMetric := range databaseCountMetricList {+ labels := map[string]string{+ "backup_schedule": "null",+ "backup_enabled": "null",+ }+ if v := databaseCountMetric.BackupPlanPolicySchedule; v != nil {+ labels["backup_schedule"] = string(*v)+ }+ if v := databaseCountMetric.BackupSettingEnabled; v != nil {+ labels["backup_enabled"] = strconv.FormatBool(*v)+ }+ res = append(res, &metric.Metric{+ Name: metricAPI.DatabaseCountMetricName,+ Value: databaseCountMetric.Count,+ Labels: labels,+ })+ }++ return res, nil+}diff --git a/metric/collector/instance_count.go b/metric/collector/instance_count.goindex 2595a52720..f0188101bf 100644--- a/metric/collector/instance_count.go+++ b/metric/collector/instance_count.go@@ -6,27 +6,28 @@ import ("github.com/bytebase/bytebase/api"metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector""github.com/bytebase/bytebase/store""go.uber.org/zap")-// instanceCollector is the metric data collector for instance.-type instanceCollector struct {+var _ metric.Collector = (*instanceCountCollector)(nil)++// instanceCountCollector is the metric data collector for instance.+type instanceCountCollector struct {l *zap.Loggerstore *store.Store}-// NewInstanceCollector creates a new instance of instanceCollector-func NewInstanceCollector(l *zap.Logger, store *store.Store) collector.MetricCollector {- return &instanceCollector{+// NewInstanceCountCollector creates a new instance of instanceCollector+func NewInstanceCountCollector(l *zap.Logger, store *store.Store) metric.Collector {+ return &instanceCountCollector{l: l,store: store,}}// Collect will collect the metric for instance-func (c *instanceCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {+func (c *instanceCountCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {var res []*metric.MetricinstanceCountMetricList, err := c.store.CountInstanceGroupByEngineAndEnvironmentID(ctx, api.Normal)diff --git a/metric/collector/issue_count.go b/metric/collector/issue_count.goindex 95ba583793..e27e0d4161 100644--- a/metric/collector/issue_count.go+++ b/metric/collector/issue_count.go@@ -5,27 +5,28 @@ import (metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector""github.com/bytebase/bytebase/store""go.uber.org/zap")-// issueCollector is the metric data collector for issue.-type issueCollector struct {+var _ metric.Collector = (*issueCountCollector)(nil)++// issueCountCollector is the metric data collector for issue.+type issueCountCollector struct {l *zap.Loggerstore *store.Store}-// NewIssueCollector creates a new instance of issueCollector-func NewIssueCollector(l *zap.Logger, store *store.Store) collector.MetricCollector {- return &issueCollector{+// NewIssueCountCollector creates a new instance of issueCollector+func NewIssueCountCollector(l *zap.Logger, store *store.Store) metric.Collector {+ return &issueCountCollector{l: l,store: store,}}// Collect will collect the metric for issue-func (c *issueCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {+func (c *issueCountCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {var res []*metric.MetricissueCountMetricList, err := c.store.CountIssueGroupByTypeAndStatus(ctx)diff --git a/metric/collector/policy_count.go b/metric/collector/policy_count.goindex ac5f119dd0..948b219f4c 100644--- a/metric/collector/policy_count.go+++ b/metric/collector/policy_count.go@@ -7,27 +7,28 @@ import ("github.com/bytebase/bytebase/api"metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector""github.com/bytebase/bytebase/store""go.uber.org/zap")-// policyCollector is the metric data collector for policy.-type policyCollector struct {+var _ metric.Collector = (*policyCountCollector)(nil)++// policyCountCollector is the metric data collector for policy.+type policyCountCollector struct {l *zap.Loggerstore *store.Store}-// NewPolicyCollector creates a new instance of policyCollector-func NewPolicyCollector(l *zap.Logger, store *store.Store) collector.MetricCollector {- return &policyCollector{+// NewPolicyCountCollector creates a new instance of policyCollector+func NewPolicyCountCollector(l *zap.Logger, store *store.Store) metric.Collector {+ return &policyCountCollector{l: l,store: store,}}// Collect will collect the metric for policy-func (c *policyCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {+func (c *policyCountCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {var res []*metric.MetricpolicyList, err := c.store.ListPolicy(ctx, &api.PolicyFind{})diff --git a/metric/collector/project_count.go b/metric/collector/project_count.goindex 8f0ef64719..37e7d40f0c 100644--- a/metric/collector/project_count.go+++ b/metric/collector/project_count.go@@ -5,27 +5,28 @@ import (metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector""github.com/bytebase/bytebase/store""go.uber.org/zap")-// projectCollector is the metric data collector for project.-type projectCollector struct {+var _ metric.Collector = (*projectCountCollector)(nil)++// projectCountCollector is the metric data collector for project.+type projectCountCollector struct {l *zap.Loggerstore *store.Store}-// NewProjectCollector creates a new instance of projectCollector-func NewProjectCollector(l *zap.Logger, store *store.Store) collector.MetricCollector {- return &projectCollector{+// NewProjectCountCollector creates a new instance of projectCollector+func NewProjectCountCollector(l *zap.Logger, store *store.Store) metric.Collector {+ return &projectCountCollector{l: l,store: store,}}// Collect will collect the metric for project-func (c *projectCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {+func (c *projectCountCollector) Collect(ctx context.Context) ([]*metric.Metric, error) {var res []*metric.MetricprojectCountMetricList, err := c.store.CountProjectGroupByTenantModeAndWorkflow(ctx)diff --git a/metric/collector/task_count.go b/metric/collector/task_count.goindex bbebd9cf41..ccca663787 100644--- a/metric/collector/task_count.go+++ b/metric/collector/task_count.go@@ -5,11 +5,12 @@ import (metricAPI "github.com/bytebase/bytebase/metric""github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector""github.com/bytebase/bytebase/store""go.uber.org/zap")+var _ metric.Collector = (*taskCountCollector)(nil)+// taskCountCollector is the metric data collector for task.type taskCountCollector struct {l *zap.Logger@@ -17,7 +18,7 @@ type taskCountCollector struct {}// NewTaskCountCollector creates a new instance of taskCollector.-func NewTaskCountCollector(l *zap.Logger, store *store.Store) collector.MetricCollector {+func NewTaskCountCollector(l *zap.Logger, store *store.Store) metric.Collector {return &taskCountCollector{l: l,store: store,diff --git a/metric/metric.go b/metric/metric.goindex 71eb8b7c30..1e6e822bec 100644--- a/metric/metric.go+++ b/metric/metric.go@@ -15,8 +15,10 @@ var (PolicyCountMetricName metric.Name = "bb.policy.count"// ProjectCountMetricName is the metric name for project countProjectCountMetricName metric.Name = "bb.project.count"- // TaskCountMetricName is the metric name for database count+ // TaskCountMetricName is the metric name for task countTaskCountMetricName metric.Name = "bb.task.count"+ // DatabaseCountMetricName is the metric name for database count+ DatabaseCountMetricName metric.Name = "bb.database.count")// InstanceCountMetric is the API message for bb.instance.count@@ -49,9 +51,16 @@ type PolicyCountMetric struct {Count int}-// TaskCountMetric is the API message for database count metric+// TaskCountMetric is the API message for task count metrictype TaskCountMetric struct {Type api.TaskTypeStatus api.TaskStatusCount int}++// DatabaseCountMetric is the API message for database count metric+type DatabaseCountMetric struct {+ BackupPlanPolicySchedule *api.BackupPlanPolicySchedule+ BackupSettingEnabled *bool // nil if BackupPlanPolicyScheduleUnset+ Count int+}diff --git a/plugin/metric/collector.go b/plugin/metric/collector.gonew file mode 100644index 0000000000..9aa02980a3--- /dev/null+++ b/plugin/metric/collector.go@@ -0,0 +1,10 @@+package metric++import (+ "context"+)++// Collector is the API message for metric collector.+type Collector interface {+ Collect(ctx context.Context) ([]*Metric, error)+}diff --git a/plugin/metric/collector/collector.go b/plugin/metric/collector/collector.godeleted file mode 100644index 2d562d24ef..0000000000--- a/plugin/metric/collector/collector.go+++ /dev/null@@ -1,12 +0,0 @@-package collector--import (- "context"-- "github.com/bytebase/bytebase/plugin/metric"-)--// MetricCollector is the API message for metric collector.-type MetricCollector interface {- Collect(ctx context.Context) ([]*metric.Metric, error)-}diff --git a/plugin/metric/reporter.go b/plugin/metric/reporter.gonew file mode 100644index 0000000000..1dbd8981b3--- /dev/null+++ b/plugin/metric/reporter.go@@ -0,0 +1,8 @@+package metric++// Reporter is the API message for metric reporter.+type Reporter interface {+ Close()+ Report(metric *Metric) error+ Identify(identifier *Identifier) error+}diff --git a/plugin/metric/reporter/reporter.go b/plugin/metric/reporter/reporter.godeleted file mode 100644index fc92936a22..0000000000--- a/plugin/metric/reporter/reporter.go+++ /dev/null@@ -1,12 +0,0 @@-package reporter--import (- "github.com/bytebase/bytebase/plugin/metric"-)--// MetricReporter is the API message for metric reporter.-type MetricReporter interface {- Close()- Report(metric *metric.Metric) error- Identify(identifier *metric.Identifier) error-}diff --git a/plugin/metric/reporter/segment.go b/plugin/metric/segment/reporter.gosimilarity index 61%rename from plugin/metric/reporter/segment.gorename to plugin/metric/segment/reporter.goindex ac7111bb68..90d0c0999c 100644--- a/plugin/metric/reporter/segment.go+++ b/plugin/metric/segment/reporter.go@@ -1,4 +1,4 @@-package reporter+package segmentimport ("time"@@ -9,8 +9,10 @@ import ("go.uber.org/zap")-// Segment is the metrics collector https://segment.com/.-type segment struct {+var _ metric.Reporter = (*reporter)(nil)++// reporter is the metrics collector https://segment.com/.+type reporter struct {l *zap.Loggeridentifier stringclient analytics.Client@@ -21,11 +23,11 @@ const (metricValueField = "value")-// NewSegmentReporter creates a new instance of segment-func NewSegmentReporter(l *zap.Logger, key string, identifier string) MetricReporter {+// NewReporter creates a new instance of segment+func NewReporter(l *zap.Logger, key string, identifier string) metric.Reporter {client := analytics.New(key)- return &segment{+ return &reporter{l: l,identifier: identifier,client: client,@@ -33,12 +35,12 @@ func NewSegmentReporter(l *zap.Logger, key string, identifier string) MetricRepo}// Close will close the segment client.-func (s *segment) Close() {- s.client.Close()+func (r *reporter) Close() {+ r.client.Close()}// Report will exec all the segment reporter.-func (s *segment) Report(metric *metric.Metric) error {+func (r *reporter) Report(metric *metric.Metric) error {properties := analytics.NewProperties().Set(metricValueField, metric.Value)@@ -46,23 +48,23 @@ func (s *segment) Report(metric *metric.Metric) error {properties.Set(key, value)}- return s.client.Enqueue(analytics.Track{+ return r.client.Enqueue(analytics.Track{Event: string(metric.Name),- UserId: s.identifier,+ UserId: r.identifier,Properties: properties,Timestamp: time.Now().UTC(),})}// Identify will identify the workspace with license.-func (s *segment) Identify(identifier *metric.Identifier) error {+func (r *reporter) Identify(identifier *metric.Identifier) error {traits := analytics.NewTraits()for key, value := range identifier.Labels {traits.Set(key, value)}- return s.client.Enqueue(analytics.Identify{- UserId: s.identifier,+ return r.client.Enqueue(analytics.Identify{+ UserId: r.identifier,Traits: traits,Timestamp: time.Now().UTC(),})diff --git a/server/metric_reporter.go b/server/metric_reporter.goindex a45066e23d..4fc7fa6dab 100644--- a/server/metric_reporter.go+++ b/server/metric_reporter.go@@ -8,9 +8,8 @@ import ("github.com/bytebase/bytebase/api"enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"- metricAPI "github.com/bytebase/bytebase/plugin/metric"- "github.com/bytebase/bytebase/plugin/metric/collector"- "github.com/bytebase/bytebase/plugin/metric/reporter"+ "github.com/bytebase/bytebase/plugin/metric"+ "github.com/bytebase/bytebase/plugin/metric/segment""go.uber.org/zap")@@ -33,13 +32,13 @@ type MetricReporter struct {// Version is the bytebase's versionversion stringworkspaceID string- reporter reporter.MetricReporter- collectors map[string]collector.MetricCollector+ reporter metric.Reporter+ collectors map[string]metric.Collector}// NewMetricReporter creates a new metric scheduler.func NewMetricReporter(logger *zap.Logger, server *Server, workspaceID string) *MetricReporter {- r := reporter.NewSegmentReporter(logger, server.profile.MetricConnectionKey, workspaceID)+ r := segment.NewReporter(logger, server.profile.MetricConnectionKey, workspaceID)return &MetricReporter{l: logger,@@ -47,7 +46,7 @@ func NewMetricReporter(logger *zap.Logger, server *Server, workspaceID string) *version: server.profile.Version,workspaceID: workspaceID,reporter: r,- collectors: make(map[string]collector.MetricCollector),+ collectors: make(map[string]metric.Collector),}}@@ -113,7 +112,7 @@ func (m *MetricReporter) Close() {}// Register will register a metric collector.-func (m *MetricReporter) Register(metricName metricAPI.Name, collector collector.MetricCollector) {+func (m *MetricReporter) Register(metricName metric.Name, collector metric.Collector) {m.collectors[string(metricName)] = collector}@@ -123,7 +122,7 @@ func (m *MetricReporter) identify() {if m.subscription != nil {plan = m.subscription.Plan.String()}- if err := m.reporter.Identify(&metricAPI.Identifier{+ if err := m.reporter.Identify(&metric.Identifier{ID: m.workspaceID,Labels: map[string]string{identifyTraitForPlan: plan,diff --git a/server/server.go b/server/server.goindex d8a6f34814..c45d3cfb19 100644--- a/server/server.go+++ b/server/server.go@@ -328,11 +328,12 @@ func (server *Server) initMetricReporter(workspaceID string) {enabled := server.profile.Mode == common.ReleaseModeProd && !server.profile.Demoif enabled {metricReporter := NewMetricReporter(server.l, server, workspaceID)- metricReporter.Register(metric.InstanceCountMetricName, metricCollector.NewInstanceCollector(server.l, server.store))- metricReporter.Register(metric.IssueCountMetricName, metricCollector.NewIssueCollector(server.l, server.store))- metricReporter.Register(metric.ProjectCountMetricName, metricCollector.NewProjectCollector(server.l, server.store))- metricReporter.Register(metric.PolicyCountMetricName, metricCollector.NewPolicyCollector(server.l, server.store))+ metricReporter.Register(metric.InstanceCountMetricName, metricCollector.NewInstanceCountCollector(server.l, server.store))+ metricReporter.Register(metric.IssueCountMetricName, metricCollector.NewIssueCountCollector(server.l, server.store))+ metricReporter.Register(metric.ProjectCountMetricName, metricCollector.NewProjectCountCollector(server.l, server.store))+ metricReporter.Register(metric.PolicyCountMetricName, metricCollector.NewPolicyCountCollector(server.l, server.store))metricReporter.Register(metric.TaskCountMetricName, metricCollector.NewTaskCountCollector(server.l, server.store))+ metricReporter.Register(metric.DatabaseCountMetricName, metricCollector.NewDatabaseCountCollector(server.l, server.store))server.MetricReporter = metricReporter}}diff --git a/store/database.go b/store/database.goindex 5b5ef8dad5..02ad0c9360 100644--- a/store/database.go+++ b/store/database.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/metric")// databaseRaw is the store model for an Database.@@ -123,6 +124,67 @@ func (s *Store) PatchDatabase(ctx context.Context, patch *api.DatabasePatch) (*areturn database, nil}+// CountDatabaseGroupByBackupScheduleAndEnabled counts database, group by backup schedule and enabled+func (s *Store) CountDatabaseGroupByBackupScheduleAndEnabled(ctx context.Context) ([]*metric.DatabaseCountMetric, 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, `+ WITH database_backup_policy AS (+ SELECT db.id AS database_id, backup_policy.payload AS payload+ FROM db, instance LEFT JOIN (+ SELECT environment_id, payload+ FROM policy+ WHERE type = 'bb.policy.backup-plan'+ ) AS backup_policy ON instance.environment_id = backup_policy.environment_id+ WHERE db.instance_id = instance.id+ ), database_backup_setting AS(+ SELECT db.id AS database_id, backup_setting.enabled AS enabled+ FROM db LEFT JOIN backup_setting ON db.id = backup_setting.database_id+ )+ SELECT database_backup_policy.payload, database_backup_setting.enabled, COUNT(*)+ FROM database_backup_policy FULL JOIN database_backup_setting+ ON database_backup_policy.database_id = database_backup_setting.database_id+ GROUP BY database_backup_policy.payload, database_backup_setting.enabled+ `)+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ var databaseCountMetricList []*metric.DatabaseCountMetric+ for rows.Next() {+ var optionalPayload sql.NullString+ var optionalEnabled sql.NullBool+ var count int+ if err := rows.Scan(&optionalPayload, &optionalEnabled, &count); err != nil {+ return nil, FormatError(err)+ }+ var backupPlanPolicySchedule *api.BackupPlanPolicySchedule+ if optionalPayload.Valid {+ backupPlanPolicy, err := api.UnmarshalBackupPlanPolicy(optionalPayload.String)+ if err != nil {+ return nil, FormatError(err)+ }+ backupPlanPolicySchedule = &backupPlanPolicy.Schedule+ }+ var enabled *bool+ if optionalEnabled.Valid {+ enabled = &optionalEnabled.Bool+ }+ databaseCountMetricList = append(databaseCountMetricList, &metric.DatabaseCountMetric{+ BackupPlanPolicySchedule: backupPlanPolicySchedule,+ BackupSettingEnabled: enabled,+ Count: count,+ })+ }++ return databaseCountMetricList, nil+}+//// private functions//