Prometheus study notes two-install and deploy Prometheus and use PromQL to query monitoring data

1. Installation and deployment.
1. Environmental preparation.

Software package download address: https://prometheus.io/download/

address Planning/Package
192.168.0.10 Prometheus Server
192.168.0.10 node_exporter

2. Deploy Prometheus Server.
1. Download the installation package.

$ cd /usr/local/src/
$ wget https://github.com/prometheus/prometheus/releases/download/v2.19.1/prometheus-2.19.1.linux-amd64.tar.gz
$ wget https://github.com/prometheus/alertmanager/releases/download/v0.21.0/alertmanager-0.21.0.linux-amd64.tar.gz
$ wget https://github.com/prometheus/node_exporter/releases/download/v1.0.1/node_exporter-1.0.1.linux-amd64.tar.gz

2. Install Prometheus

创建prometheus用户
$ groupadd prometheus
$ useradd -g prometheus -m -d /var/lib/prometheus -s /sbin/nologin prometheus
解压安装包。
$ tar xf prometheus-2.19.1.linux-amd64.tar.gz -C /usr/local/ && cd /usr/local/
$ ln -s /usr/local/prometheus-2.19.1.linux-amd64/ prometheus

Detailed explanation of Prometheus command parameters:

usage: prometheus [<flags>]

The Prometheus monitoring server

Flags:
  -h, --help                     查看命令帮助
      --version                  查看版本信息
      --config.file="prometheus.yml"  
                               	 Prometheus配置文件路径
      --web.listen-address="0.0.0.0:9090"  
                                 监听地址
      --web.read-timeout=5m      超时读取请求并关闭空闲连接之前的最大持续时间
      --web.max-connections=512  最大同时连接数
      --web.external-url=<URL>   可从外部访问Prometheus的URL,(例如,如果Prometheus是通过反向代理提供的)。
      							 用来生成返回到Prometheus本身的相对和绝对路径。如果该网址包含路径部分,它将是
                                 用于为Prometheus服务的所有HTTP端点添加前缀。 如果省略,将导出相关的URL组件
                                 自动。
      --web.route-prefix=<path>  Web端点内部路由的前缀。 默认为--web.external-url的路径。
      --web.user-assets=<path>   静态资源目录位于:/user.
      --web.enable-lifecycle     启用关机并通过HTTP请求重新加载.
      --web.enable-admin-api     为管理员控制操作启用API端点.
      --web.console.templates="consoles"  
                                 控制台模板目录的路径位于:/consoles.
      --web.console.libraries="console_libraries"  
                                 控制台库目录的路径.
      --web.page-title="Prometheus Time Series Collection and Processing Server"  
                                 Prometheus实例的文档标题.
      --web.cors.origin=".*"     用于CORS来源的正则表达式:'https?://(domain1|domain2)\.com'
      --storage.tsdb.path="data/"  
                                 指标存储的基本路径.
      --storage.tsdb.retention.time=STORAGE.TSDB.RETENTION.TIME  
                                 将样品保存多长时间。 设置此标志后,它将覆盖“ storage.tsdb.retention”。 如果未设置此标志,“ storage.tsdb.retention”或“ storage.tsdb.retention.size”,则保留时间默认为15d。 支持的单位:y,w,d,h,m,s,ms。
      --storage.tsdb.retention.size=STORAGE.TSDB.RETENTION.SIZE  
                                 EXPERIMENTAL]可以为块存储的最大字节数。 需要一个单位,受支持的单位:B,KB,MB,GB,TB,PB,EB。 例如:“ 512MB”。 该标志是试验性的,可以在将来的版本中进行更改。
      --storage.tsdb.no-lockfile  
                                 不要在数据目录中创建锁文件。
      --storage.tsdb.allow-overlapping-blocks  
                                 [EXPERIMENTAL]允许重叠的块,从而启用垂直压缩和垂直查询合并。
      --storage.tsdb.wal-compression  
                                 压缩tsdb WAL。
      --storage.remote.flush-deadline=<duration>  
                                 关闭或配置重新加载时等待冲洗样品的时间
      --storage.remote.read-sample-limit=5e7  
                                 在单个查询中要通过远程读取接口返回的最大样本总数。 0表示没有限制。 对于流式响应类型,将忽略此限制。
      --storage.remote.read-concurrent-limit=10  
                                 并发远程读取调用的最大数目。 0表示没有限制。
      --storage.remote.read-max-bytes-in-frame=1048576  
                                 编组之前用于流式传输远程读取响应类型的单个帧中的最大字节数。 请注意,客户端也可能会限制帧大小。 默认为protobuf建议的1MB。
      --rules.alert.for-outage-tolerance=1h  
                                 容忍普罗米修斯中断以恢复警报“ for”状态的最大时间。
      --rules.alert.for-grace-period=10m  
                                 警报和恢复的“ for”状态之间的最短持续时间。 仅对于配置的“ for”时间大于宽限期的警报,才保持此状态。
      --rules.alert.resend-delay=1m  
                                 重新发送警报到Alertmanager之前等待的最短时间
      --alertmanager.notification-queue-capacity=10000  
                                 等待的Alertmanager通知的队列容量。
      --alertmanager.timeout=10s  
                                 向Alertmanager发送警报的超时。
      --query.lookback-delta=5m  在表达式评估和联合期间用于检索指标的最大回溯持续时间。
      --query.timeout=2m         查询中止之前可能要花费的最长时间。
      --query.max-concurrency=20  
                                 并发执行的最大查询数。
      --query.max-samples=50000000  
                                 单个查询可以加载到内存中的最大样本数。 请注意,如果查询尝试将更多的样本加载到内存中,则查询将失败,因此这也限制了查询可以返回的样本数。
      --log.level=info           仅记录具有给定严重性或更高严重性的消息。 下列之一:[调试,信息,警告,错误]
      --log.format=logfmt        日志消息的输出格式。 下列之一:[logfmt,json]

Create systemd startup script

$ vim /etc/systemd/system/prometheus.service
 
添加如下内容:
[Unit]
Description=prometheus
After=network.target

[Service]
Type=simple
User=prometheus
ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml --storage.tsdb.path=/var/lib/prometheus --storage.tsdb.retention.time=10d --log.level=info
Restart=on-failure

[Install]
WantedBy=multi-user.target

--Storage.tsdb.path modify the path of local data storage
--log.level log level
--storage.tsdb.retention.time save time

2.1 Use container installation
For Docker users, you can start Prometheus Server directly by using the Prometheus image

docker run -p 9090:9090 -v /etc/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

After the startup is complete, you can access the Prometheus UI interface through http://localhost:9090:

3. Install node_exporter
In the architecture design of Prometheus, Prometheus Server does not directly serve and monitor specific targets. Its main task is to collect, store and provide data query support. Therefore, in order to be able to monitor certain things, such as the host's CPU usage, we need to use Exporter. Prometheus periodically pulls monitoring sample data from the HTTP service address exposed by Exporter (usually /metrics).

From the above description, it can be seen that Exporter can be a relatively open concept. It can be an independently running program independent of the monitoring target, or it can be directly built into the monitoring target. As long as you can provide Prometheus with monitoring sample data in a standard format.

Install node_exporter on the Prometheus node or another node separately

$ tar xf node_exporter-1.0.1.linux-amd64.tar.gz -C /usr/local/ && cd /usr/local/
$ ln -s /usr/local/node_exporter-1.0.1.linux-amd64/ node_exporter
$ chown -R prometheus:prometheus /usr/local/node_exporter-1.0.1.linux-amd64/

Common command parameters of node_exporter:

用法:node_exporter [<flags>]

标志:
  -h,--help显示上下文相关的帮助(也可以尝试--help-long和--help-man)。
      --collector.cpu.info启用指标cpu_info
      --collector.diskstats.ignored-devices =“ ^(ram | loop | fd |(h | s | v | xv)d [a-z] | nvme \\ d + n \\ d + p)\\ d + $”
                                设备的正则表达式,忽略diskstats。
      --collector.filesystem.ignored-mount-points =“ ^ /(dev | proc | sys | var / lib / docker /.+)($ | /)”
                                对于文件系统收集器,要忽略的安装点正则表达式。
      --collector.filesystem.ignored-fs-types =“ ^(autofs | binfmt_misc | bpf | cgroup2?| configfs | debugfs | devpts | devtmpfs | fusectl | hugetlbfs | iso9660 | mqueue | nsfs | overlay | proc | procfs | pstore | rpc_pipefs | securityfs | selinuxfs | squashfs | sysfs | tracefs)$“
                                文件系统收集器忽略的文件系统类型的正则表达式。
      --collector.netclass.ignored-devices =“ ^ $”
                                Netclass收集器忽略的网络设备的正则表达式。
      --collector.netdev.device-blacklist = COLLECTOR.NETDEV.DEVICE-BLACKLIST
                                净设备正则表达式到黑名单(相互排斥于设备白名单)。
      --collector.netdev.device-whitelist = COLLECTOR.NETDEV.DEVICE-WHITELIST
                                将网络设备的正则表达式添加到白名单(相互排斥于设备黑名单)。
      --collector.netstat.fields =“ ^(。* _(InErrors | InErrs)| Ip_Forwarding | Ip(6 | Ext)_(InOctets | OutOctets)| Icmp6?__(InMsgs | OutMsgs)| TcpExt_(Listen。* | Syncookies。* | TCPSynRetrans)| Tcp_(ActiveOpens | InSegs | OutSegs | PassiveOpens | RetransSegs | CurrEstab)| Udp6?_(InDatagrams | OutDatagrams | NoPorts | RcvbufErrors | SndbufErrors))$“
                                Regexp字段返回以返回netstat收集器。
      --collector.ntp.server =“ 127.0.0.1”
                                用于ntp收集器的NTP服务器
      --collector.ntp.protocol-version = 4
                                NTP协议版本
      --collector.ntp.server-is-local
                                确认collector.ntp.server地址不是公共ntp服务器
      --collector.ntp.ip-ttl = 1发送NTP查询时要使用的IP TTL
      --collector.ntp.max-distance = 3.46608s
                                到根的最大累积距离
      --collector.ntp.local-offset-tolerance = 1ms
                                本地时钟和本地ntpd时间之间的偏差可以容忍
      --path.procfs =“ / proc”挂载点。
      --path.sysfs =“ / sys” sysfs挂载点。
      --path.rootfs =“ /” rootfs安装点。
      --collector.perf.cpus =“”应该从中收集性能指标的CPU列表
      --collector.perf.tracepoint = COLLECTOR.PERF.TRACEPOINT ...
                                应收集的性能跟踪点
      --collector.powersupply.ignored-supplies =“ ^ $”
                                电源正则表达式对于powersupplyclass收集器将被忽略。
      --collector.qdisc.fixtures =“”
                                用于qdisc收集器端到端测试的测试夹具
      --collector.runit.servicedir =“ / etc / service”
                                Runit服务目录的路径。
      --collector.supervisord.url =“ http:// localhost:9001 / RPC2”
                                XML RPC端点。
      --collector.systemd.unit-whitelist =“。+”
                                将系统单位的正则表达式列入白名单。单元必须同时与白名单匹配,并且与黑名单不匹配。
      --collector.systemd.unit-blacklist =“。+ \\。(自动安装|设备|安装|范围|切片)”
                                将系统单位的正则表达式列入黑名单。单元必须同时与白名单匹配,并且与黑名单不匹配。
      --collector.systemd.enable-task-metrics
                                启用服务单元任务指标unit_tasks_current和unit_tasks_max
      --collector.systemd.enable-restarts-metrics
                                启用服务单位指标service_restart_total
      --collector.systemd.enable-start-time-metrics
                                启用服务单位指标unit_start_time_seconds
      --collector.textfile.directory =“”
                                用于读取带有度量标准的文本文件的目录。
      --collector.vmstat.fields =“ ^(oom_kill | pgpg | pswp | pg。* fault)。*”
                                用于vmstat收集器返回的字段的正则表达式。
      --collector.wifi.fixtures =“”
                                测试装置以用于wifi收集器指标
      --collector.arp启用arp收集器(默认值:启用)。
      --collector.bcache启用bcache收集器(默认值:启用)。
      --collector.bonding启用绑定收集器(默认值:启用)。
      --collector.btrfs启用btrfs收集器(默认值:启用)。
      --collector.buddyinfo启用buddyinfo收集器(默认值:禁用)
--collector.conntrack启用conntrack收集器(默认值:启用)。
      --collector.cpu启用cpu收集器(默认值:启用)。
      --collector.cpufreq启用cpufreq收集器(默认值:启用)。
      --collector.diskstats启用diskstats收集器(默认值:启用)。
      --collector.drbd启用drbd收集器(默认值:禁用)。
      --collector.edac启用edac收集器(默认值:启用)。
      --collector.entropy启用熵收集器(默认值:启用)。
      --collector.filefd启用filefd收集器(默认值:启用)。
      --collector.filesystem启用文件系统收集器(默认值:启用)。
      --collector.hwmon启用hwmon收集器(默认值:启用)。
      --collector.infiniband启用infiniband收集器(默认值:启用)。
      --collector.interrupts启用中断收集器(默认值:禁用)。
      --collector.ipvs启用ipvs收集器(默认值:启用)。
      --collector.ksmd启用ksmd收集器(默认值:禁用)。
      --collector.loadavg启用loadavg收集器(默认值:启用)。
      --collector.logind启用登录的收集器(默认值:禁用)。
      --collector.mdadm启用mdadm收集器(默认值:启用)。
      --collector.meminfo启用meminfo收集器(默认值:启用)。
      --collector.meminfo_numa启用meminfo_numa收集器(默认值:禁用)。
      --collector.mountstats启用mountstats收集器(默认值:禁用)。
      --collector.netclass启用netclass收集器(默认值:启用)。
      --collector.netdev启用netdev收集器(默认值:启用)。
      --collector.netstat启用netstat收集器(默认值:启用)。
      --collector.nfs启用nfs收集器(默认值:启用)。
      --collector.nfsd启用nfsd收集器(默认值:启用)。
      --collector.ntp启用ntp收集器(默认值:禁用)。
      --collector.perf启用性能收集器(默认值:禁用)。
      --collector.powersupplyclass
                                启用powersupplyclass收集器(默认值:启用)。
      --collector.pressure启用压力收集器(默认值:启用)。
      --collector.processes启用进程收集器(默认值:禁用)。
      --collector.qdisc启用qdisc收集器(默认值:禁用)。
      --collector.rapl启用rapl收集器(默认值:启用)。
      --collector.runit启用runit收集器(默认值:禁用)。
      --collector.schedstat启用schedstat收集器(默认值:启用)。
      --collector.sockstat启用sockstat收集器(默认值:启用)。
      --collector.softnet启用softnet收集器(默认值:启用)。
      --collector.stat启用统计信息收集器(默认值:启用)。
      --collector.supervisord启用受监管的收集器(默认值:禁用)。
      --collector.systemd启用systemd收集器(默认值:禁用)。
      --collector.tcpstat启用tcpstat收集器(默认值:禁用)。
      --collector.textfile启用文本文件收集器(默认值:启用)。
      --collector.thermal_zone启用thermal_zone收集器(默认值:启用)。
      --collector.time启用时间收集器(默认值:启用)。
      --collector.timex启用timex收集器(默认值:启用)。
      --collector.udp_queues启用udp_queues收集器(默认值:启用)。
      --collector.uname启用uname收集器(默认值:启用)。
      --collector.vmstat启用vmstat收集器(默认值:启用)。
      --collector.wifi启用wifi收集器(默认值:禁用)。
      --collector.xfs启用xfs收集器(默认值:启用)。
      --collector.zfs启用zfs收集器(默认值:启用)。
      --web.listen-address =“:9100”
                                公开指标和Web界面的地址。
      --web.telemetry-path =“ / metrics”
                                公开指标的路径。
      --web.disable-exporter-metrics
                                排除有关导出器本身的指标(promhttp _ *,process _ *,go_ *)。
      --web.max-requests = 40并行抓取请求的最大数量。使用0禁用。
      --collector.disable-defaults
                                将所有收集器默认设置为禁用。
      --web.config =“” [EXPERIMENTAL]可以启用TLS或身份验证的配置yaml文件的路径。
      --log.level = info仅记录具有给定严重性或更高严重性的消息。下列之一:[调试,信息,警告,错误]
      --log.format = logfmt日志消息的输出格式。下列之一:[logfmt,json]
      --version 查看版本信息

Create node_exporter startup script

$ vim /etc/systemd/system/node_exporter.service
 
添加如下内容:
 
[Unit]
Description=node_export
Documentation=https://github.com/prometheus/node_exporter
After=network.target

[Service]
Type=simple
User=prometheus
ExecStart=/usr/local/node_exporter/node_exporter
Restart=on-failure

[Install]
WantedBy=multi-user.target

Note: The running user of node_exporter is also a prometheus user and this user needs to be created on each node.

启动 node_exporter 服务:
$ systemctl enable node_exporter.service
$ systemctl start node_exporter.service
$ systemctl status node_exporter.service
$ ss -tnl | grep 9100
#访问http://localhost:9100/
curl http://localhost:9100/

Visit http://localhost:9100/metrics, you can see all the monitoring data of the current host obtained by the current node exporter, as shown below:
Insert picture description here
Before each monitoring metric, there will be a piece of information similar to the following form:

# HELP node_cpu Seconds the cpus spent in each mode.
# TYPE node_cpu counter
node_cpu{
    
    cpu="cpu0",mode="idle"} 362812.7890625
# HELP node_load1 1m load average.
# TYPE node_load1 gauge
node_load1 3.0703125

HELP is used to explain the meaning of the current indicator, and TYPE is the data type of the current indicator. In the above example, the note of node_cpu indicates that the current indicator is the total time that the idle process on cpu0 occupies the CPU. The CPU occupancy time is a metric that only increases and does not decrease. It can also be seen from the type that the data type of node_cpu is counter (counter ), consistent with the actual meaning of the indicator. Another example is node_load1. This indicator reflects the current host's load situation within the last minute. The system load situation will change with the use of system resources. Therefore, node_load1 reflects the current state. The data may increase or decrease. From the comments, you can It can be seen that the current indicator type is gauge, which is consistent with the actual meaning reflected by the indicator.
In addition to these, depending on the physical host system on the current page, you may also see the following monitoring indicators:

  1. node_boot_time: system boot time
  2. node_cpu: system CPU usage
  3. nodedisk *: Magnetic 盘 IO
  4. nodefilesystem*: file system usage
  5. node_load1: system load
  6. nodememeory*: memory usage
  7. nodenetwork*: network bandwidth
  8. node_time: current system time
  9. go_*: Go related indicators in node exporter
  10. process_*: node exporter's own process related operating indicators

2. Configure Prometheus to add monitoring targets and collect monitoring data from Node Exporter

$ cd /usr/local/prometheus
$ vim prometheus.yml 
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'
 
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    # 搜集node exporter监控数据
    static_configs:
    - targets: ['localhost:9090','localhost:9100'] # 对本机node_exporter 监控

举例新添加的对其它node节点抓取数据
  - job_name: '0.11'
    #重写了全局抓取间隔时间,由15秒重写成5秒。
    scrape_interval: 5s
    static_configs:
    - targets: ['192.168.0.11:9100']

Start the Prometheus service:

$ chown -R prometheus:prometheus /usr/local/prometheus-2.19.1.linux-amd64/
$ systemctl enable prometheus.service
$ systemctl start prometheus.service
$ systemctl status prometheus.service

Note: Pay attention to the directory permission changes before starting, otherwise you may report an error when starting Feb 11 16:08:41 localhost alertmanager: level=error ts=2019-02-11T08:08:41.419390133Z caller=main.go: 179 msg="Unable to create data directory" err="mkdir data/: permission denied".
Visit the Prometheus WEB to view the target host we defined: http://192.168.0.10:9090/targets
Insert picture description here
where "1" means normal, otherwise "0" means abnormal.
Insert picture description here
Use PromQL to query monitoring data.
Prometheus UI is a built-in visual management interface of Prometheus. Through Prometheus UI users can easily understand the current configuration of Prometheus and monitor the running status of tasks. Through the Graph panel, users can also directly use PromQL to query monitoring data in real time:
Insert picture description here
switch to the Graph panel, and users can use PromQL expressions to query the monitoring data of specific monitoring indicators. As shown below, to query the host load changes, you can use the keyword node_load1 to query the sample data of the host load collected by Prometheus. These sample data are displayed in chronological order, forming a trend chart of the host load over time:
Insert picture description here

PromQL is a powerful data query language customized by Prometheus. In addition to using monitoring indicators as query keywords, it also has a large number of built-in functions to help users further process time series data. For example, using the rate() function, you can calculate the change in sample data per unit time, that is, the growth rate. Therefore, through this function, we can approximate the CPU utilization rate through the CPU usage time:

rate(process_cpu_seconds_total[2m])

Insert picture description here
At this time, if you want to ignore that CPU, just use the without expression to aggregate the data after removing the label CPU:

avg without(cpu) (rate(process_cpu_seconds_total[2m]))

Insert picture description here

To query the CPU load of each server every 1 minute, you need to use the following query statement to query:

(1-((sum(increase(node_cpu_seconds_total{
    
    mode="idle"}[1m])) by (instance)) /(sum(increase(node_cpu_seconds_total[1m])) by (instance)))) * 100

Insert picture description here
Through PromQL, we can easily query, filter, aggregate, and calculate data. Through these rich expression book sentences, the monitoring indicators are no longer a single individual, but a language that can express formal business meaning.

Help document: https://yunlzheng.gitbook.io/prometheus-book/

Guess you like

Origin blog.csdn.net/ZhanBiaoChina/article/details/107024115