Prometheus基于Golang编写,编译后的软件包,不依赖于任何的第三方依赖。用户只须要下载对应平台的二进制包,解压而且添加基本的配置便可正常启动Prometheus Server。html
一、下载安装包node
为您的平台下载最新版本的Prometheus,而后解压缩并运行它:mysql
https://prometheus.io/download/git
https://prometheus.io/docs/prometheus/latest/getting_started/github
tar xvfz prometheus-*.tar.gz cd prometheus-* mv prometheus-* /usr/local/prometheus
Centos7上,注册为服务:web
cat /usr/lib/systemd/system/prometheus.service sql
[Unit] Description=https://prometheus.io [Service] Restart=on-failure ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml [Install] WantedBy=multi-user.target
Centos6上,注册为服务:docker
#!/bin/bash # # Comments to support chkconfig # chkconfig: 2345 98 02 # description: prometheus service script # # Source function library. . /etc/init.d/functions ### Default variables prog_name="prometheus" config_file="/usr/local/${prog_name}/${prog_name}.yml" prog_path="/usr/local/${prog_name}/${prog_name}" data_path="/usr/local/${prog_name}/data" pidfile="/var/run/${prog_name}.pid" prog_logs="/var/log/${prog_name}.log" #启动项,监听本地9090端口,支持配置热加载 options="--web.listen-address=0.0.0.0:9090 --config.file=${config_file} --storage.tsdb.path=${data_path}" DESC="Prometheus Server" # Check if requirements are met [ -x "${prog_path}" ] || exit 1 RETVAL=0 start(){ action $"Starting $DESC..." su -s /bin/sh -c "nohup $prog_path $options >> $prog_logs 2>&1 &" 2> /dev/null RETVAL=$? PID=$(pidof ${prog_path}) [ ! -z "${PID}" ] && echo ${PID} > ${pidfile} echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog_name return $RETVAL } stop(){ echo -n $"Shutting down $prog_name: " killproc -p ${pidfile} RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog_name return $RETVAL } restart() { stop start } case "$1" in start) start ;; stop) stop ;; restart) restart ;; status) status $prog_path RETVAL=$? ;; *) echo $"Usage: $0 {start|stop|restart|status}" RETVAL=1 esac exit $RETVAL
Centos7:数据库
systemctl start prometheusapi
Centos6:
service prometheus start
https://prometheus.io/docs/prometheus/latest/installation/
prometheus.yml
经过运行如下命令将您从主机绑定:
docker run -p 9090:9090 -v /tmp/prometheus.yml:/etc/prometheus/prometheus.yml \ prom/prometheus
或者为配置使用额外的卷:
docker run -p 9090:9090 -v /prometheus-data \ prom/prometheus --config.file=/prometheus-data/prometheus.yml
http://localhost:9090访问本身的状态页面
能够经过访问localhost:9090验证Prometheus自身的指标:localhost:9090/metrics
Prometheus从目标机上经过http方式拉取采样点数据, 它也能够拉取自身服务数据并监控自身的健康情况
固然Prometheus服务拉取自身服务采样数据,并无多大的用处,可是它是一个好的DEMO。保存下面的Prometheus配置,并命名为:prometheus.yml:
global: scrape_interval: 15s # 默认状况下,每15s拉取一次目标采样点数据。 # 咱们能够附加一些指定标签到采样点度量标签列表中, 用于和第三方系统进行通讯, 包括:federation, remote storage, Alertmanager external_labels: monitor: 'codelab-monitor' # 下面就是拉取自身服务采样点数据配置 scrape_configs: # job名称会增长到拉取到的全部采样点上,同时还有一个instance目标服务的host:port标签也会增长到采样点上 - job_name: 'prometheus' # 覆盖global的采样点,拉取时间间隔5s scrape_interval: 5s static_configs: - targets: ['localhost:9090']
重启promethues服务。
经过http://10.11.100.99:9090/targets,就能够查看到了:
配置文件的格式是YAML,使用--config.file指定配置文件的位置。本节列出重要的配置项。
有关配置选项的完整,请参阅:https://prometheus.io/docs/prometheus/latest/configuration/configuration/
Prometheus以scrape_interval规则周期性从监控目标上收集数据,而后将数据存储到本地存储上。scrape_interval能够设定全局也能够设定单个metrics。
Prometheus以evaluation_interval规则周期性对告警规则作计算,而后更新告警状态。evaluation_interval只有设定在全局。
global:全局配置
alerting:告警配置
rule_files:告警规则
scrape_configs:配置数据源,称为target,每一个target用job_name命名。又分为静态配置和服务发现
global: # 默认抓取周期,设置每15s采集数据一次,默认1分钟 [ scrape_interval: <duration> | default = 1m ] # 默认抓取超时 [ scrape_timeout: <duration> | default = 10s ] # 估算规则的默认周期 # 每15秒计算一次规则。默认1分钟 [ evaluation_interval: <duration> | default = 1m ] # 和外部系统(例如AlertManager)通讯时为时间序列或者警情(Alert)强制添加的标签列表 external_labels: [ <labelname>: <labelvalue> ... ] # 规则文件列表 rule_files: [ - <filepath_glob> ... ] # 抓取配置列表 scrape_configs: [ - <scrape_config> ... ] # Alertmanager相关配置 alerting: alert_relabel_configs: [ - <relabel_config> ... ] alertmanagers: [ - <alertmanager_config> ... ] # 远程读写特性相关的配置 remote_write: [ - <remote_write> ... ] remote_read: [ - <remote_read> ... ]
其中,比较重要的配置为scrape_configs.
根据配置的任务(job)以http/s周期性的收刮(scrape/pull)
指定目标(target)上的指标(metric)。目标(target)
能够以静态方式或者自动发现方式指定。Prometheus将收刮(scrape)的指标(metric)保存在本地或者远程存储上。
使用scrape_configs定义采集目标
配置一系列的目标,以及如何抓取它们的参数。通常状况下,每一个scrape_config对应单个Job。
目标能够在scrape_config中静态的配置,也可使用某种服务发现机制动态发现。
# 任务名称,自动做为抓取到的指标的一个标签 job_name: <job_name> # 抓取周期 [ scrape_interval: <duration> | default = <global_config.scrape_interval> ] # 每次抓取的超时 [ scrape_timeout: <duration> | default = <global_config.scrape_timeout> ] # 从目标抓取指标的URL路径 [ metrics_path: <path> | default = /metrics ] # 当添加标签发现指标已经有同名标签时,是否保留原有标签不覆盖 [ honor_labels: <boolean> | default = false ] # 抓取协议 [ scheme: <scheme> | default = http ] # HTTP请求参数 params: [ <string>: [<string>, ...] ] # 身份验证信息 basic_auth: [ username: <string> ] [ password: <secret> ] [ password_file: <string> ] # Authorization请求头取值 [ bearer_token: <secret> ] # 从文件读取Authorization请求头 [ bearer_token_file: /path/to/bearer/token/file ] # TLS配置 tls_config: [ <tls_config> ] # 代理配置 [ proxy_url: <string> ] # DNS服务发现配置 dns_sd_configs: [ - <dns_sd_config> ... ] # 文件服务发现配置 file_sd_configs: [ - <file_sd_config> ... ] # K8S服务发现配置 kubernetes_sd_configs: [ - <kubernetes_sd_config> ... ] # 此Job的静态配置的目标列表,用的最多的配置!!! static_configs: [ - <static_config> ... ] # 目标重打标签配置 relabel_configs: [ - <relabel_config> ... ] # 指标重打标签配置 metric_relabel_configs: [ - <relabel_config> ... ] # 每次抓取容许的最大样本数量,若是在指标重打标签后,样本数量仍然超过限制,则整个抓取认为失败 # 0表示不限制 [ sample_limit: <int> | default = 0
三、relabel_configs
relabel_configs :容许在采集以前对任何目标及其标签进行修改
从新标签的意义?
action:从新标签动做
支持服务发现的来源:
Prometheus也提供了服务发现功能,能够从consul,dns,kubernetes,file等等多种来源发现新的目标。
其中最简单的是从文件发现服务。
https://github.com/prometheus/prometheus/tree/master/discovery
服务发现支持: endpoints,ingress,kubernetes,node,pod,service
node_exporter:用于*NIX系统监控,使用Go语言编写的收集器。
使用文档:https://prometheus.io/docs/guides/node-exporter/
GitHub:https://github.com/prometheus/node_exporter
exporter列表:https://prometheus.io/docs/instrumenting/exporters/
收集到 node_exporter 的数据后,咱们可使用 PromQL 进行一些业务查询和监控,下面是一些比较常见的查询。
注意:如下查询均以单个节点做为例子,若是你们想查看全部节点,将 instance="xxx" 去掉便可。
CPU使用率: 100 - (avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) * 100) 内存使用率: 100 - (node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes) / node_memory_MemTotal_bytes * 100 磁盘使用率: 100 - (node_filesystem_free_bytes{mountpoint="/",fstype=~"ext4|xfs"} / node_filesystem_size_bytes{mountpoint="/",fstype=~"ext4|xfs"} * 100)
mysql_exporter:用于收集MySQL性能信息。
https://github.com/prometheus/mysqld_exporter
https://grafana.com/dashboards/7362
登陆mysql为exporter建立帐号: mysql> CREATE USER 'exporter'@'localhost' IDENTIFIED BY 'XXXXXXXX' WITH MAX_USER_CONNECTIONS 3; mysql> GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost'; # cat .my.cnf [client] user=exporter password=exporter123 # ./mysqld_exporter --config.my-cnf=.my.cnf - job_name: 'mysql' static_configs: - targets: ['localhost:9104']
Grafana是一个开源的最近很是流行的度量分析和可视化工具。
https://grafana.com/grafana/download
Grafana支持查询普罗米修斯。自Grafana 2.5.0(2015-10-28)以来,包含了Prometheus的Grafana数据源。
Grafana.com维护着一组共享仪表板 ,能够下载并与Grafana的独立实例一块儿使用。
好比
https://grafana.com/dashboards/9276
告警无疑是监控中很是重要的环节,虽然监控数据可视化了,也很是容易观察到运行状态。但咱们很难作到时刻盯着监控,因此程序来帮巡检并自动告警,这个程序是幕后英雄,保障业务稳定性就靠它了。
前面讲到过Prometheus的报警功能主要是利用Alertmanager这个组件。当Alertmanager接收到 Prometheus 端发送过来的 Alerts 时,Alertmanager 会对 Alerts 进行去重复,分组,按标签内容发送不一样报警组,包括:邮件,微信,webhook。
使用prometheus进行告警分为两部分:Prometheus Server中的告警规则会向Alertmanager发送。而后,Alertmanager管理这些告警,包括进行重复数据删除,分组和路由,以及告警的静默和抑制。
在Prometheus平台中,警报由独立的组件Alertmanager处理。一般状况下,咱们首先告诉Prometheus Alertmanager所在的位置,而后在Prometheus配置中建立警报规则,最后配置Alertmanager来处理警报并发送给接收者(邮件,webhook、slack等)。
地址1:https://prometheus.io/download/
地址2:https://github.com/prometheus/alertmanager/releases
注册为服务
#!/bin/bash # # Comments to support chkconfig # chkconfig: 2345 98 02 # description: prometheus service script # # Source function library. . /etc/init.d/functions ### Default variables base_name="alertmanager" prog_name="alertmanager" config_file="/usr/local/${base_name}/${prog_name}.yml" prog_path="/usr/local/${base_name}/${prog_name}" data_path="/usr/local/${base_name}/data" pidfile="/var/run/${porg_name}.pid" prog_logs="/var/log/${prog_name}.log" #启动项,监听本地9090端口,支持配置热加载 options="--config.file=${config_file}" DESC="altermanager" # Check if requirements are met [ -x "${prog_path}" ] || exit 1 RETVAL=0 start(){ action $"Starting $DESC..." su -s /bin/sh -c "nohup $prog_path $options>> $prog_logs 2>&1 &" 2> /dev/null RETVAL=$? PID=$(pidof ${prog_path}) [ ! -z "${PID}" ] && echo ${PID} > ${pidfile} echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog_name return $RETVAL } stop(){ echo -n $"Shutting down $prog_name: " killproc -p ${pidfile} RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog_name return $RETVAL } restart() { stop start } case "$1" in start) start ;; stop) stop ;; restart) restart ;; status) status $prog_path RETVAL=$? ;; *) echo $"Usage: $0 {start|stop|restart|status}" RETVAL=1 esac exit $RETVAL
启动Alertmanager
service alertmanager start
一个完整的alertmanager.yml以下:
# 全局配置项 global: resolve_timeout: 5m #处理超时时间,默认为5min smtp_smarthost: 'smtp.sina.com:25' # 邮箱smtp服务器代理 smtp_from: '******@sina.com' # 发送邮箱名称 smtp_auth_username: '******@sina.com' # 邮箱名称 smtp_auth_password: '******' # 邮箱密码或受权码 wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/' # 企业微信地址 # 定义模板信心 templates: - 'template/*.tmpl' # 定义路由树信息 route: group_by: ['alertname'] # 报警分组依据 group_wait: 10s # 最初即第一次等待多久时间发送一组警报的通知 group_interval: 10s # 在发送新警报前的等待时间 repeat_interval: 1m # 发送重复警报的周期 对于email配置中,此项不能够设置太低,不然将会因为邮件发送太多频繁,被smtp服务器拒绝 receiver: 'email' # 发送警报的接收者的名称,如下receivers name的名称 # 定义警报接收者信息 receivers: - name: 'email' # 警报 email_configs: # 邮箱配置 - to: '******@163.com' # 接收警报的email配置 html: '{{ template "test.html" . }}' # 设定邮箱的内容模板 headers: { Subject: "[WARN] 报警邮件"} # 接收邮件的标题 webhook_configs: # webhook配置 - url: 'http://127.0.0.1:5001' send_resolved: true wechat_configs: # 企业微信报警配置 - send_resolved: true to_party: '1' # 接收组的id agent_id: '1000002' # (企业微信-->自定应用-->AgentId) corp_id: '******' # 企业信息(个人企业-->CorpId[在底部]) api_secret: '******' # 企业微信(企业微信-->自定应用-->Secret) message: '{{ template "test_wechat.html" . }}' # 发送消息模板的设定 # 一个inhibition规则是在与另外一组匹配器匹配的警报存在的条件下,使匹配一组匹配器的警报失效的规则。两个警报必须具备一组相同的标签。 inhibit_rules: - source_match: severity: 'critical' target_match: severity: 'warning' equal: ['alertname', 'dev', 'instance']
设置告警和通知的主要步骤以下:
a、配置Prometheus与Alertmanager通讯
# vi prometheus.yml alerting: alertmanagers: - static_configs: - targets: - 127.0.0.1:9093
b、在Prometheus中建立告警规则
# vi prometheus.yml rule_files: - "rules/*.yml" # vi rules/node.yml groups: - name: example # 报警规则组名称 rules: # 任何实例5分钟内没法访问发出告警 - alert: InstanceDown expr: up == 0 for: 5m #持续时间 , 表示持续一分钟获取不到信息,则触发报警 labels: severity: page # 自定义标签 annotations: summary: "Instance {{ $labels.instance }} down" # 自定义摘要 description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes." # 自定义具体描述
c、触发告警
d、告警状态
一旦这些警报存储在Alertmanager,它们可能处于如下任何状态:
这样目的是屡次判断失败才发告警,减小邮件。
route
属性用来设置报警的分发策略,它是一个树状结构,按照深度优先从左向右的顺序进行匹配。
route: receiver: 'default-receiver' group_wait: 30s group_interval: 5m repeat_interval: 4h group_by: [cluster, alertname] # 全部不匹配如下子路由的告警都将保留在根节点,并发送到“default-receiver” routes: # 全部service=mysql或者service=cassandra的告警分配到数据库接收端 - receiver: 'database-pager' group_wait: 10s match_re: service: mysql|cassandra # 全部带有team=frontend标签的告警都与此子路由匹配 # 它们是按产品和环境分组的,而不是集群 - receiver: 'frontend-pager' group_by: [product, environment] match: team: frontend
group_by
:报警分组依据
group_wait
:为一个组发送通知的初始等待时间,默认30s
group_interval
:在发送新告警前的等待时间。一般5m或以上
repeat_interval
:发送重复告警的周期。若是已经发送了通知,再次发送以前须要等待多长时间。一般3小时或以上
主要处理流程:
告警面临最大问题,是警报太多,至关于狼来了的形式。收件人很容易麻木,再也不继续理会。关键的告警经常被淹没。在一问题中,alertmanger在必定程度上获得很好解决。
Prometheus成功的把一条告警发给了Altermanager,而Altermanager并非简简单单的直接发送出去,这样就会致使告警信息过多,重要告警被淹没。因此须要对告警作合理的收敛。
告警收敛手段:
分组(group):将相似性质的警报分类为单个通知
抑制(Inhibition):当警报发出后,中止重复发送由此警报引起的其余警报
静默(Silences):是一种简单的特定时间静音提醒的机制
报警处理流程以下:
# cat rules/general.yml groups: - name: general.rules rules: - alert: InstanceDown expr: up == 0 for: 2m labels: severity: error annotations: summary: "Instance {{ $labels.instance }} 中止工做" description: "{{ $labels.instance }}: job {{ $labels.job }} 已经中止5分钟以上." # cat rules/node.yml groups: - name: node.rules rules: - alert: NodeFilesystemUsage expr: 100 - (node_filesystem_free_bytes{fstype=~"ext4|xfs"} / node_filesystem_size_bytes{fstype=~"ext4|xfs"} * 100) > 80 for: 2m labels: severity: warning annotations: summary: "{{$labels.instance}}: {{$labels.mountpoint }} 分区使用太高" description: "{{$labels.instance}}: {{$labels.mountpoint }} 分区使用大于 80% (当前值: {{ $value }})" - alert: NodeMemoryUsage expr: 100 - (node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes) / node_memory_MemTotal_bytes * 100 > 80 for: 2m labels: severity: warning annotations: summary: "{{$labels.instance}}: 内存使用太高" description: "{{$labels.instance}}: 内存使用大于 80% (当前值: {{ $value }})" - alert: NodeCPUUsage expr: 100 - (avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) * 100) > 80 for: 2m labels: severity: warning annotations: summary: "{{$labels.instance}}: CPU使用太高" description: "{{$labels.instance}}: CPU使用大于 80% (当前值: {{ $value }})" # cat rules/reload.yml groups: - name: prometheus.rules rules: - alert: AlertmanagerReloadFailed expr: alertmanager_config_last_reload_successful == 0 for: 10m labels: severity: warning annotations: summary: "{{$labels.instance}}: Alertmanager配置从新加载失败" description: "{{$labels.instance}}: Alertmanager配置从新加载失败" - alert: PrometheusReloadFailed expr: prometheus_config_last_reload_successful == 0 for: 10m labels: severity: warning annotations: summary: "{{$labels.instance}}: Prometheus配置从新加载失败" description: "{{$labels.instance}}: Prometheus配置从新加载失败"