3

利用promwrite对prometheus进行remote-write写入

 1 week ago
source link: https://wiki.eryajf.net/pages/3bd2f4/#%E5%AE%9E%E8%B7%B5%E4%BB%8B%E7%BB%8D
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

# 前言

prometheus 大概在 2.30 版本左右的时候,增加了 remote write 的能力,这是一种有别于 exporter 暴漏指标由 prometheus 拉,以及 pushgateway 推的指标上报方式,你可以借助于这种方式上报你的指标,也可以基于此能力,将多个集群的指标汇聚到一个集群之中。

腾讯云的 cls 推出了指标主题的类型,其支持的,也正是这种 remote write 写入的方式。

# 相关资料

prometheus 官方相关文档: https://prometheus.io/docs/practices/remote_write/ (opens new window) 腾讯云指标主题的介绍:指标上报 (opens new window)

# 实践介绍

本文实际主要想介绍的,是基于 go 语言的 remote write 上报实践,这里就结合我的个人实际体验,来进行记录。

我在实践的过程中,找到了一个比较好用的包: https://github.com/castai/promwrite (opens new window),但实际应用过程中发现,此包没有支持开启了认证的场景,而腾讯云 cls 默认是开启认证的,因此个人对此包做了一些功能扩展,提交了 pr,但是之后源仓库维护者没有理会,我就单独重置了 mod,因此接下来的示例就用我的包来做了。事实上直接看 readme 的介绍也可以了解用法。

我的地址为: https://github.com/eryajf/promwrite (opens new window)

go get github.com/eryajf/promwrite

示例代码:

	client := promwrite.NewClient("http://prometheus:8428/api/v1/write")
	resp, err := client.Write(context.Background(), &promwrite.WriteRequest{
		TimeSeries: []promwrite.TimeSeries{
			{
				Labels: []promwrite.Label{
					{
						Name:  "__name__",
						Value: "my_metric_name",
					},
				},
				Sample: promwrite.Sample{
					Time:  time.Now(),
					Value: 123,
				},
			},
		},
	})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

如果你的集群包含认证,那么可以使用如下代码:

	client := promwrite.NewClient("http://prometheus:8428/api/v1/write",
		promwrite.HttpClientWithAuth(
			&http.Client{},
			&promwrite.BasicAuth{
				Username: "admin",
				Password: "xxxxxx",
			}))

	resp, err := client.Write(context.Background(), &promwrite.WriteRequest{
		TimeSeries: []promwrite.TimeSeries{
			{
				Labels: []promwrite.Label{
					{
						Name:  "__name__",
						Value: "my_metric_name",
					},
				},
				Sample: promwrite.Sample{
					Time:  time.Now(),
					Value: 123,
				},
			},
		},
	})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

其中的 __name__ 是保留字段,会自动作为该记录的的指标名。剩下的如果你需要更多的补充字段,则在 []promwrite.Label 补充即可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK