You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
2.1 KiB
84 lines
2.1 KiB
package et_prometheus_exporter
|
|
|
|
import (
|
|
"fmt"
|
|
"gitea.anxinyun.cn/container/common_models"
|
|
"gitea.anxinyun.cn/container/common_utils/configLoad"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
"log"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// 定义自定义指标
|
|
var (
|
|
once sync.Once
|
|
//设备数据量统计
|
|
devDataCounter = prometheus.NewCounterVec(prometheus.CounterOpts{
|
|
Name: "device_data_count",
|
|
Help: "单次有效运行时间段内,设备数据量实时统计,累计有效数据条数",
|
|
}, []string{"deviceId", "thingId", "timeStart"})
|
|
timeStart = time.Now().Format("2006-01-02 15:04:05")
|
|
|
|
//设备数据最后时间统计
|
|
devLastDataTimeGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
|
Name: "device_last_time_unix",
|
|
Help: "设备数据最新时间戳",
|
|
}, []string{"deviceId", "thingId"})
|
|
)
|
|
|
|
func init() {
|
|
// 注册自定义指标
|
|
prometheus.MustRegister(devLastDataTimeGauge)
|
|
prometheus.MustRegister(devDataCounter)
|
|
}
|
|
|
|
type PrometheusExporter struct {
|
|
}
|
|
|
|
func NewPrometheusExporter() PrometheusExporter {
|
|
run()
|
|
return PrometheusExporter{}
|
|
|
|
}
|
|
|
|
func run() {
|
|
once.Do(func() {
|
|
go apiRun()
|
|
})
|
|
}
|
|
func (p *PrometheusExporter) OnIotaData2metricByPrometheus(data *common_models.IotaData) {
|
|
|
|
if data.Data.Success() == false {
|
|
return
|
|
}
|
|
|
|
//log.Printf("prometheusExporter 导出设备[%s]指标 ", data.DeviceId)
|
|
deviceId := data.DeviceId
|
|
thingId := data.ThingId
|
|
|
|
collectTime := data.TriggerTime.Unix()
|
|
devLastDataTimeGauge.WithLabelValues(deviceId, thingId).Set(float64(collectTime))
|
|
devDataCounter.WithLabelValues(deviceId, thingId, timeStart).Inc()
|
|
}
|
|
|
|
func apiRun() {
|
|
|
|
// 设置仪表的值
|
|
|
|
// 暴露metrics
|
|
port := configLoad.LoadConfig().GetInt32("prometheus.port") //8080
|
|
http.Handle("/metrics", myMetrics{})
|
|
log.Println(fmt.Sprintf("Beginning to Prometheus Exporter serve on port :%d", port))
|
|
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
|
|
}
|
|
|
|
type myMetrics struct {
|
|
}
|
|
|
|
func (m myMetrics) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
log.Println("prometheus 抓取")
|
|
promhttp.Handler().ServeHTTP(w, r)
|
|
}
|
|
|