|
- package metrics
-
- import (
- "fmt"
-
- "github.com/prometheus/client_golang/prometheus"
- "github.com/QuantumNous/new-api/common"
- "github.com/QuantumNous/new-api/model"
- )
-
- // ChannelCollector 从数据库查询渠道状态并暴露为 Prometheus Gauge
- type ChannelCollector struct {
- channelStatus *prometheus.Desc
- }
-
- // NewChannelCollector 创建渠道状态 Collector
- func NewChannelCollector() *ChannelCollector {
- return &ChannelCollector{
- channelStatus: prometheus.NewDesc(
- "newapi_channel_status",
- "Channel enabled status (1=enabled, 0=disabled)",
- []string{"channel", "channel_type"},
- nil,
- ),
- }
- }
-
- func (c *ChannelCollector) Describe(ch chan<- *prometheus.Desc) {
- ch <- c.channelStatus
- }
-
- func (c *ChannelCollector) Collect(ch chan<- prometheus.Metric) {
- if model.DB == nil {
- return
- }
-
- var channels []struct {
- Id int
- Type int
- Status int
- }
-
- err := model.DB.Table("channels").Select("id, type, status").Find(&channels).Error
- if err != nil {
- return
- }
-
- for _, ch2 := range channels {
- value := float64(0)
- if ch2.Status == common.ChannelStatusEnabled {
- value = 1
- }
- m, err := prometheus.NewConstMetric(
- c.channelStatus,
- prometheus.GaugeValue,
- value,
- fmt.Sprintf("%d", ch2.Id),
- fmt.Sprintf("%d", ch2.Type),
- )
- if err == nil {
- ch <- m
- }
- }
- }
|