跳到主要内容

14 篇博文 含有标签「Prometheus」

查看所有标签

Prometheus 监控注册 Nacos 注册的服务

· 阅读需 6 分钟

Prometheus 监控注册 Nacos 注册的服务

Prometheus官方提供Consul为注册中心的配置方式且只支持Consul的接口,配置后可自动获取Consul中所有实例的信息并进行监控,这里使用 Nacos Consul Adapter 来让 Nacos 伪装成 Consul

在 Spring Cloud Gateway 引入jar包

可以是服务中任意的节点,在Spring Cloud Gateway中引入jar包的原因是它基于Reactor,如果不是使用Spring WebFlux则还需要引入额外的包。

<dependency>
<groupId>io.github.chen-gliu</groupId>
<artifactId>nacos-consul-adapter</artifactId>
<version>version</version>
</dependency>

如果拉取不到包,可以在setting文件中添加如下配置:

<mirror>
<id>mvnrepository</id>
<mirrorOf>*</mirrorOf>
<name>仓库</name>
<url>https://repo1.maven.org/maven2</url>
</mirror>

修改应用的依赖及配置

pom.xml 文件中添加相关的 Maven 依赖项,视情况调整相应的版本

<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.5.1</version>
</dependency>

修改代码,暴露指标接口

在项目启动时,添加相应的监控配置,同时 micrometer 也提供了部分常用的监控数据采集,具体在 io.micrometer.core.instrument.binder 包下,可以按实际情况添加。

姿势一:

public class Application {
// 作为全局变量,可以在自定义监控中使用
public static final PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
static {
// 添加 Prometheus 全局 Label,建议加一上对应的应用名
registry.config().commonTags("application", "java-demo");
}

public static void main(String[] args) throws Exception {
// 添加 JVM 监控
new ClassLoaderMetrics().bindTo(registry);
new JvmMemoryMetrics().bindTo(registry);
new JvmGcMetrics().bindTo(registry);
new ProcessorMetrics().bindTo(registry);
new JvmThreadMetrics().bindTo(registry);
new UptimeMetrics().bindTo(registry);
new FileDescriptorMetrics().bindTo(registry);
System.gc(); // Test GC
try {
// 暴露 Prometheus HTTP 服务,如果已经有,可以使用已有的 HTTP Server
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/metrics", httpExchange -> {
String response = registry.scrape();
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});

new Thread(server::start).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

由于 JVM GC Pause 监控是通过 GarbageCollector Notification 机制实现,因此只有发生 GC 之后才有监控数据。上述示例为了测试更直观,主动调用了 System.gc()

通过 http://localhost:8080/metrics 访问到 Prometheus 协议的指标数据。

姿势二

@Bean
MeterRegistryCustomizer<MeterRegistry> configurer(
@Value("${spring.application.name}") String applicationName) {
return (registry) -> registry.config().commonTags("application", applicationName);
}

在项目启动类加上这个bean配置之后,别忘记在配置文件加上management.endpoints.web.exposure.include=*这些配置来开启 Actuator 服务,因为Spring Boot Actuator 会自动配置一个 URL 为 /actuator/Prometheus 的 HTTP 服务来供 Prometheus 抓取数据,不过默认该服务是关闭的,该配置将打开所有的 Actuator 服务

完成之后,我们再启动服务,然后在浏览器访问http://192.168.0.4:6601/actuator/prometheus,就可以看到服务的一系列不同类型 metrics 信息

例如 http_server_requests_seconds_count、jvm_threads_states_threads、jvm_classes_loaded_classes、jvm_memory_max_bytes、jvm_gc_pause_seconds summary、jvm_gc_memory_promoted_bytes_total counter 等等。

Prometheus 配置

K8s 容器版

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: java-demo
namespace: cm-prometheus
spec:
namespaceSelector:
matchNames:
- java-demo
podMetricsEndpoints:
- interval: 30s
path: /metrics
port: metric-port
selector:
matchLabels:
k8s-app: java-demo

二进制版

- job_name: nacos-prometheus
scrape_interval: 2s
metrics_path: '/actuator/prometheus'
static_configs:
consul_sd_configs:
- server: '192.168.0.4:18016'
services: []

# 注意:-targets: 后面是引入了nacos-consul-adapter.jar包的实例IP+端口,记得换成自己的实例IP和端口。如图:
# 这个配置表示:prometheus每隔2秒钟从http://192.168.0.4:18016/actuator/prometheus这个url拉取指标数据

在 Prometheus 验证监控服务

# 重启 prometheus 容器
访问http://192.168.0.4:9090/targets

# 通过在 graph 关键字搜索一些统计数据
jvm_threads_states_threads

配置 Grafana 并展示监控界面

此处使用模版ID:10280

还有很多不错的模版,比如说:4701,14370,8878...

可以参考:https://grafana.com/grafana/dashboards/

应用概况

![1.png](/img/Prometheus 监控 Nacos 注册的服务/1.png)

JVM 相关的监控数据

![2.png](/img/Prometheus 监控 Nacos 注册的服务/2.png)

GC 情况

![3.png](/img/Prometheus 监控 Nacos 注册的服务/3.png)

日志统计分析数据

![4.png](/img/Prometheus 监控 Nacos 注册的服务/4.png)

自定义监控指标并展示在 Grafana

虽然 Spring-boot-actuator 集成了 Micrometer 来提供的默认监控项,覆盖 JVM 各个层间的监控,配合 Grafana Dashboard 模板基本可以满足我们日常对 Java 应用的监控,当然,它也支持自定义监控指标,实现各个方面的监控,例如统计访问某一个 API 接口的请求数,统计实时在线人数、统计实时接口响应时间等功能,而这些都可以通过使用 Micrometer 来实现

不对针对于接口的请求数和一些接口延迟,也可以使用 APM 来针对去做监控

举个例子:

监控所有API请求次数

监控请求次数可以使用 Counter 计数器来处理,为了测试,我们就直接在 Controller 类中进行累计,项目中,可以使用一个 AOP 切面,通过切面注入可以做到统计所有请求记录,代码:

@RestController
@RequestMapping("/gateway/metrics")
public class GrafanaTestController {
@Autowired
private MeterRegistry meterRegistry;
private Counter counter;

@PostConstruct
public void init() {
Tags tags = Tags.of("common", "test");
// 公共标签
meterRegistry.config().commonTags(tags);
counter = Counter.builder("metrics.request.common").register(meterRegistry);
}

/**
* 订单请求测试
*/
@GetMapping("/order/{appId}")
public RestResponse<String> orderTest(@PathVariable("appId") String appId) {
counter.increment();
return RestResponse.ok(appId);
}

/**
* 商品请求测试
*/
@GetMapping("/product/{appId}")
public RestResponse<String> productTest(@PathVariable("appId") String appId) {
counter.increment();
return RestResponse.ok(appId);
}
}

然后分别访问接口 /order/{appId} 6次,访问接口 /product/{appId} 6次,然后我们在 Grafana Dashboard 上添加一个新的 Panel 并添加 Query 查询,最后图形化展示出来

避免重复代码的更改操作

1.增加 MeterRegistryCustomizer 配置类,而不是在每个实例的启动类挨个配置;

@Configuration
public class MeterRegistryConfig {

@Value("${spring.application.name}")
private String applicationName;

@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags("application", applicationName);
}
}

2.使用 nacos 的 shared-configs 启用配置共享,新建配置文件:springcloud-actuator-common.yml,开启全部 actuator 端点:

management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always

基于避免重复造轮子的原则,也可以不需要增加 MeterRegistryCustomizer 配置类了,1.1.0+ 以后也支持在配置文件配置了,所以我们只需要增加一个 nacos 的 shared-configs 共享文件即可。如下:

management:
endpoints:
web:
exposure:
include: 'prometheus' # 暴露/actuator/prometheus
endpoint:
health:
show-details: always
metrics:
tags:
application: ${spring.application.name} # 暴露的数据中添加application label

PromQL 语句使用

· 阅读需 7 分钟

https://prometheus.io/docs/prometheus/latest/querying/basics/

Prometheus 提供一个函数式的表达式语言PromQL (Prometheus Query Language),可以使用户实时地查找和聚合时间序列数据,表达式计算结果可以在图表中展示,也可以在 Prometheus 表达式浏览器中以表格形式展示, 或者作为数据源, 以 HTTP API 的方式提供给外部系统使用。

PromQL 数据基础

数据分类

瞬时向量、瞬时数据(instant vector):是一组时间序列,每个时间序列包含单个数据样本,比如node_memory_MemTotal_bytes查询当前剩余内存就是一个瞬时向量,该表达式的返回值中只会包含该时间序列中的最新的一个样本值,而相应的这样的表达式称之为瞬时向量表达式,例如: prometheus_http_requests_tota

范围向量、范围数据(range vector):是指在任何一个时间范围内,抓取的所有度量指标数据.比如最近一天的网卡流量趋势图,例如: prometheus_http_requests_total[5m]

标量、纯量数据(scalar):是一个浮点数类型的数据值,使用 node_load1 获取到时一个瞬时向量, 但是可用使用内置函数scalar()将瞬时向量转换为标量,例如: scalar(sum(node_load1))

字符串(string):字符串类型的数据,目前使用较少

数据类型

  • Counter

Counter : 计数器, Counter 类型代表一个累积的指标数据, 在没有被重置的前提下只增不减,比如磁盘I/O 总数、nginx的请求总数、网卡流经的报文总数等。

  • Gauge

Gauge : 仪表盘, Gauge 类型代表一个可以任意变化的指标数据, 值可以随时增高或减少,如带宽速录、CPU负载、内存利用率、nginx 活动连接数等。

例如在Graph 的 Gauge 查看 node_load1 可以看到相对应图标指标

  • Histogram

Histogram:累积直方图 , Histogram 会在一段时间范围内对数据进行采样 (通常是请求持续时间或响应大小等), 假如每分钟产生一个当前的活跃连接数, 那么一天就会产生1440个数据, 查看数据的每间隔的绘图跨度为2小时, 那么2点的柱状图 (bucket) 会包含 0点 到 2点 即两个小时的数据, 而 4点 的柱状图 (bucket) 则会包含0点到 4点 的数据 , 而 6点 的柱状图 (bucket) 则会包含 0点 到 6点 的数据。

  prometheus_tsdb_compaction_chunk_range_seconds_bucket
# TYPE go_gc_heap_frees_by_size_bytes_total histogram
go_gc_heap_frees_by_size_bytes_total_bucket[le="8.999999999999998"] 1.489766e+06
go_gc_heap_frees_by_size_bytes_total_bucket[le="24.999999999999996"] 3.1621269e+07
go_gc_heap_frees_by_size_bytes_total_bucket[le=" 64.99999999999999 "] 3.9805887e+07
go_gc_heap_frees_by_size_bytes_total_bucket[le="144.99999999999997"] 4.5192143e+07
go_gc_heap_frees_by_size_bytes_total_bucket [le=" 320.99999999999994"] 4.5981675e+07
go_gc_heap_frees_by_size_bytes_total_bucket[le="704.9999999999999 "] 4.6231281e+07
go_gc_heap_frees_by_size_bytes_total_bucket[le="1536.9999999999998") 4.6293065e+07
go_gc_heap_frees_by_size_bytes_total_bucket[le=" 3200.9999999999995"] 4.6357758e+07
  • Summary
Summary: 摘要,也是一组数据,统计的不是区间的个数而是统计分位数,从0到1,表示是0%~100%,如下统计的是0、0.25、0.5、0.75、1 的数据量分别是多少
go_gc_duration_seconds
# HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds {quantile="0"} 1.8479e-05
go_gc_duration_seconds {quantile="0.25"} 6.5059e-05
go_gc_duration_seconds {quantile="0.5"} 9.3605e-05
go_gc_duration_seconds {quantile="0.75"} 0.000133103 #百分75的go_gc_duration_seconds的持续时间
go_gc_duration_seconds {quantile="1"} 0.004022673
go_gc_duration_seconds_sum 1.446781088
go_gc_duration_seconds_count 7830

PromQL-指标数据

node_memory_MemTotal_bytes #查询node节点总内存大小
node_memory_MemFree_bytes #查询node节点剩余可用内存
node_memory_MemTotal_bytes{instance="192.168.15.100:9100"} #基于标签查询指定节点的总内存
node_memory_MemFree_bytes{instance="192.168.15.100:9100"} #基于标签查询指定节点的可用内存

node_disk_io_time_seconds_total{device="sda"} #查询指定磁盘的每秒磁盘io
node_filesystem_free_bytes{device="/dev/sda1",fstype="xfs", mountpoint="/"} #查看指定磁盘的磁盘剩余空间
# 例如查询 node_filesystem_free_bytes{device="/dev/sda1"} 指定查看

# HELP node_loadl 1m load average. #CPU负载
# TYPE node_loadl gauge
node_load1 0.1
# HELP node_load15 15m load average.
# TYPE node_load15 gauge
node_load15 0.17
# HELP node_load5 5m load average.
# TYPE node_load5 gauge
node_load5 0.13

PromeQL-匹配器

=  :选择与提供的字符串完全相同的标签,精确匹配。
!= :选择与提供的字符串不相同的标签,去反。
=~ :选择正则表达式与提供的字符串(或子字符串)相匹配的标签。
!~ :选择正则表达式与提供的字符串(或子字符串)不匹配的标签。

#查询格式 <metric name>{<label name>=<label value>, ...}
node_loadl {instance="192.168.15.100:9100"}
node_loadl {job="promethues-node"}

node_load1{job="promethues-node",instance="192.168.15.100:9100"} #精确匹配
node_load1{job="promethues-node",instance!="192.168.15.100:9100"} #取反
node_loadl{instance=~"192.168.15.100.*:9100$"} #包含正则且匹配
node_loadl{instance!~"192.168.15.100:9100"} #包含正则且取反

PromQL-时间范围

s - 秒
m - 分钟
h - 小时
d - 天
w - 周
y - 年

#瞬时向量表达式,选择当前最新的数据
node_memory_MemTotal_bytes{}

#区间向量表达式,选择以当前时间为基准,查询所有节点node_memory_MemTotal_bytes指标5分钟内的数据
node_memory_MemTotal_bytes{}[5m]

#区间向量表达式,选择以当前时间为基准,查询指定节点node_memory_MemTotal_bytes指标5分钟内的数据
node_memory_MemTotal_bytes{instance="192.168.15.100:9100"}[5m]

PromQL-运算符

+ 加法
- 减法
* 乘法
/ 除法
% 模
^ 幕等

node_memory_MemFree_bytes/1024/1024 #将内存进行单位从字节转行为兆
node_disk_read_bytes_total{device="sda"} + node_disk_written_bytes_total{device="sda"}
#计算磁盘读写数据量

PromQL-聚合运算

max、min、avg

max() #最大值
min() #最小值
avg() #平均值

# 计算每个节点的最大的流量值:
max(node_network_receive_bytes_total) by (instance)

# 计算每个节点最近五分钟每个device的最大流量
max(rate(node_network_receive_bytes_total[5m])) by (device)

sum、sount

sum() #求数据值相加的和(总数)
sum(prometheus_http_requests_total)
{} 2495 #最近总共请求数为2495次,用于计算返回值的总数(如http请求次数)

count() #统计返回值的条数
count(node_os_version)
{} 2 #一共两条返回的数据,可以用于统计节点数、pod数量等

count_values() #对value的个数(行数)进行计数
count_values("node_version",node_os_version) #统计不同的系统版本节点有多少

abs、absent

abs()  #返回指标数据的值
abs(sum(prometheus_http_requests_total{handler="/metrics"}))

absent() #如果监指标有数据就返回空,如果监控项没有数据就返回1,可用于对监控项设置告警通知
absent(sum(prometheus_http_requests_total{handler="/metrics"}))

# 当一个指标没有返回数据,则返回1如 : {} 1
# 比如说查询 absent(sum(prometheus_http_requests_total{handler="/metricsAAA"}))
# 则是没有数据,会返回 {} 1

stddev、stdvar

stddev() #标准差
stddev(prometheus_http_requests_total) #5+5=10,1+9=10,1+9这一组的数据差异就大,在系统是数据波动较大,不稳定

stdvar() #求方差
stdvar(prometheus_http_requests_total)

topk、bottomk

topk() #样本值排名最大的N个数据
#取从大到小的前6个
topk(6, prometheus_http_requests_total)

bottomk() #样本值排名最小的N个数据
#取从小到大的前6个
bottomk(6, prometheus_http_requests_total)

rate、irate

rate()  #函数是专门搭配counter数据类型使用函数,功能是取counter数据类型在这个时间段中平均每秒的增量平均数
rate(prometheus_http_requests_total[5m])
rate(node_network_receive_bytes_total[5m])

irate() #函数是专门搭配counter数据类型使用函数,功能是取counter数据类型在这个时间段中平均每秒的峰值
irate(prometheus_http_requests_total[5m])
irate(node_network_receive_bytes_total[5m])

by、without

#by,在计算结果中,只保留by指定的标签的值,并移除其它所有的
sum(rate(node_network_receive_packets_total{instance=~".*"}[10m])) by (instance)
sum(rate(node_memory_MemFree_bytes[5m])) by (increase)

#without,从计算结果中移除列举的instance, job标签,保留其它标签
sum(prometheus_http_requests_total) without (instance,job)

Prometheus victoria-metrics 存储

· 阅读需 9 分钟

Prometheus victoria-metrics 存储

Prometheus 本地存储

默认情况下,prometheus 将采集到的数据存储在本地的 TSDB 数据库中,路径默认为 prometheus 安装目录的 data 目录,数据写入过程为先把数据写入 wal 日志并放在内存,然后 2 小时后将内存数据保存至一个新的 block 块,同时再把新采集的数据写入内存并在 2 小时后再保存至一个新的 block 块,以此类推

每个 block 为一个 data 目录中以 01 开头的存储目录,比如说:

[root@yuan ~]# ls -l /apps/prometheus/data/
total 20
drwxr-xr-x 3 root root 68 May 8 13:00 01G2H0KYPSE8MZATVBBG9KPJME
drwxr-xr-x 3 root root 68 May 10 16:08 01G2PG73ZNQ0G1ZGD0EGDV2VMD
drwxr-xr-x 3 root root 68 May 10 16:08 01G2PG740MHR9JC7V772CYARAR
drwxr-xr-x 3 root root 68 May 10 16:08 01G2PG742VRGMXC2Z784YNKW29
block 的特征

block 会压缩、合并历史数据块,以及删除过期的块,随着压缩、合并,block 的数量会减少,在压缩过程中会发生三件事:

  • 定期执行压缩
  • 合并小的 block 到大的 block
  • 清理过期的块
每个块有 4 部分组成
[root@yuan ~]# tree /apps/prometheus/data/01G2H0KYPSE8MZATVBBG9KPJME/
/apps/prometheus/data/01G2H0KYPSE8MZATVBBG9KPJME/
├── chunks
│ └── 000001 #数据目录,每个大小为 512MB 超过会被切分为多个
├── index #索引文件,记录存储的数据的索引信息,通过文件内的几个表来查找时序数据
├── meta.json #block 元数据信息,包含了样本数、采集数据数据的起始时间、压缩历史
└── tombstones #逻辑数据,主要记载删除记录和标记要删除的内容,删除标记,可在查询块时排除样本
本地存储配置参数
--config.file="prometheus.yml"  #指定配置文件
--web.listen-address="0.0.0.0:9090" #指定监听地址
--storage.tsdb.path="data/" #指定数据存储目录

--storage.tsdb.retention.size=B,KB,MB,TB,PB,EB #指定 chunk 大小,默认 512MB
--storage.tsdb.retention.time= #数据保存时长,默认15天

--query.timeout=2m #最大查询超时时间
--query.max-concurrency=20 #最大查询并发量

--web.read-timeout=5m #最大空闲超时时间
--web.max-connections=512 #最大并发连接数
--web.enable-lifecycle #启用 API 动态加载配置功能

远端存储 victoriametrics

https://github.com/VictoriaMetrics/VictoriaMetrics

https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html

单机版部署
# 下载安装包
wget https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.71.0/victoria-metrics-arm-v1.71.0.tar.gz

tar xvf victoria-metrics-arm-v1.71.0.tar.gz
参数:

-httpListenAddr=0.0.0.0:8428 #监听地址及端口

-storageDataPath #VictoriaMetrics 将所有数据存储在此目录中,默认为执行启动 victoria 的当前目录下的 victoria-metrics-data 目录中

-retentionPeriod #存储数据的保留,较旧的数据会自动删除,默认保留期为 1 个月,默认单位为m(月),支持的单位有 h(hour), d(day), w(week), y(year)

设置 service 启动文件
mv victoria-metrics-prod /usr/local/bin

cat /etc/systemd/system/victoria-metrics-prod.service

[Unit]
Description=For Victoria-metrics-prod Service
After=network.target

[Service]
ExecStart=/usr/local/bin/victoria-metrics-prod -httpListenAddr=0.0.0.0:8428 -storageDataPath=/data/victoria -retentionPeriod=3

[Install]
WantedBy=multi-user.target
启动并设置开机自启
systemctl daemon-reload
systemctl restart victoria-metrics-prod.service
systemctl enable victoria-metrics-prod.service

验证页面 : 192.168.15.100:8428 查看数据

Prometheus 设置
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).

remote_write:
- url: http://192.168.15.100:8428/api/v1/write

重启 prometheus,再次验证 192.168.15.100:8428 查看数据

grafana 配置

添加数据源:

类型为 prometheus ,地址及端口为 VictoriaMetrics: http://192.168.15.100:8428

导入指定模版

8919

官方 docker-compose

https://github.com/VictoriaMetrics/VictoriaMetrics/tree/cluster/deployment/docker

git clone https://github.com/VictoriaMetrics/VictoriaMetrics.git
cd VictoriaMetrics/deployment/docker

[root@yuan docker]# ls -l
total 44
-rw-r--r-- 1 root root 61 May 10 19:32 alertmanager.yml
-rw-r--r-- 1 root root 17025 May 10 19:32 alerts.yml
drwxr-xr-x 2 root root 24 May 10 19:32 base
drwxr-xr-x 2 root root 24 May 10 19:32 builder
-rw-r--r-- 1 root root 2843 May 10 19:32 docker-compose.yml
-rw-r--r-- 1 root root 6280 May 10 19:32 Makefile
-rw-r--r-- 1 root root 298 May 10 19:32 prometheus.yml
drwxr-xr-x 4 root root 43 May 10 19:32 provisioning
-rw-r--r-- 1 root root 1495 May 10 19:32 README.md

docker-compose up -d

# 验证 web 界面
192.168.15.100:8428
集群版部署
组件介绍

vminsert #写入组件(写),vminsert 负责接收数据写入并根据对度量名称及其所有标签的一致 hash 结果将数据分散写入不同的后段 vmstorage 节点之间 vmstorage,vminsert 默认端口 8480

vmstorage #存储原始数据并返回给定时间范围内给定标签过滤器的查询数据,默认端口8482

vmselect #查询组建(读),连续 vmstorage,默认端口 8481

其他可选组件:

vmagent #是一个很轻量级但功能强大的代理,它可以从 node_exporter 各种来源收集度量指标,并将它们存储在 VictoriaMetrics 或任何其他支持远程写入协议的与 prometheus 兼容的存储系统中,有替代 prometheus server 的意向

vmalert #替换prometheus server,以 VictoriaMetrics 为数据源,基于兼容 prometheus 的告警规则,判断数据是否异常,并将产生的通知发送给 alertmanager

Vmgateway #读写 VictoriaMetrics 数据的代理网关,可实现限速和访问控制等功能,目前为企业版组件

vmctl #VictoriaMetrics 的命令行工具,目前主要用于将 prometheus 、opentsdb 等数据源的数据迁移到VictoriaMetrics

部署集群

分别在各个 VictoriaMetrics 服务器进行安装配置

wget https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.71.0/victoria-metrics-amd64-v1.71.0-cluster.tar.gz

tar xvf victoria-metrics-amd64-v1.71.0-cluster.tar.gz

[root@yuan victoria]# ls -l
total 35016
-rwxr-xr-x 1 yuan yuan 11312016 Dec 21 01:33 vminsert-prod
-rwxr-xr-x 1 yuan yuan 13026872 Dec 21 01:33 vmselect-prod
-rwxr-xr-x 1 yuan yuan 11512464 Dec 21 01:33 vmstorage-prod

mv vminsert-prod vmselect-prod vmstorage-prod /usr/local/bin

# 主要参数
-httpListenAddr string
Address to listen for http connections (default ":8482")
-vminsertAddr string
TCP address to accept connections from vminsert services (default ":8400")
-vmselectAddr string
TCP address to accept connections from vmselect services (default ":8401 ")

  • 部署 vmstorage-prod 组件

负责数据的持久化,监听端口:API 8482,数据写入端口:8400,数据读取端口:8401

vim /etc/systemd/system/vmstorage.service

[Unit]
Description=Vmstorage Server
After=network.target

[Service]
Restart=on-failure
WorkingDirectory=/tmp
ExecStart=/usr/local/bin/vmstorage-prod -loggerTimezone Asia/Shanghai -storageDataPath /data/vmstorage-data -httpListenAddr :8482 -vminsertAddr :8400 -vmselectAddr :8401

[Install]
WantedBy=multi-user.target

启动服务并设置开机自启

systemctl restart vmstorage.service
systemctl enable vmstorage.service
systemctl status vmstorage.service

配置另外两台服务器

# 将启动文件发送至另两台服务器
scp /etc/systemd/system/vmstorage.service 192.168.15.101:etc/systemd/system/vmstorage.service

scp /etc/systemd/system/vmstorage.service 192.168.15.101:etc/systemd/system/vmstorage.service

scp /usr/local/bin/vm* 192.168.15.101:/usr/local/bin/
scp /usr/local/bin/vm* 192.168.15.102:/usr/local/bin/

# 101
systemctl restart vmstorage.service && systemctl enable vmstorage.service
systemctl status vmstorage.service

# 102
systemctl restart vmstorage.service && systemctl enable vmstorage.service
systemctl status vmstorage.service
  • 部署 vminsert-prod 组件

接收外部的写请求,默认端口 8480

vim /etc/systemd/system/vminsert.service

[Unit]
Description=Vminsert Server
After=network.target

[Service]
Restart=on-failure
WorkingDirectory=/tmp
ExecStart=/usr/local/bin/vminsert-prod -httpListenAddr :8480 -storageNode=192.168.15.100:8400,192.168.15.101:8400,192.168.15.102:8400

[Install]
WantedBy=multi-user.target

启动服务并设置开机自启

systemctl daemon-reload
systemctl restart vminsert.service && systemctl enable vminsert.service
systemctl status vminsert.service

配置另外两台服务器

scp /etc/systemd/system/vminsert.service 192.168.15.101:/etc/systemd/system/vminsert.service
scp /etc/systemd/system/vminsert.service 192.168.15.102:/etc/systemd/system/vminsert.service

systemctl daemon-reload
systemctl restart vminsert.service && systemctl enable vminsert.service
systemctl status vminsert.service
  • 部署 vmselect-prod 组件

负责接收外部的读请求,默认端口 8481

vim /etc/systemd/system/vmselect.service

[Unit]
Description=Vminsert Server
After=network.target

[Service]
Restart=on-failure
WorkingDirectory=/tmp
ExecStart=/usr/local/bin/vmselect-prod -httpListenAddr :8481 -storageNode=192.168.15.100:8401,192.168.15.101:8401,192.168.15.102:8401

[Install]
WantedBy=multi-user.target

启动服务并设置开机自启

systemctl daemon-reload
systemctl restart vmselect.service && systemctl enable vmselect.service
systemctl status vmselect.service

配置另外两台服务器

scp /etc/systemd/system/vmselect.service 192.168.15.101:/etc/systemd/system/vmselect.service
scp /etc/systemd/system/vmselect.service 192.168.15.102:/etc/systemd/system/vmselect.service

systemctl daemon-reload
systemctl restart vmselect.service && systemctl enable vmselect.service
systemctl status vmselect.service

验证服务端口

#192.168.15.100
curl http://192.168.15.100:8480/metrics
curl http://192.168.15.100:8481/metrics
curl http://192.168.15.100:8482/metrics

#192.168.15.101
curl http://192.168.15.101:8480/metrics
curl http://192.168.15.101:8481/metrics
curl http://192.168.15.101:8482/metrics

#192.168.15.102
curl http://192.168.15.102:8480/metrics
curl http://192.168.15.102:8481/metrics
curl http://192.168.15.102:8482/metrics
Prometheus 配置远程写入

vim /apps/prometheus/prometheus.yml

# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).

# 单机写入
#remote_write:
# - url: http://192.168.15.100:8428/api/v1/write

# 集群写入
remote_write:
- url: http://192.168.15.100:8480/insert/0/prometheus
- url: http://192.168.15.101:8480/insert/0/prometheus
- url: http://192.168.15.102:8480/insert/0/prometheus
grafana 数据源配置

https://github.com/VictoriaMetrics/VictoriaMetrics#grafana-setup

添加数据源

在 grafana settings 中添加Data Sources,

Name:vmselect , URL:http://192.168.15.102:8481/select/0/prometheus

导入指定模版:

13824

import 导入后查看 Dashboard

开启数据复制

https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#replication-and-data-safety

默认情况下,数据被 vminsert 的组件基于 hash 算法分别将数据持久化到不同的 vmstorage 节点,可以启用 vminsert 组件支持的 -replicationFactor=N 复制功能,将数据分别在各节点保存一份完整的副本以实现数据的高可用