es watcher插件安装及使用

es watcher插件安装及使用

简介

  • watcher是一个用于elasticsearch的插件,它可以根据数据的变化提供警报和通知

安装

  • 从5.0版本之后,watcher就成为了x-pack的一部分,也就是说安装了x-pack,watcher就已经安装了。

使用

  • 验证watcher是否启动:
 curl --user elastic:changeme -XGET 'http://172.30.1.45:9200/_watcher/stats?pretty'

返回:
{
  "watcher_state" : "started",
  "watch_count" : 0,
  "execution_thread_pool" : {
    "queue_size" : 0,
    "max_size" : 10
  },
  "manually_stopped" : false
}

说明watcher已经启动
  • watcher通常用于两个场景:

    • 监控日志数据的错误(Watch Log Data for Errors)
    • 监控es集群的状态(Watch Your Cluster Health)
  • 构建一个watcher,watcher的主体内容包含四部分:

    • 触发设置(trigger):设置一个检查错误日志数据的周期(periodically checks your log data for error conditions),以下是两种表达式:
      • ”schedule” : { “interval” : “10s” } 每十秒检查一次
      • “schedule” : { “cron” : “0 0/1 * * * ?” } 每分钟一次
      • 通常Schedules 配置不会很频繁的,配置10s是为了方便触发,便于测试,测试完成要记得删除测试watcher
    "trigger" : { 
        "schedule" : { "interval" : "10s" } 
    }
    或者
     "trigger" : { 
        "schedule" : { "cron" : "0 0/1 * * * ?" } 
    }
    
    • 数据来源设置(input):
    "input" : {
        "search" : {
            "request" : {
                "indices": ["ecps-*"],  //索引名称
                "body" : {
                    "query" : {
                        "match" : { "message": "WEIFAN-NIHAO" }
                    }
                }
            }
        }
    }
    
    match短语:
    
    "match" : {
        "message" : {
            "query" : "this is a test",
            "type" : "phrase"
        }
    }
    • 条件设置(condition):判断要监控的内容是否命中(checks to see if any errors were found or hit)
    条件:总命中数大于2,gt是大于,gte是大于等于
    
    "condition" : {
        "compare" : { "ctx.payload.hits.total" : { "gt" : 2 }}
    }
    
    ctx.payload.hits   查询结果命中内容
    ctx.payload.hits.total  查询结果命中数量
    ctx.payload.hits.hits.2  指定第几个命中的,0是起始索引
    ctx.payload.hits.hits.<index>.fields.<fieldname> 指定第几个命中的某个属性,eg:ctx.payload.hits.hits.0.fields.message
    
    以上均可可以作为邮件内容发送
    • 动作设置(actions): 一旦监控的内容命中,需要采取的措施,可以打印日志或者邮件预警等。(Take action if there are any errors)
    可以把命中数动态写入动作内容:
    
    动作一:通过打印日志
    
    logging:会将日志打印到es的标准输出日志中!(A watch action that simply logs text to the standard Elasticsearch logs)
    
    "actions" : {
        "log_error" : {//动作id
            "logging" : {
                "text" : "Found {{ctx.payload.hits.total}} errors in the logs, message:服务挂了!!!",
                "level": info //默认就是info
            }
        }
    }
    
    动作二:通过发送邮件
    
    "actions" : {
        "reminder_email" : {//动作 id
            "email" : {
                "to" : "to@host.domain",//收件人地址
                "subject" : "system error",//主题
                "body" : "Found {{ctx.payload.hits.total}} errors in the logs, message:服务挂了!!!"//内容
        },
       "priority" : "high"//优先级:lowest, low, normal, high and highest
    }
    
  • 测试(测试过程可以直接在kibana dev tools 控制台进行):

# 验证watcher是否启动
 curl --user elastic:changeme -XGET 'http://172.30.1.45:9200/_watcher/stats?pretty'

# 创建索引index1
curl --user elastic:changeme -XPUT '172.30.1.45:9200/index1?pretty'

# 设置watch,id:weifan_watch
curl --user elastic:changeme -XPUT 'http://172.30.1.45:9200/_watcher/watch/weifan_watch' -d '{这里是watch的配置,json字符串}

# 测试案例一:
curl --user elastic:changeme -XPUT 'http://172.30.1.45:9200/_watcher/watch/weifan_watch' -d '{
  "trigger" : { "schedule" : { "interval" : "10s" } },
  "input" : {
    "search" : {
      "request" : {
        "indices":["index1"],
        "body" : {
          "query" : {
            "match" : { "message": "YIKANG" }//这里的message是精确匹配
          }
        }
      }
    }
  },
  "condition" : {
    "compare" : { "ctx.payload.hits.total" : { "gte" : 1 }}
  },
  "actions" : {
    "log_error" : {
      "logging" : {
        "text" : "Found {{ctx.payload.hits.total}} errors in the logs,message: 服务挂了!!!"
      }
    }
  }
}'

# 测试案例二:
curl --user elastic:changeme -XPUT 'http://172.30.1.45:9200/_watcher/watch/weifan_watch' -d '{
  "trigger" : { "schedule" : { "interval" : "10s" } },
  "input" : {
    "search" : {
      "request" : {
        "indices":["index1"],
        "body" : {
          "query" : {
           "match" : {
                "message" : {
                    "query" : "java.lang.OutOfMemoryError",
                    "type" : "phrase"//这里的message是根据短语匹配,message包含关键字即可预警
                }
            }
          }
        }
      }
    }
  },
  "condition" : {
    "compare" : { "ctx.payload.hits.total" : { "gte" : 1 }}
  },
  "actions" : {
    "log_error" : {
      "logging" : {
        "text" : "Found {{ctx.payload.hits.total}} errors in the logs,message: 服务挂了!!!"
      }
    }
  }
}'

# 查看watcher内容:
curl --user elastic:changeme -XGET 'http://172.30.1.45:9200/_watcher/watch/weifan_watch'

# 往es里面放数据,索引index1,type:type1,ID:1
# 测试案例一:
curl -XPOST '172.30.1.45:9200/index1/type1/1?pretty' -d '{"message": "YIKANG" }'

# 测试案例二:
curl -XPOST '172.30.1.45:9200/index1/type1/1?pretty' -d '{"message": "tomcat: java.lang.OutOfMemoryError: PermGen space" }'

查看es标准输出日志,是否打印:Found 1 errors in the logs,message: 服务挂了!!!,如果打印,即测试通过

# 删除测试watcher:
curl --user elastic:changeme -XDELETE 'http://172.30.1.45:9200/_watcher/watch/weifan_watch'

其他可能用到的命令:

# 查看索引信息(根据id查询):
curl --user elastic:changeme -XGET '172.30.1.45:9200/index1/type1/1?pretty'

# 查看索引内容(索引下所有):
curl --user elastic:changeme '172.30.1.45:9200/index1/_search?q=*&pretty'

# 删除索引:
curl --user elastic:changeme -XDELETE '172.30.1.45:9200/index1?pretty'

# 列举所有索引
curl --user elastic:changeme 'http://172.30.1.45:9200/_cat/indices?v'
<think>好的,我现在需要帮助用户使用Elasticsearch Watcher来设置基于防火墙威胁日志数量激增的告警,并通过邮件发送包含统计信息的通知。用户之前的问题是关于Kibana告警的配置,现在转向使用Watcher,可能需要更复杂的条件或更灵活的设置。 首先,用户提到“日志数量激增”,比如10分钟内数量翻倍。在之前的回答中,我指导用户使用Kibana的告警规则,但这里用户明确要求使用Elasticsearch WatcherWatcherElasticsearch的告警功能,更底层,适合复杂场景,而Kibana的告警可能更简单。需要确认两者的区别,并调整步骤。 接下来,用户需求中的关键点: 1. 使用Elasticsearch Watcher。 2. 基于日志数量激增的条件,比如10分钟内数量翻倍。 3. 邮件通知包含统计信息,如具体威胁类型及其数量。 需要参考用户提供的引用内容,特别是关于ELK Stack和告警的部分。引用中提到了ELK的日志收集、传输、存储和告警,但用户现在需要的是Watcher的具体配置。 用户之前的配置使用了Kibana的告警规则,现在要转换为Watcher的JSON配置。需要确保语法正确,包括输入、条件、动作等部分。可能需要构建一个Watcher,定期执行查询,比较当前窗口与前一时段的日志数量,并触发邮件。 另外,用户希望邮件中包含统计信息,这意味着Watcher的查询需要做聚合,按威胁类型分组统计数量。这需要在Watcher的输入部分设置terms aggregation。 还需要处理时间窗口的问题,比如当前10分钟和前10分钟的数据对比。可能需要使用Elasticsearch的日期范围查询,结合聚合来获取数量变化。同时,触发条件需要判断当前数量是否超过前一时段的两倍。 邮件内容需要动态填充统计结果,可能需要使用Mustache模板来生成邮件正文,将聚合结果循环展示出来。 需要注意Watcher的权限和配置,确保Elasticsearch集群启用了Watcher功能,并且SMTP设置正确,以便发送邮件。用户之前配置过Kibana的SMTP,但Watcher可能需要单独配置,或者使用相同的设置? 此外,用户的环境是微服务架构,日志分散,可能需要确保所有相关日志都正确索引到Elasticsearch,并且有统一的Trace ID,方便追踪。但当前问题聚焦在Watcher设置,这部分可能属于环境准备步骤,需要用户确认日志收集和存储是否已经正常。 测试步骤也很重要,需要指导用户如何手动触发测试日志,验证Watcher是否正常工作,以及如何查看执行历史记录来调试问题。 总结步骤: 1. 确认环境准备,包括Elasticsearch和Watcher的启用,SMTP配置。 2. 编写Watcher的JSON定义,包括输入查询、条件判断、聚合统计。 3. 配置邮件动作,使用模板插入统计信息。 4. 部署和测试Watcher,确保告警触发和邮件发送正常。 5. 提供优化建议,比如加入Trace ID或使用Kafka缓冲。 需要确保每个步骤的细节正确,例如时间窗口的计算、比较条件的语法、聚合查询的正确性。可能还需要处理时区问题,确保查询的时间范围正确。 最后,用户的相关问题可能涉及Watcher的高级用法、与其他系统的集成,或者性能优化,需要在回答后列出这些问题,帮助用户进一步探索。</think>基于Elasticsearch Watcher实现防火墙威胁日志激增告警的核心配置可分为以下步骤: --- ### **一、Watcher基础架构** Watcher由三部分组成: - **Input**:数据输入(日志查询) - **Condition**:触发条件(数量对比) - **Actions**:告警动作(邮件通知) $$ \text{Watcher} = \left\{ \text{Input} \rightarrow \text{Condition} \rightarrow \text{Actions} \right\} $$ --- ### **二、告警规则配置** #### **1. 输入阶段(Input)** ```json "input": { "search": { "request": { "indices": ["firewall-*"], "body": { "size": 0, "query": { "range": { "@timestamp": { "gte": "now-10m", "lte": "now" } } }, "aggs": { "current_threats": { "value_count": { "field": "threat.type.keyword" } }, "threat_types": { "terms": { "field": "threat.type.keyword", "size": 10 } } } } } } } ``` > 通过聚合查询获取: > - 当前窗口期(10分钟)总威胁量`current_threats` > - 具体威胁类型分布`threat_types` #### **2. 条件判断(Condition)** ```json "condition": { "script": { "source": """ def prev = ctx.payload.hits.total.value; def current = ctx.payload.aggregations.current_threats.value; return current >= prev * 2; """, "params": { "prev_window": "now-20m/m", "current_window": "now-10m/m" } } } ``` > 对比当前窗口与前一时段的日志量,实现$ \text{current} \geq 2 \times \text{previous} $判断[^1] #### **3. 邮件动作(Actions)** ```json "actions": { "send_email": { "email": { "to": "security@example.com", "subject": "防火墙威胁激增告警 - 检测到{{ctx.payload.aggregations.current_threats.value}}次攻击", "body": """ 时间窗口:{{ctx.watch.trigger.triggered_time}} 威胁分布: {{#ctx.payload.aggregations.threat_types.buckets}} ▸ {{key}}: {{doc_count}}次 {{/ctx.payload.aggregations.threat_types.buckets}} 原始日志查询:{{ctx.watch_id}} """ } } } ``` --- ### **三、部署与验证** 1. **创建Watcher** ```bash PUT _watcher/watch/firewall_threat_alert { "trigger": { "schedule": { "interval": "5m" } }, "input": { ... }, // 上述Input配置 "condition": { ... }, // 上述Condition配置 "actions": { ... } // 上述Actions配置 } ``` 2. **调试技巧** - 执行模拟测试:`POST _watcher/watch/firewall_threat_alert/_execute` - 查看执行记录:`GET .watcher-history*/_search` --- ### **四、进阶优化建议** 1. **加入Trace ID** 在日志采集阶段注入唯一追踪标识: ```json "processors": [ { "set": { "field": "trace_id", "value": "{{_id}}" } } ] ``` 2. **引入Kafka缓冲** 使用Logstash Kafka插件避免日志洪峰: ```conf input { kafka { topics => ["firewall-logs"] } } filter { grok { match => { "message" => "%{SYSLOG5424LINE}" } } } output { elasticsearch { hosts => ["es01:9200"] } } ``` --- ### **相关问题** 1. 如何实现Watcher与其他告警系统(如PagerDuty)的联动? 2. Elasticsearch Watcher与Kibana Alerting有何本质区别? 3. 如何通过Watcher监控微服务间的异常调用链? : 注意时间窗口计算需考虑时区设置,建议使用UTC时间避免偏差 [^2]: 当威胁类型超过50种时,建议采用滚动聚合优化性能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值