1. 程式人生 > >【ELK】elastalert 日誌告警

【ELK】elastalert 日誌告警

# 一、環境 ``` 系統:centos7 elk 版本:7.6.2 ``` ## 1.1 ElastAlert 工作原理 週期性的查詢Elastsearch並且將資料傳遞給規則型別,規則型別定義了需要查詢哪些資料。 當一個規則匹配觸發,就會給到一個或者多個的告警,這些告警具體會根據規則的配置來選擇告警途徑,就是告警行為,比如郵件、釘釘、tg、slack、企業微信等 [ElastAlert 手冊](https://elastalert.readthedocs.io/en/latest/elastalert.html#) # 二、安裝配置 elastalert **Tips:Elastalert 0.2.0 之後使用 Python 3.6,不再使用 Python 2 版本** ## 2.1 安裝 python3.6 ``` #安裝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 ``` ##2.2 安裝 elastalert ``` pip3 install elastalert ``` ###2.2.1 配置 ``` cd /opt/soft/ git clone https://github.com/Yelp/elastalert.git cd elastalert cp config.yaml.example config.yaml mkdir rules ``` ###2.2.2 樣例 https://github.com/Yelp/elastalert/tree/master/example_rules ### 2.2.3 config.yaml 配置檔案 ``` #規則目錄 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 ``` **以下配置沒使用,只做介紹 ** ``` #### 使用 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 ``` ###2.2.4 在 elasticsearch 中建立 elastalert 的日誌索引 **Tips : **如果索引已存在,則不會重新建立 ``` elastalert-create-index --index elastalert ``` 輸出結果: ``` 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' ``` ##2.3 常用命令 ``` # 測試規則檔案 elastalert-test-rule rule.yaml # 啟動監控報警 python3 -m elastalert.elastalert --verbose --rule /root/elastalert/example_rules/rule.yaml ``` ## 2.4 服務啟動方法 **Tips: 啟動指定家目錄的原因主要是有呼叫,可以少寫路徑,比如不需要指定 config.yml,rule 裡面的 yml 檔案可以少寫路徑指定==** ### 2.4.1 service 啟動管理 ``` # 建立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 ``` ### 2.4.2 supervisor 啟動管理 安裝supervisor ``` 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 ``` # 三、告警測試 ## 3.1 es 測試索引 ###3.1.1 建立並推送資料到 index `curl -X POST "http://elastic:[email protected]: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}` ###3.1.2 刪除 index `curl -X DELETE http://elastic:[email protected]:9200/test-alert` 輸出: `{"acknowledged":true}` ### 3.1.3 檢視有哪些索引 `curl 'http://elastic:[email protected]:9200/_cat/indices?v'` ###3.1.4檢視索引內容: `curl -X GET http://elastic:[email protected]: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"}}]}} ``` ## 3.2 郵件告警 ### 3.2.1 建立測試告警規則 `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: "[email protected]" ### 傳送郵件的賬號密碼 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: - "[email protected]" - "[email protected]" ``` ### 3.2.2 傳送郵件的賬號密碼 `vi /opt/soft/elastalert/elastalert/smtp_auth_file.yml` ``` # 發件箱的qq郵箱地址,也就是使用者名稱 user: [email protected] # 不是qq郵箱的登入密碼,是授權碼 password: passwd ``` ### 3.2.3 啟動告警規則併發送測試資料 ``` cd /opt/soft/elastalert python3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/emailtt.yml ``` ##3.3 釘釘告警 ###3.3.1 下載外掛 ``` cd /opt/soft/elastalert git clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugin cp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert/ ``` ### 3.3.2 安裝依賴 ``` #檢視依賴檔案elastalert-dingtalk-plugin/requirements.txt,在對比 pip list 之後,我發現只需要安裝以下內容即可 pip3 install pyOpenSSL==16.2.0 pip3 install requests==2.18.1 pip3 install setuptools>
=11.3 ``` ###3.3.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" ``` ### 3.3.4 啟動告警規則併發送測試資料 ``` cd /opt/soft/elastalert python3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/dingtt.yml ``` ### 3.3.5 釘釘機器人配置 具體可以檢視[釘釘機器人開發文件](https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq) 1. 最簡單可以使用加 ip 方式
2. 加關鍵字,就是傳送到釘釘的資訊裡面有某個關鍵字 ###3.3.6 測試結果告警內容如下所示 ## 3.4 微信告警 ###3.4.1 參考 https://github.com/anjia0532/elastalert-wechat-plugin https://anjia0532.github.io/2017/02/16/elastalert-wechat-plugin/ https://github.com/anjia0532/elastalert-docker ## 3.5 告警格式優化 ``` # 注意上下欄位對應 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 外掛 ##4.1 elastalert-kibana-plugin外掛 kibana中elastalert外掛,可以實現在kibana介面上編輯elastalert的告警規則配置。 kibana 的 elastalert 外掛需要使用新的 [bitsensor/elastalert](https://github.com/bitsensor/elastalert) api 服務 ### 4.1.1 演示效果
## 4.2 安裝 elastalert-kibana-plugin 官網主推:[bitsensor/elastalert-kibana-plugin](https://github.com/bitsensor/elastalert-kibana-plugin) 但是樓上那個很多小版本都沒有,以上沒有的話推薦使用以下版本: [nsano-rururu/elastalert-kibana-plugin](https://github.com/nsano-rururu/elastalert-kibana-plugin) 目前版本支援: - [Kibana 6.8.1~6.8.12、7.5.1~7.8.1](https://github.com/nsano-rururu/elastalert-kibana-plugin/releases/tag/1.2.0) - [Kibana 7.9.0~7.9.3](https://github.com/nsano-rururu/elastalert-kibana-plugin/releases/tag/1.3.0) ### 4.2.1 安裝命令 `/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` ### 4.2.2 配置 > 預設情況下,外掛將連線到 localhost:3030,也就是 kibana 和 elastalert 在同一臺伺服器上面,那麼就不需要新增以下配置。如果您的ElastAlert伺服器在其他主機或埠上執行,請在config / kibana.yml檔案中新增更改以下選項: ``` elastalert-kibana-plugin.serverHost: 192.168.1.1 elastalert-kibana-plugin.serverPort: 9000 ``` ##4.3 安裝 elastalert_docker 檢視 nsano 提供的 [elastalert api 服務支援列表](https://github.com/nsano-rururu/elastalert-kibana-plugin/wiki/ElastAlert-Server-Docker-Images) 我使用的是 [praecoapp/elastalert-server](https://hub.docker.com/r/praecoapp/elastalert-server) 提供的 docker 映象對應 [elastalert 0.2.4 版本](https://github.com/Yelp/elastalert/releases/tag/v0.2.4) [docker-compose sample 示例參考](https://github.com/nsano-rururu/elastalert-kibana-plugin/wiki/docker-compose-sample) ###4.3.1 安裝命令 ``` cd /opt/soft/ git clone https://github.com/bitsensor/elastalert.git elastalert_docker cd elastalert_docker mkdir rules ``` ### 4.3.2 更改配置,api server 端用的配置是config.json `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" } ``` ### 4.3.3 更改 elastalert 配置 `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 ``` ### 4.3.4 docker-compose.yml 配置檔案 `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,#這一句先註釋掉,下面有個操作 ``` ### 4.3.5 啟動 ``` docker-compose up -d ##然後把 docker 映象裡面的 elastalert 複製出來 docker cp elastalert:/opt/elastalert/elastalert . ##再把docker-compose.yml 裡面的 volumes 的註釋項去掉重新啟動 docker-compose up -d ``` ###4.3.6 配套釘釘外掛和規則測試 ``` 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 ``` ## 4.4 出現的報錯: ``` 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' } ``` 解決辦法: 1. 直接 chmod 777 -R /opt/soft/elastalert_docker/rules/ 2. 直接 chown centos.centos /opt/soft/elastalert_docker/rules/* ![image-20210122095445225](https://cdn.jsdelivr.net/gh/ZhaoUncle/image@main/blog/image-20210122095445225.png) # 五、告警規則詳解 [ElastAlert 規則介紹](https://elastalert.readthedocs.io/en/latest/ruletypes.html) ##5.1 告警型別 ``` ElastAlert包含幾種具有常見監視範例的規則型別: any: 匹配任何與給定過濾器匹配的事件,這個是查到了什麼便直接報警,屬於自定義選項; frequency: 匹配Y時間內至少有X個事件的地方 spike: 當事件發生率增加或減少時匹配,API 流量陡然上升並馬上恢復的時候; flatline: 在Y時間內少於X個事件時進行匹配,記憶體或者CPU使用率下降的時候; blacklist並whitelist輸入: 當某個欄位與黑名單/白名單匹配時匹配,昨天的那個疑似爬蟲的 IP 地址又出現了; change: 當某個欄位在一段時間內具有兩個不同的值時進行匹配,應用的狀態突然從 UP 轉為 DOWN; new_term: 當欄位中出現從未見過的術語時進行匹配,某個列舉型別欄位,突然出現了未定義的型別; cardinality:當欄位的唯一值數量大於或小於閾值時匹配,線上的 API 伺服器突然掛了一臺,它是根據唯一值的數量來判定的; ``` ##5.2 報警抑制:減少重複報警 ``` # 用來區分報警,跟 realert 配合使用,在這裡意味著, # 5 分鐘內如果有重複報警,那麼當 name 不同時,會當做不同的報警處理,可以是陣列 query_key: - name # 5 分鐘內相同的報警不會重複傳送 realert: minutes: 5 # 指數級擴大 realert 時間,中間如果有報警, # 則按照 5 -> 10 -> 20 -> 40 -> 60 不斷增大報警時間到制定的最大時間, # 如果之後報警減少,則會慢慢恢復原始 realert 時間 exponential_realert: hours: 1 ``` ##5.3 報警聚合:相同報警,聚合為一條 ``` # 根據報警的內,將相同的報警安裝 name 來聚合 aggregation_key: name # 聚合報警的內容,只展示 name 與 message summary_table_fields: - name - message ``` ##5.4 報警格式化:突出重要資訊 在這裡,你可以自定義 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最起碼要實現的需求: - 查詢條件(精確匹配):一級域名、二級域名、客戶真實IP、HTTP狀態碼、HTTP方法、request_time、response_time、代理IP、body_bytes_sent - 查詢條件(模糊匹配):url(如查詢SQL注入關鍵字)、refere(流量來源)、agent(如查詢搜尋引擎) - 近期(1周、1個月)內整體請求量走勢情況; - 如果發現總體走勢異常,要很方便找到那個域名走勢異常; - 過去一個週期內(1天、1周、1月)所有請求構成,按不同域名出餅圖; - 實時監控爬蟲IP過高的頻率訪問(如單個IP1分鐘請求超過100次報警); - 實時監控500狀態請求情況(如單個域名1分鐘出現30個500就報警); # 參考 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 https://segmentfault.com/a/1190000017553282 https://blog.csdn.net/wenwenxiong/article/details/106048313 https://www.cnblogs.com/liuxinyustu/articles/14228934.html