Prometheus监控神器-服务发现篇(六)

icegoblin
发布于 2022-7-6 15:26
浏览
0收藏

 

将Consul日志加入Syslog
此处为可选项,如果你需要单独将日志输出到ELK,那么此项配置非常有必要,因为默认的日志都打到syslog中了。

# 创建目录&赋权
mkdir -p /var/log/consul/
chown -R syslog.syslog /var/log/consul/

# 创建日志配置文件
cat >/etc/rsyslog.d/consul.conf <<EOF
local0.* /var/log/consul/consul.log
EOF

# 修改默认配置文件中的以下内容
vim /etc/rsyslog.d/50-default.conf

# 变更前
*.*;auth,authpriv.none          -/var/log/syslog

# 变更后
*.*;auth,authpriv.none,local0.none          -/var/log/syslog

# 重启rsyslog让配置生效。
$ systemctl restart rsyslog

# 创建日志轮循规则
$ cat >/etc/logrotate.d/consul <<EOF
/var/log/consul/*log {
missingok
compress
notifempty
daily
rotate 5
create 0600 root root
}
EOF

# 在Systemd启动脚本中加入`-syslog`参数
sed -i 's@ExecStart=/usr/local/bin/consul agent@ExecStart=/usr/local/bin/consul agent -syslog@g' /lib/systemd/system/consul-server{1..3}.service

# 重启服务
systemctl daemon-reload && systemctl restart consul-server1
systemctl daemon-reload && systemctl restart consul-server2
systemctl daemon-reload && systemctl restart consul-server3

# 查看输出日志,对于加入ELK的配置就不过多描述了,如果想了解,加入我们的qq群与微信群咨询相关解决方案。
tail -f /var/log/consul/consul.log

FAQ : 如果集群加入失败
 或 提示:Error retrieving members: Unexpected response code: 403 (ACL not 
found),toekn格式不对,需要重新检查集群节点tokens配置,格式为:'55eca91c-b5f7-e82d-7777-dba7637e8888',然后删除/data/consul/server{1..3}/data/目录下的数据,重启服务即可。

 

Prometheus集成Consul

# 基于AWS EC2 REDIS 发现规则

cat >> /data/prometheus/conf/prometheus.yml <<EOF
  - job_name: 'ec2_exporter'
      consul_sd_configs:
          - server: 172.26.42.229:8500
          token: '${CONSUL_HTTP_TOKEN}'
          services: ['node_exporter']
      relabel_configs:
          - source_labels: [__address__]
          regex: 172.26.42.229:8300
          action: drop
          - source_labels: [__meta_consul_tags]
          regex: ".*,prod,.*"
          replacement: prod
          action: replace
          target_label: env

  - job_name: 'redis_exporter'
      consul_sd_configs:
          - server: 172.26.42.229:28500
          token: '${CONSUL_HTTP_TOKEN}'
          services: ['redis_exporter']
      relabel_configs:
          - source_labels: [__address__]
          regex: 172.26.42.229:28300
          action: drop
          - source_labels: [__meta_consul_tags]
          regex: ".*,prod,.*"
          replacement: prod
          action: replace
          target_label: env
  - job_name: 'mysql_exporter'
      consul_sd_configs:
          - server: 172.26.42.229:38500
          token: '${CONSUL_HTTP_TOKEN}'
          services: ['mysql_exporter']
      relabel_configs:
          - source_labels: [__address__]
          regex: 172.26.42.229:38300
          action: drop
          - source_labels: [__meta_consul_tags]
          regex: ".*,prod,.*"
          replacement: prod
          action: replace
          target_label: env
EOF


# registered nginx01 service to consul1 , ID为唯一标识,用于删除,Name就是consul中service字段的发现关键字,tag可以依据自己的需求relableing。
curl -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" -X PUT -d '{"ID": "node_exporter01", "Name": "node_exporter", "Address": "192.168.1.220", "Port": 9100, "Tags": ["prod"], "EnableTagOverride": false}' \
http://192.168.1.153:8500/v1/agent/service/register

# registered redis01 to consul2
curl -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" -X PUT -d '{"ID": "redis_exporter01", "Name": "redis_exporter", "Address": "172.26.42.229", "Port": 9121, "Tags": ["prod"], "EnableTagOverride": false}' \
http://192.168.1.153:8500/v1/agent/service/register

# registered mysql01 to consul2
curl -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" -X PUT -d '{"ID": "mysql_exporter01", "Name": "mysql_exporter", "Address": "172.26.42.229", "Port": 9105, "Tags": ["prod"], "EnableTagOverride": false}' \
http://192.168.1.153:8500/v1/agent/service/register 

# delete nginx01 service 
curl -X PUT -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" http://192.168.1.153:8500/v1/agent/service/deregister/node_exporter01

# delete redis01 service
curl -X PUT -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" http://192.168.1.153:8500/v1/agent/service/deregister/redis_exporter01

# delete mysql_exporter01 service
curl -X PUT -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" http://192.168.1.153:8500/v1/agent/service/deregister/mysql_exporter01

使用Consul-template动态配置服务

# 安装Consul-template 下载地址:https://releases.hashicorp.com/consul-template/
wget https://releases.hashicorp.com/consul-template/0.22.0/consul-template_0.22.0_linux_amd64.zip
unzip consul-template_0.22.0_linux_amd64.zip
mv consul-template /usr/local/bin/
# 查看版本
consul-template -v
consul-template v0.22.0 (6cae10fe)

#常用参数的作用:
-consul-auth=<username[:password]>     # 设置基本的认证用户名和密码。
-consul-addr=<address>                 # 设置Consul实例的地址。
-max-stale=<duration>                  # 查询过期的最大频率,默认是1s。
-dedup                                 # 启用重复数据删除,当许多consul template实例渲染一个模板的时候可以降低consul的负载。
-consul-ssl                            # 使用https连接Consul。
-consul-ssl-verify                     # 通过SSL连接的时候检查证书。
-consul-ssl-cert                       # SSL客户端证书发送给服务器。
-consul-ssl-key                        # 客户端认证时使用的SSL/TLS私钥。
-consul-ssl-ca-cert                    # 验证服务器的CA证书列表。
-consul-token=<token>                  # 设置Consul API的token。
-syslog                                # 把标准输出和标准错误重定向到syslog,syslog的默认级别是local0。
-syslog-facility=<facility>            # 设置syslog级别,默认是local0,必须和-syslog配合使用。
-template=<template>                   # 增加一个需要监控的模板,格式是:'templatePath:outputPath(:command)',多个模板则可以设置多次。
-wait=<duration>                       # 当呈现一个新的模板到系统和触发一个命令的时候,等待的最大最小时间。如果最大值被忽略,默认是最小值的4倍。
-retry=<duration>                      # 当在和consul api交互的返回值是error的时候,等待的时间,默认是5s。
-config=<path>                         # 配置文件或者配置目录的路径。
-pid-file=<path>                       # PID文件的路径。
-log-level=<level>                     # 设置日志级别,可以是"debug","info", "warn" (default), and "err"。
-dry                                   # Dump生成的模板到标准输出,不会生成到磁盘。
-once                                  # 运行consul-template一次后退出,不以守护进程运行

# 在conf目录下创建1个nginx.json的配置文件
cat >> /data/consul/server1/config/nginx.json <<EOF
{
    "service":{
        "name":"nginx",
        "tags":[
            "web"
        ],
        "port":80,
        "check":{
            "http":"http://127.0.0.1:80",
            "interval":"10s"
        },
        "token":"233b604b-b92e-48c8-a253-5f11514e4b50"
    }
}
EOF

# 热加载配置文件
consul reload
# 验证服务是否注册成功
curl -H "x-consul-token: ${CONSUL_HTTP_TOKEN}" http://172.26.42.229:8500/v1/catalog/service/nginx | python -m json.tool
[
    {
        "Address": "192.168.1.153",
        "CreateIndex": 21233,
        "Datacenter": "prometheus",
        "ID": "09d82408-bc4f-49e0-4208-61ef1d4842f7",
        "ModifyIndex": 21233,
        "Node": "server1",
        "NodeMeta": {
            "consul-network-segment": ""
        },
        "ServiceAddress": "",
        "ServiceConnect": {},
        "ServiceEnableTagOverride": false,
        "ServiceID": "nginx",
        "ServiceKind": "",
        "ServiceMeta": {},
        "ServiceName": "nginx",
        "ServicePort": 80,
        "ServiceProxy": {
            "MeshGateway": {}
        },
        "ServiceTags": [
            "web"
        ],
        "ServiceWeights": {
            "Passing": 1,
            "Warning": 1
        },
        "TaggedAddresses": {
            "lan": "192.168.1.153",
            "wan": "192.168.1.155"
        }
    }
]

# 创建模板
cat > tmpltest.ctmpl << EOF
{{range services}}
{{.Name}}
{{range .Tags}}
{{.}}{{end}}
{{end}}
EOF

# 调用模板渲染
consul-template -consul-addr 192.168.1.153:8500 -template "/data/consul/consul-template/conf/tmpltest.ctmpl:result" -once

# 查看模板渲染的输出结果,返回的结果:consul是系统自带的服务,nginx是刚才注册的服务,Tags是web
cat result

consul

nginx

web

# 创建nginx模板文件
cat >> /data/consul/consul-template/conf/nginx.conf.ctmpl << EOF
{{range services}} {{$name := .Name}} {{$service := service .Name}}
upstream {{$name}} {
  zone upstream-{{$name}} 64k;
  {{range $service}}server {{.Address}}:{{.Port}} max_fails=3 fail_timeout=60 weight=1;
  {{else}}server 127.0.0.1:65535; # force a 502{{end}}
} {{end}}

server {
  listen 80 default_server;

  location / {
    root /usr/share/nginx/html/;
    index index.html;
  }

  location /stub_status {
    stub_status;
  }

{{range services}} {{$name := .Name}}
  location /{{$name}} {
    proxy_pass http://{{$name}};
  }
{{end}}
}
EOF

# 调用模板文件生成Nginx配置文件
consul-template -consul-addr 192.168.1.153:8500 -template "/data/consul/consul-template/conf/nginx.conf.ctmpl:nginx.conf" -once

# 为了更加安全,token从环境变量里读取,使用CONSUL_TOKEN和VAULT_TOKEN。强烈建议你不要把token放到未加密的文本配置文件中。
# 创建一个nginx.hcl文件
cat >> nginx.hcl << EOF
consul {
address = "192.168.1.153:8500"
}

template {
source = "/data/consul/consul-template/conf/nginx.conf.ctmpl"
destination = "/etc/nginx/conf/conf.d/default.conf"
command = "service nginx reload"
}
EOF

# 执行渲染命令
consul-template -config "nginx.hcl:test.out"

# 同时渲染多个template并放出后台启动
cat > consul_temp.sh << EOF
#!/bin/bash
#prom 
cd /data/consul/consul-template/ && nohup /usr/local/bin/consul-template -config=/data/consul/consul-template/hcl_conf/ & 2>&1
EOF

结语:
相比于直接使用静态配置和基于文件发现,是不利于云环境以及k8s环境的,因为我们大多时候更多监控对象都是动态的。因此,通过服务发现,使得Prometheus相比于其他传统监控解决方案更适用于云以及k8s环境下的监控需求。

 

欢迎大家关注我的公众号ID:k8stech


文章转自公众号:Kubernetes技术栈

标签
已于2022-7-6 15:26:20修改
收藏
回复
举报
回复
    相关推荐