1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package main
import ( "database/sql" _ "github.com/go-sql-driver/mysql" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "log" "net/http" "strconv" "time" )
var ( alertEventMetric = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "alert_event_trigger_time", Help: "Trigger time of the alert events in UNIX timestamp", }, []string{"id", "cluster", "group_id", "severity", "description", "Group", "Region"}, #此处标签根据业务实际情况添加 ) )
func init() { prometheus.MustRegister(alertEventMetric) } func queryDatabaseAndUpdateMetrics() { dsn := "xxx:xxx@tcp(xxxx:3306)/n9e_v5" db, err := sql.Open("mysql", dsn) if err != nil { log.Fatalf("Failed to connect to MySQL: %v", err) } defer db.Close()
err = db.Ping() if err != nil { log.Fatalf("MySQL connection error: %v", err) }
query := `SELECT id, cluster, group_id, severity, rule_name, trigger_time FROM alert_cur_event where severity < 3;`
rows, err := db.Query(query) if err != nil { log.Fatalf("Failed to execute query: %v", err) } defer rows.Close()
alertEventMetric.Reset() currentTime := time.Now().Unix() for rows.Next() { var id int var cluster string var groupID int var severity int var ruleName string var triggerTime int64 var region string
err := rows.Scan(&id, &cluster, &groupID, &severity, &ruleName, &triggerTime) if err != nil { log.Printf("Error scanning row: %v", err) continue } region = "告警升级" var metricValue float64 if currentTime-triggerTime > 8*3600 { metricValue = 1 } else { metricValue = 0 } alertEventMetric.WithLabelValues( strconv.Itoa(id), cluster, strconv.Itoa(groupID), strconv.Itoa(severity), ruleName, cluster, region, ).Set(float64(metricValue)) }
if err = rows.Err(); err != nil { log.Fatalf("Error during rows iteration: %v", err) } }
func main() { go func() { for { queryDatabaseAndUpdateMetrics() time.Sleep(30 * time.Second) } }()
http.Handle("/metrics", promhttp.Handler()) log.Println("Starting HTTP server on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
|