-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
82 lines (68 loc) · 2.56 KB
/
monitor.go
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
package main
import (
"context"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
// 默认的 CKB 节点 RPC 地址
DefaultCkbRpcUrl = "https://mainnet.ckb.dev"
// 默认的更新时间间隔,单位为秒
DefaultUpdateInterval = 10
// 指标名称
MetricName = "ckb_block_info"
)
var (
blockNumber = prometheus.NewGauge(prometheus.GaugeOpts{
Name: MetricName + "_number",
Help: "The current block number",
})
blockTimestamp = prometheus.NewGauge(prometheus.GaugeOpts{
Name: MetricName + "_timestamp",
Help: "The current block timestamp",
})
)
func main() {
// 读取 CKB 节点 RPC 地址和更新时间间隔的环境变量
ckbRpcUrl := os.Getenv("CKB_RPC_URL")
if ckbRpcUrl == "" {
ckbRpcUrl = DefaultCkbRpcUrl
}
updateIntervalStr := os.Getenv("UPDATE_INTERVAL")
updateInterval, err := strconv.Atoi(updateIntervalStr)
if err != nil || updateInterval <= 0 {
updateInterval = DefaultUpdateInterval
}
// 创建 CKB 节点的 RPC 客户端
client, err := rpc.Dial(ckbRpcUrl)
if err != nil {
log.Fatalf("Failed to create CKB node RPC client: %v", err)
}
// 注册指标
prometheus.MustRegister(blockNumber)
prometheus.MustRegister(blockTimestamp)
// 定时获取区块信息并更新指标
go func() {
for {
header, err := client.GetTipHeader(context.Background())
if err != nil {
log.Printf("Failed to get tip header: %v", err)
continue
}
blockNumber.Set(float64(header.Number))
blockTimestamp.Set(float64(header.Timestamp))
log.Printf("Updated block info: number=%d timestamp=%d", header.Number, header.Timestamp)
time.Sleep(time.Duration(updateInterval) * time.Second)
}
}()
// 启动 HTTP 服务,暴露指标
log.Printf("Starting HTTP server on port 8080")
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}