系统:centos7 elk 版本:7.6.2
周期性的查询Elastsearch而且将数据传递给规则类型,规则类型定义了须要查询哪些数据。php
当一个规则匹配触发,就会给到一个或者多个的告警,这些告警具体会根据规则的配置来选择告警途径,就是告警行为,好比邮件、钉钉、tg、slack、企业微信等html
ElastAlert 手册python
Tips:Elastalert 0.2.0 以后使用 Python 3.6,再也不使用 Python 2 版本git
#安装EPEL和IUS软件源 yum install epel-release -y yum install https://centos7.iuscommunity.org/ius-release.rpm -y #安装python3.6 yum install python36u python36u-devel python36u-pip -y #ln -s /usr/bin/python3.6 /bin/python3 #ln -s /usr/bin/pip3.6 /bin/pip3
pip3 install elastalert
cd /opt/soft/ git clone https://github.com/Yelp/elastalert.git cd elastalert cp config.yaml.example config.yaml mkdir rules
https://github.com/Yelp/elastalert/tree/master/example_rulesgithub
#规则目录 rules_folder: /opt/soft/elastalert/rules #多久从ES中查询一次 run_every: seconds: 30 #是查询窗口的大小,从每一个查询运行的时间向后延伸。对于其中use_count_query或use_terms_query设置为true的规则,此值将被忽略。 buffer_time: minutes: 15 #链接elasticsearch配置 es_host: 127.0.0.1 es_port: 9200 es_username: elastic es_password: xxxxxxxx #elastalert索引名称 writeback_index: elastalert_status writeback_alias: elastalert_alerts #失败重试限制 alert_time_limit: days: 2
**如下配置没使用,只作介绍 **web
#### 使用 TLS 链接诶 elastsearch #use_ssl: True #验证 tls 证书 #verify_certs: True #带正文的GET请求是Elasticsearch的默认选项。若是由于某些缘由失败了,你能够经过'GET','POST'或'source',具体能够查看如下(http://elasticsearch-py.readthedocs.io/en/master/connection.html?highlight=send_get_body_as#transport) #es_send_get_body_as: GET # 开启 ssl 认证证书 #verify_certs: True #ca_certs: /path/to/cacert.pem #client_cert: /path/to/client_cert.pem #client_key: /path/to/client_key.key
**Tips : **若是索引已存在,则不会从新建立docker
elastalert-create-index --index elastalert
输出结果:json
ProcessController: Elastic Version: 7.6.2 Reading Elastic 6 index mappings: Reading index mapping 'es_mappings/6/silence.json' Reading index mapping 'es_mappings/6/elastalert_status.json' Reading index mapping 'es_mappings/6/elastalert.json' Reading index mapping 'es_mappings/6/past_elastalert.json' Reading index mapping 'es_mappings/6/elastalert_error.json'
# 测试规则文件 elastalert-test-rule rule.yaml # 启动监控报警 python3 -m elastalert.elastalert --verbose --rule /root/elastalert/example_rules/rule.yaml
Tips: 启动指定家目录的缘由主要是有调用,能够少写路径,好比不须要指定 config.yml,rule 里面的 yml 文件能够少写路径指定==vim
# 建立elastalert服务文件 vim /etc/systemd/system/elastalert.service
[Unit] Description=elastalert After=elasticsearch.service [Service] Type=simple User=root Group=root Restart=on-failure WorkingDirectory=/opt/soft/elastalert ExecStart=/usr/bin/python3 -m elastalert.elastalert --verbose --config /opt/soft/elastalert/config.yaml [Install] WantedBy=multi-user.target
安装supervisorc#
yum install -y supervisor systemctl enable supervisord
编写elastalert supervisord守护进程
vim /etc/supervisord.d/elastalert.ini
[program:elastalert] directory=/opt/soft/elastalert command=/usr/bin/python3 -m elastalert.elastalert --verbose autostart=true startsecs=5 autorestart=true startretries=10 redirect_stderr=true stdout_logfile_maxbytes=20MB stdout_logfile_backups=5 stdout_logfile=/var/log/elastalert/elastalert.log
启动
systemctl enable supervisord systemctl restart supervisord systemctl start supervisord systemctl stop supervisord supervisorctl status
curl -X POST "http://elastic:passwd@127.0.0.1:9200/test-alert/test" -H 'Content-Type: application/json' -d '{"@timestamp": "'$(date --iso-8601=seconds)'", "field": "value"}'
输出:
{"_index":"test-alert","_type":"test","_id":"inH1I3cBMJwNYi416aLN","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}
curl -X DELETE http://elastic:passwd@127.0.0.1:9200/test-alert
输出:
{"acknowledged":true}
curl 'http://elastic:passwd@127.0.0.1:9200/_cat/indices?v'
curl -X GET http://elastic:passwd@127.0.0.1:9200/test-alert/_search
输出结果:
{"took":2,"timed_out":false,"shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":4,"relation":"eq"},"max_score":1.0,"hits":[{"index":"test-alert","type":"test","id":"inH1I3cBMJwNYi416aLN","score":1.0,"source":{"@timestamp": "2021-01-21T08:01:52+00:00", "field": "value"}},{"index":"test-alert","type":"test","id":"0ocXJHcBMJwNYi41y3rG","score":1.0,"source":{"@timestamp": "2021-01-21T08:37:55+0000", "field": "value"}},{"index":"test-alert","type":"test","id":"aZAiJHcBMJwNYi41QTqW","score":1.0,"source":{"@timestamp": "2021-01-21T08:49:20+0000", "field": "value"}},{"index":"test-alert","type":"test","id":"1ZMmJHcBMJwNYi41h4z8","score":1.0,"source":{"@timestamp": "2021-01-21T08:54:00+0000", "field": "value"}}]}}
vim /opt/soft/elastalert/rules/emailtt.yml
name: test-alert type: any # es 的监控索引 index: test-ale* # 发现 1 次就告警 num_events: 1 #1 分钟检查1次,和上面一块儿配合就是 1 分钟内触发 1 次规则就告警 timeframe: minutes: 1 #告警规则,查询索引内 field 字段的值 value,能够用正则进行匹配 filter: - query: query_string: query: "field: *value*" ## smtp 邮件 server 配置 smtp_host: smtp.zoho.com smtp_port: 465 smtp_ssl: true from_addr: "test@qq.com" ### 发送邮件的帐号密码 smtp_auth_file: /opt/soft/elastalert/elastalert/smtp_auth_file.yml #告警方式 alert: - "email" #设置只须要的告警字段 include: ["_index","uri","remote_addr","http_x_forwarded_for","status"] #邮件标题 alert_subject: "test-alert 正式环境 告警 {}" #告警邮件接收人 email: - "test@qq.com" - "test1@qq.comk"
vi /opt/soft/elastalert/elastalert/smtp_auth_file.yml
# 发件箱的qq邮箱地址,也就是用户名 user: test@qq.com # 不是qq邮箱的登陆密码,是受权码 password: passwd
cd /opt/soft/elastalert python3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/emailtt.yml
cd /opt/soft/elastalert git clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugin cp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert/
#查看依赖文件elastalert-dingtalk-plugin/requirements.txt,在对比 pip list 以后,我发现只须要安装如下内容便可 pip3 install pyOpenSSL==16.2.0 pip3 install requests==2.18.1 pip3 install setuptools>=11.3
vim /opt/soft/elastalert/rules/dingtt.yml
name: Example frequency rule type: any index: test-alert num_events: 1 timeframe: minutes: 1 filter: - query: query_string: query: "field: value" #告警方式 alert: - "elastalert.dingtalk_alert.DingTalkAlerter" #钉钉接口 dingtalk_webhook: "https://oapi.dingtalk.com/robot/send?access_token=钉钉机器人 api token" dingtalk_msgtype: "text"
cd /opt/soft/elastalert python3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/dingtt.yml
具体能够查看钉钉机器人开发文档
https://github.com/anjia0532/elastalert-wechat-plugin
https://anjia0532.github.io/2017/02/16/elastalert-wechat-plugin/
https://github.com/anjia0532/elastalert-docker
# 注意上下字段对应 alert_text: | kibana_url: "https://hostname:5601/app/kibana" alarm_reason: "1分钟内login.php至少被访问10次" alarm_name: {} request_uri: {} request_ip: {} response_status: {} alert_text_args: - name - request - clientip - response alert_text_type: alert_text_only
kibana中elastalert插件,能够实如今kibana界面上编辑elastalert的告警规则配置。
kibana 的 elastalert 插件须要使用新的 bitsensor/elastalert api 服务
官网主推:bitsensor/elastalert-kibana-plugin
可是楼上那个不少小版本都没有,以上没有的话推荐使用如下版本:
nsano-rururu/elastalert-kibana-plugin
目前版本支持:
/usr/share/kibana/bin/kibana-plugin install https://github.com/nsano-rururu/elastalert-kibana-plugin/releases/download/1.2.0/elastalert-kibana-plugin-1.2.0-7.6.2.zip --allow-root
默认状况下,插件将链接到 localhost:3030,也就是 kibana 和 elastalert 在同一台服务器上面,那么就不须要添加如下配置。若是您的ElastAlert服务器在其余主机或端口上运行,请在config / kibana.yml文件中添加更改如下选项:
elastalert-kibana-plugin.serverHost: 192.168.1.1 elastalert-kibana-plugin.serverPort: 9000
查看 nsano 提供的 elastalert api 服务支持列表
我使用的是 praecoapp/elastalert-server 提供的 docker 镜像对应 elastalert 0.2.4 版本
cd /opt/soft/ git clone https://github.com/bitsensor/elastalert.git elastalert_docker cd elastalert_docker mkdir rules
vi config/config.json
由于个人 kibana 和 elastalert docker 是同一台机,因此我主要修改 es 的配置就能够
{ "appName": "elastalert-server", "port": 3030, "wsport": 3333, "elastalertPath": "/opt/elastalert", "verbose": false, "es_debug": false, "debug": false, "rulesPath": { "relative": true, "path": "/rules" }, "templatesPath": { "relative": true, "path": "/rule_templates" }, "es_host": "192.168.3.30", "es_port": 9200, "writeback_index": "elastalert_status" }
vi ./config/elastalert.yaml
es_host: 192.168.3.30 es_port: 9200 rules_folder: rules run_every: seconds: 5 buffer_time: minutes: 1 es_username: elastic es_password: passwd writeback_index: elastalert_status alert_time_limit: days: 2
vi docker-compose.yml
version: '3' services: elastalert: image: praecoapp/elastalert-server:20210104 container_name: elastalert hostname: elastalert restart: always network_mode: "host" ports: - "3030:3030" - "3333:3333" volumes: - ./config/elastalert.yaml:/opt/elastalert/config.yaml - ./config/elastalert-test.yaml:/opt/elastalert/config-test.yaml - ./config/config.json:/opt/elastalert-server/config/config.json - ./rules:/opt/elastalert/rules - ./rule_templates:/opt/elastalert/rule_templates #- ./elastalert:/opt/elastalert/elastalert,#这一句先注释掉,下面有个操做
docker-compose up -d ##而后把 docker 镜像里面的 elastalert 复制出来 docker cp elastalert:/opt/elastalert/elastalert . ##再把docker-compose.yml 里面的 volumes 的注释项去掉从新启动 docker-compose up -d
cd /opt/soft/elastalert_docker git clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugin cp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert/ ##安装依赖 docker exec -it elastalert pip install pyOpenSSL==16.2.0 docker exec -it elastalert pip install requests==2.18.1 docker exec -it elastalert pip install setuptools>=11.3 #建立规则 touch rules/dingtt.yml #受权,不然页面没法编辑,具体能够看下面的报错示例 chown centos.centos rules/dingtt.yml #从新启动 elastalert 容器 docker restart elastalert ##查看日志 docker logs -f --tail=20 elastalert
01:50:07.285Z ERROR elastalert-server: Routes: Request for '/rules/:id' failed with error: [Error: EACCES: permission denied, open '/opt/elastalert/rules/dingtt.yaml'] { errno: -13, code: 'EACCES', syscall: 'open', path: '/opt/elastalert/rules/dingtt.yaml' }
解决办法:
ElastAlert包含几种具备常见监视范例的规则类型: any: 匹配任何与给定过滤器匹配的事件,这个是查到了什么便直接报警,属于自定义选项; frequency: 匹配Y时间内至少有X个事件的地方 spike: 当事件发生率增长或减小时匹配,API 流量陡然上升并立刻恢复的时候; flatline: 在Y时间内少于X个事件时进行匹配,内存或者CPU使用率降低的时候; blacklist并whitelist输入: 当某个字段与黑名单/白名单匹配时匹配,昨天的那个疑似爬虫的 IP 地址又出现了; change: 当某个字段在一段时间内具备两个不一样的值时进行匹配,应用的状态忽然从 UP 转为 DOWN; new_term: 当字段中出现从未见过的术语时进行匹配,某个枚举类型字段,忽然出现了未定义的类型; cardinality:当字段的惟一值数量大于或小于阈值时匹配,线上的 API 服务器忽然挂了一台,它是根据惟一值的数量来断定的;
# 用来区分报警,跟 realert 配合使用,在这里意味着, # 5 分钟内若是有重复报警,那么当 name 不一样时,会当作不一样的报警处理,能够是数组 query_key: - name # 5 分钟内相同的报警不会重复发送 realert: minutes: 5 # 指数级扩大 realert 时间,中间若是有报警, # 则按照 5 -> 10 -> 20 -> 40 -> 60 不断增大报警时间到制定的最大时间, # 若是以后报警减小,则会慢慢恢复原始 realert 时间 exponential_realert: hours: 1
# 根据报警的内,将相同的报警安装 name 来聚合 aggregation_key: name # 聚合报警的内容,只展现 name 与 message summary_table_fields: - name - message
在这里,你能够自定义 alert 的内容,它的内部使用 Python 的 format 来实现的。
alert_subject: "Error {} @{}" alert_subject_args: - name - "@timestamp" alert_text_type: alert_text_only alert_text: | ### Error frequency exceeds > Name: {} > Message: {} > Host: {} ({}) alert_text_args: - name - message - hostname - host
Email Slack 企业微信 钉钉 alerta:https://github.com/alerta/alerta,告警接收平台 JIRA OpsGenie Commands HipChat MS Teams Telegram AWS SNS VictorOps PagerDuty Exotel Twilio Gitter
整理下实施ELK最起码要实现的需求:
https://github.com/Yelp/elastalert
https://github.com/bitsensor/elastalert
https://github.com/bitsensor/elastalert-kibana-plugin
https://github.com/xuyaoqiang/elastalert-dingtalk-plugin
https://github.com/anjia0532/elastalert-wechat-plugin
http://www.javashuo.com/article/p-yrjmqnxo-ko.html