This commit is contained in:
Sense T
2024-04-07 10:07:26 +08:00
parent bdd4866c10
commit 0a20b5a670
6 changed files with 221 additions and 12 deletions

View File

@@ -124,3 +124,11 @@ func (c *Controller) DeleteDomain(id string) error {
return nil
})
}
func (c *Controller) getDomainCounts() (float64, error) {
var count int64
if err := c.DB.Model(models.Domain{}).Count(&count).Error; err != nil {
return 0, err
}
return float64(count), nil
}

62
controllers/metrics.go Normal file
View File

@@ -0,0 +1,62 @@
package controllers
import (
"github.com/prometheus/client_golang/prometheus"
ginprometheus "github.com/zsais/go-gin-prometheus"
ormMetric "gorm.io/plugin/prometheus"
)
var (
GaugeDomainCounts = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "recoredui",
Subsystem: "domains",
Name: "count",
Help: "domains managed in reCoreD-UI",
})
GaugeRecordCounts = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "recoredui",
Subsystem: "records",
Name: "count",
Help: "records managed in reCoreD-UI, by domain",
}, []string{"domain"})
)
func (c *Controller) RegisterMetrics() {
prometheus.MustRegister(GaugeDomainCounts, GaugeRecordCounts)
GormMetrics := ormMetric.New(ormMetric.Config{
DBName: "recored-ui",
MetricsCollector: []ormMetric.MetricsCollector{
&ormMetric.MySQL{
VariableNames: []string{"Threads_running"},
},
},
}).Collectors
prometheus.MustRegister(GormMetrics...)
GinMetrics := ginprometheus.NewPrometheus("recoredui")
for _, v := range GinMetrics.MetricsList {
prometheus.MustRegister(v.MetricCollector)
}
}
func (c *Controller) RefreshMetrics() error {
domainCounts, err := c.getDomainCounts()
if err != nil {
return err
}
GaugeDomainCounts.Set(domainCounts)
recordCounts, err := c.getRecordCounts()
if err != nil {
return err
}
for domain, counts := range recordCounts {
GaugeRecordCounts.WithLabelValues(domain).Set(counts)
}
return nil
}

View File

@@ -59,3 +59,23 @@ func (c *Controller) DeleteRecord(domain, id string) error {
Delete(&models.Record{}).Error
})
}
func (c *Controller) getRecordCounts() (map[string]float64, error) {
rows, err := c.DB.Model(models.Record{}).Select("zone", "count(*) as count").Group("zone").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[string]float64)
for rows.Next() {
var domain string
var count int64
if err := rows.Scan(&domain, &count); err != nil {
return nil, err
}
result[domain] = float64(count)
}
return result, nil
}