[TOC]
關於SkyWalking的基礎使用參考:
官方文檔:
SkyWalking 告警功能
SkyWalking 告警功能是在6.x版本新增的,其核心由一組規則驅動,這些規則定義在config/alarm-settings.yml
文件中。 告警規則的定義分爲兩部分:
- 告警規則:它們定義了應該如何觸發度量警報,應該考慮什麼條件。
- Webhook(網絡鉤子):定義當警告觸發時,哪些服務終端需要被告知
告警規則
SkyWalking 的發行版都會默認提供config/alarm-settings.yml
文件,裏面預先定義了一些常用的告警規則。如下:
- 過去3分鐘內服務平均響應時間超過1秒
- 服務成功率在過去2分鐘內低於80%
- 服務90%響應時間在過去3分鐘內低於1000毫秒
- 服務實例在過去2分鐘內的平均響應時間超過1秒
- 端點平均響應時間過去2分鐘超過1秒
這些預定義的告警規則,打開config/alarm-settings.yml
文件即可看到。其具體內容如下:
rules:
# Rule unique name, must be ended with `_rule`.
service_resp_time_rule:
metrics-name: service_resp_time
op: ">"
threshold: 1000
period: 10
count: 3
silence-period: 5
message: Response time of service {name} is more than 1000ms in 3 minutes of last 10 minutes.
service_sla_rule:
# Metrics value need to be long, double or int
metrics-name: service_sla
op: "<"
threshold: 8000
# The length of time to evaluate the metrics
period: 10
# How many times after the metrics match the condition, will trigger alarm
count: 2
# How many times of checks, the alarm keeps silence after alarm triggered, default as same as period.
silence-period: 3
message: Successful rate of service {name} is lower than 80% in 2 minutes of last 10 minutes
service_p90_sla_rule:
# Metrics value need to be long, double or int
metrics-name: service_p90
op: ">"
threshold: 1000
period: 10
count: 3
silence-period: 5
message: 90% response time of service {name} is more than 1000ms in 3 minutes of last 10 minutes
service_instance_resp_time_rule:
metrics-name: service_instance_resp_time
op: ">"
threshold: 1000
period: 10
count: 2
silence-period: 5
message: Response time of service instance {name} is more than 1000ms in 2 minutes of last 10 minutes
除此之外,官方還提供了一個config/alarm-settings-sample.yml
文件,該文件是一個告警規則的示例文件,裏面展示了目前支持的所有告警規則配置項:
# Sample alarm rules.
rules:
# Rule unique name, must be ended with `_rule`.
endpoint_percent_rule:
# Metrics value need to be long, double or int
metrics-name: endpoint_percent
threshold: 75
op: <
# The length of time to evaluate the metrics
period: 10
# How many times after the metrics match the condition, will trigger alarm
count: 3
# How many times of checks, the alarm keeps silence after alarm triggered, default as same as period.
silence-period: 10
message: Successful rate of endpoint {name} is lower than 75%
service_percent_rule:
metrics-name: service_percent
# [Optional] Default, match all services in this metrics
include-names:
- service_a
- service_b
exclude-names:
- service_c
threshold: 85
op: <
period: 10
count: 4
告警規則配置項的說明:
- Rule name:規則名稱,也是在告警信息中顯示的唯一名稱。必須以
_rule
結尾,前綴可自定義 - Metrics name:度量名稱,取值爲oal腳本中的度量名,目前只支持
long
、double
和int
類型。詳見Official OAL script - Include names:該規則作用於哪些實體名稱,比如服務名,終端名(可選,默認爲全部)
- Exclude names:該規則作不用於哪些實體名稱,比如服務名,終端名(可選,默認爲空)
- Threshold:閾值
- OP: 操作符,目前支持
>
、<
、=
- Period:多久告警規則需要被覈實一下。這是一個時間窗口,與後端部署環境時間相匹配
- Count:在一個Period窗口中,如果values超過Threshold值(按op),達到Count值,需要發送警報
- Silence period:在時間N中觸發報警後,在TN -> TN + period這個階段不告警。 默認情況下,它和Period一樣,這意味着相同的告警(在同一個Metrics name擁有相同的Id)在同一個Period內只會觸發一次
- message:告警消息
Webhook(網絡鉤子)
Webhook可以簡單理解爲是一種Web層面的回調機制,通常由一些事件觸發,與代碼中的事件回調類似,只不過是Web層面的。由於是Web層面的,所以當事件發生時,回調的不再是代碼中的方法或函數,而是服務接口。例如,在告警這個場景,告警就是一個事件。當該事件發生時,SkyWalking就會主動去調用一個配置好的接口,該接口就是所謂的Webhook。
SkyWalking的告警消息會通過 HTTP 請求進行發送,請求方法爲 POST
,Content-Type
爲 application/json
,其JSON 數據實基於List<org.apache.skywalking.oap.server.core.alarm.AlarmMessage
進行序列化的。JSON數據示例:
[{
"scopeId": 1,
"scope": "SERVICE",
"name": "serviceA",
"id0": 12,
"id1": 0,
"ruleName": "service_resp_time_rule",
"alarmMessage": "alarmMessage xxxx",
"startTime": 1560524171000
}, {
"scopeId": 1,
"scope": "SERVICE",
"name": "serviceB",
"id0": 23,
"id1": 0,
"ruleName": "service_resp_time_rule",
"alarmMessage": "alarmMessage yyy",
"startTime": 1560524171000
}]
字段說明:
- scopeId、scope:所有可用的 Scope 詳見
org.apache.skywalking.oap.server.core.source.DefaultScopeDefine
- name:目標 Scope 的實體名稱
- id0:Scope 實體的 ID
- id1:保留字段,目前暫未使用
- ruleName:告警規則名稱
- alarmMessage:告警消息內容
- startTime:告警時間,格式爲時間戳
郵件告警功能實踐
根據以上兩個小節的介紹,可以得知:SkyWalking是不支持直接向郵箱、短信等服務發送告警信息的,SkyWalking只會在發生告警時將告警信息發送至配置好的Webhook接口。
但我們總不能人工盯着該接口的日誌信息來得知服務是否發生了告警,因此我們需要在該接口裏實現發送郵件或短信等功能,從而達到個性化的告警通知。
接下來開始動手實踐,這裏基於Spring Boot進行實現。首先是添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置郵箱服務:
server:
port: 9134
#郵箱配置
spring:
mail:
host: smtp.163.com
#發送者郵箱賬號
username: 你的郵箱@163.com
#發送者密鑰
password: 你的郵箱服務密鑰
default-encoding: utf-8
port: 465 #端口號465或587
protocol: smtp
properties:
mail:
debug:
false
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
根據SkyWalking發送的JSON數據定義一個DTO,用於接口接收數據:
@Data
public class SwAlarmDTO {
private Integer scopeId;
private String scope;
private String name;
private Integer id0;
private Integer id1;
private String ruleName;
private String alarmMessage;
private Long startTime;
}
接着定義一個接口,實現接收SkyWalking的告警通知,並將數據發送至郵箱:
package com.example.alarmdemo.controller;
import com.example.alarmdemo.dto.SwAlarmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/alarm")
public class SwAlarmController {
private final JavaMailSender sender;
@Value("${spring.mail.username}")
private String from;
/**
* 接收skywalking服務的告警通知併發送至郵箱
*/
@PostMapping("/receive")
public void receive(@RequestBody List<SwAlarmDTO> alarmList) {
SimpleMailMessage message = new SimpleMailMessage();
// 發送者郵箱
message.setFrom(from);
// 接收者郵箱
message.setTo(from);
// 主題
message.setSubject("告警郵件");
String content = getContent(alarmList);
// 郵件內容
message.setText(content);
sender.send(message);
log.info("告警郵件已發送...");
}
private String getContent(List<SwAlarmDTO> alarmList) {
StringBuilder sb = new StringBuilder();
for (SwAlarmDTO dto : alarmList) {
sb.append("scopeId: ").append(dto.getScopeId())
.append("\nscope: ").append(dto.getScope())
.append("\n目標 Scope 的實體名稱: ").append(dto.getName())
.append("\nScope 實體的 ID: ").append(dto.getId0())
.append("\nid1: ").append(dto.getId1())
.append("\n告警規則名稱: ").append(dto.getRuleName())
.append("\n告警消息內容: ").append(dto.getAlarmMessage())
.append("\n告警時間: ").append(dto.getStartTime())
.append("\n\n---------------\n\n");
}
return sb.toString();
}
}
最後將該接口配置到SkyWalking中,Webhook的配置位於config/alarm-settings.yml
文件的末尾,格式爲http://{ip}:{port}/{uri}
。如下示例:
[root@localhost skywalking]# vim config/alarm-settings.yml
webhooks:
- http://127.0.0.1:9134/alarm/receive
測試告警功能
完成告警接口的開發及配置後,我們來進行一個簡單的測試。這裏有一條調用鏈路如下:
我在/producer
接口中增加了一行會導致異常的代碼,故意使該接口不可用:
@GetMapping
public String producer() {
log.info("received a request");
int i = 1 / 0;
return "this message from producer";
}
接下來編寫一段測試代碼,讓其服務成功率滿足在過去2分鐘內低於80%這條默認的告警規則:
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
for (int i = 0; i < 100; i++) {
String result = restTemplate.getForObject("http://127.0.0.1:8936/consumer", String.class);
log.info(result);
}
}
執行完測試代碼,等待約兩分鐘後,告警接口的控制檯輸出了一段日誌信息:
此時,郵箱正常收到了告警郵件: