Quando as regras de alerta em uma política de notificação são acionadas, o ARMS envia notificações por DingTalk, Lark, WeCom, SMS, chamada telefônica, e-mail ou webhook. Cada canal possui um modelo predefinido que você pode personalizar usando a sintaxe de Go template.
Esta página aborda os modelos predefinidos para cada canal, as variáveis de modelo disponíveis e a sintaxe de Go template para criar modelos personalizados.
Modelos de notificação predefinidos
O ARMS fornece um modelo predefinido para cada canal de notificação. Cada modelo renderiza os dados do alerta em uma mensagem legível usando a sintaxe de Go template.
Alert name: {{ .commonLabels.alertname }}
{{if .commonLabels.clustername }}
Cluster name: {{ .commonLabels.clustername }}
{{ end }}
{{if eq "app" .commonLabels._aliyun_arms_involvedObject_kind }}
Application name: {{ .commonLabels._aliyun_arms_involvedObject_name }}
{{ end }}
Notification policy: {{ .dispatchRuleName }}
Alert triggered at: {{ .startTime }}
Alert content: {{ if .newIncidentIn }} (New event) {{ end }} {{ for .alerts }} {{.annotations.message}} {{ if .generatorURL }} <a href="{{.generatorURL}}" >Details URL</a> {{end}} {{end}}
A tabela a seguir explica cada seção do modelo.
|
Seção do modelo |
Descrição |
|
|
Nome do alerta. Por padrão, as políticas de notificação agrupam alertas por |
|
|
Renderiza o nome do cluster apenas se o rótulo |
|
|
Exibe o nome da aplicação somente quando o tipo de objeto do alerta for |
|
|
Nome da política de notificação que correspondeu ao alerta. |
|
|
Horário em que o alerta foi acionado. |
|
|
Marca a notificação com |
|
|
Itera sobre todos os eventos de alerta e renderiza cada anotação |
Exemplo de saída:
Alert name: The memory usage of the container has exceeded 80%.
Cluster name: klyz1688-kubernetes-1
Notification policy: Notification policy name
Alert triggered at: 2023-02-22 07:18:15
Alert content: Namespace: arms-prom / Pod: kube-state-metrics-ccb59dbff-jljg4 / Container: kube-state-metrics. The memory usage of the container has exceeded 80%. Current value: 15.52%.
SMS e chamada telefônica
Os modelos de SMS e chamada telefônica compartilham a mesma estrutura do modelo de e-mail, mas omitem a URL de detalhes.
{{ .level }} alert occurred
Alert name: {{ .commonLabels.alertname }}
{{if .commonLabels.clustername }}
Cluster name: {{ .commonLabels.clustername }}
{{ end }}
{{if eq "app" .commonLabels._aliyun_arms_involvedObject_kind }}
Application name: {{ .commonLabels._aliyun_arms_involvedObject_name }}
{{ end }}
Notification policy: {{ .dispatchRuleName }}
Alert triggered at: {{ .startTime }}
Alert content: {{ if .newIncidentIn }} (New event)
{{end}} {{ for .alerts }} {{ .annotations.message }} {{ end }}
Chatbot (DingTalk, Lark, WeCom)
O modelo de chatbot gera saída em Markdown. O suporte à formatação varia conforme a plataforma.
{{ if .newIncidentIn }} (New event) {{end}}
{{if .commonLabels.clustername }}
> Cluster name: {{ .commonLabels.clustername }}
{{ end }}
{{if eq "app" .commonLabels._aliyun_arms_involvedObject_kind }}
> Application name: {{ .commonLabels._aliyun_arms_involvedObject_name }}
{{ end }}
{{ for .alerts }} > {{ .annotations.message }} {{if .generatorURL }} [Details URL]({{.generatorURL}}) {{end}}{{if .annotations._aliyun_arms_insights_analyze_link }}[<font color='#ff0000'>Root cause</font>]({{ .annotations._aliyun_arms_insights_analyze_link}}){{ end }}{{if eq "1" .labels._aliyun_arms_denoise_code }} (Important: {{.labels._aliyun_arms_important_reason }}) {{end}}
{{end}}
Suporte a Markdown no chatbot:
|
Recurso |
Sintaxe |
Suporte por plataforma |
|
Citação em bloco |
|
DingTalk, Lark, WeCom |
|
Cor da fonte |
|
Apenas DingTalk e WeCom. O Lark não suporta cores de fonte. |
|
Quebra de linha |
Pressione Enter duas vezes no modelo |
Apenas DingTalk |
|
Quebra de linha |
Pressione Enter uma vez no modelo |
Lark, WeCom |
Webhook
{
"Alert name":"{{ .commonLabels.alertname }}
{{if .commonLabels.clustername }}", "Cluster name":"{{ .commonLabels.clustername }} {{ end }}
{{if eq "app" .commonLabels._aliyun_arms_involvedObject_kind }}", "Application name":"{{ .commonLabels._aliyun_arms_involvedObject_name }} {{ end }}",
"Notification Policy":"{{ .dispatchRuleName }}",
"Alert triggered at":"{{ .startTime }}",
"Alert content":"{{ for .alerts }} {{ .annotations.message }} {{ end }}"
}
Exemplo de saída:
{
"Alert name": "The memory usage of the container has exceeded 80%.",
"Cluster name": "klyz1688-kubernetes-1",
"Notification policy": "Notification policy name",
"Alert triggered at": "2023-02-22 07:18:15",
"Alert content": "Namespace: arms-prom / Pod: kube-state-metrics-ccb59dbff-jljg4 / Container: kube-state-metrics. The memory usage of the container has exceeded 80%. Current value: 15.52%."
}
Variáveis de modelo
Estas variáveis estão disponíveis nos modelos de notificação para renderizar dados de alerta.
|
Variável |
Tipo |
Descrição |
|
|
String |
ID do alerta original. |
|
|
List |
Lista de eventos de alerta originais neste grupo. |
|
|
Map |
Anotações do alerta original. |
|
|
Timestamp |
Horário em que o alerta foi limpo. Equivale ao horário de acionamento mais o período de limpeza. |
|
|
Timestamp |
Horário em que o alerta foi acionado. |
|
|
String |
Impressão digital do alerta. Alertas com o mesmo conjunto de rótulos compartilham a mesma impressão digital. |
|
|
Map |
Rótulos do alerta original. |
|
|
String |
Status do alerta. Valores válidos: |
|
|
Map |
Anotações compartilhadas por todos os alertas do grupo. |
|
|
Map |
Rótulos compartilhados por todos os alertas do grupo. |
|
|
Map |
Rótulos usados para agrupar alertas, conforme definido na condição de grupo da política de notificação. |
|
|
String |
Status do grupo de alertas. Valores válidos: |
|
|
String |
Horário de criação do grupo de alertas. |
|
|
String |
Horário em que o grupo de alertas foi limpo. Corresponde ao momento em que o último alerta do grupo foi resolvido. |
|
|
String |
Nível de severidade. Valores válidos: |
|
|
String |
Nome da política de notificação que correspondeu a este grupo de alertas. |
Os parâmetros de alerta consistem em múltiplos rótulos. Use rótulos para referenciar dados específicos do alerta em seus modelos. Por exemplo, .commonLabels.alertname retorna o nome do alerta.
Exemplo de contexto de alerta
O JSON a seguir mostra o contexto completo de alerta referenciado por todos os exemplos na seção Sintaxe de Go template.
{
"alerts": [
{
"annotations": {
"message": "Namespace: arms-prom / Pod: kube-state-metrics-ccb59dbff-jljg4 / Container: kube-state-metrics. The memory usage of the container has exceeded 80%. Current value: 15.52%.",
"value": "15.521240234375"
},
"endsAt": "2023-02-22T07:27:15.404000000Z",
"fingerprint": "bec72890cc2c7b4a027e008df0cd1013",
"labels": {
"container": "kube-state-metrics",
"severity": "warning",
"instance": "10.0.80.186:10255",
"clustername": "klyz1688-kubernetes-1",
"alertname": "The memory usage of the container has exceeded 80%.",
"_aliyun_arms_involvedObject_name": "klyz1688-kubernetes-1",
"pod_name": "kube-state-metrics-ccb59dbff-jljg4",
"_aliyun_arms_involvedObject_kind": "cluster",
"name": "k8s_kube-state-metrics_kube-state-metrics-ccb59dbff-jljg4_arms-prom_359508f3-7e76-4740-b915-41ea48849641_0",
"namespace": "arms-prom"
},
"startsAt": "2023-02-22T07:18:15.578000000Z",
"status": "firing"
}
],
"commonAnnotations": {
"message": "Namespace: arms-prom / Pod: kube-state-metrics-ccb59dbff-jljg4 / Container: kube-state-metrics. The memory usage of the container has exceeded 80%. Current value: 15.52%.",
"value": "15.521240234375"
},
"commonLabels": {
"container": "kube-state-metrics",
"severity": "warning",
"instance": "10.0.80.186:10255",
"clustername": "klyz1688-kubernetes-1",
"alertname": "The memory usage of the container has exceeded 80%.",
"_aliyun_arms_involvedObject_name": "klyz1688-kubernetes-1",
"pod_name": "kube-state-metrics-ccb59dbff-jljg4",
"_aliyun_arms_involvedObject_kind": "cluster",
"name": "k8s_kube-state-metrics_kube-state-metrics-ccb59dbff-jljg4_arms-prom_359508f3-7e76-4740-b915-41ea48849641_0",
"namespace": "arms-prom"
},
"groupLabels": {
"alertname": "The memory usage of the container has exceeded 80%."
},
"status": "firing",
"startTime": "2023-02-22 07:18:15",
"endTime": "The time when the alert was cleared",
"level": "error",
"dispatchRuleName": "Notification policy name",
"alarmId": "123456"
}
Sintaxe de Go template
O ARMS utiliza a sintaxe de Go template para renderizar modelos de notificação. No momento da renderização, o modelo é preenchido com dados do contexto de alerta.
Notação de ponto
O ponto (.) representa o escopo atual do contexto.
Acessar todo o contexto:
{{ . }}
Saída: Retorna todos os dados no contexto de alerta.
Acessar um campo de nível superior:
{{ .level }}
Saída:
error
Acessar um campo aninhado:
{{ .commonLabels.alertname }}
Saída:
The memory usage of the container has exceeded 80%.
Variáveis
Armazene dados de contexto em variáveis para reutilização.
Defina um campo a uma variável:
{{ $alertname := .commonLabels.alertname }} {{$alertname}}
Saída:
The memory usage of the container has exceeded 80%.
Acessar um elemento de array através de uma variável:
{{ $alert0 := index .alerts 0 }} {{$alert0.labels.alertname}}
Saída:
The memory usage of the container has exceeded 80%.
Condicionais: if/else
Verifique valores com if. A condição é avaliada como false para valores nulos, 0, ponteiros nil, strings vazias e strings de comprimento zero.
Condição simples:
{{if eq "warning" .commonLabels.severity }} P3 alert {{ end }}
Saída:
P3 alert
if/else:
{{if eq "critical" .commonLabels.severity }} P1 alert {{ else }} P2 alert {{ end }}
Saída:
P2 alert
Loops: for
Itere sobre uma lista.
Percorrer alertas e obter o nome de cada alerta:
{{ for .alerts}} {{.labels.alertname}} \n {{end}}
Saída:
The memory usage of the container has exceeded 80%.
Loops: range
Percorra uma sequência de valores.
Iterar sobre inteiros de 0 a 9:
{{ $ran := range 0 10 }} {{ for $ran }} {{.}} {{end}}
Saída:
0 1 2 3 4 5 6 7 8 9
A função index
Recupere um elemento específico de um array pelo índice.
Obter o primeiro evento de alerta:
{{ $alert0 := index .alerts 0 }} {{$alert0.labels.alertname}}
Saída:
The memory usage of the container has exceeded 80%.
Funções de comparação
|
Função |
Descrição |
|
|
Igual a |
|
|
Diferente de |
|
|
Menor que |
|
|
Menor ou igual a |
|
|
Maior que |
|
|
Maior ou igual a |
Exemplo:
{{if eq "warning" .commonLabels.severity }} P3 alert {{ end }}
Saída:
P3 alert
Operadores lógicos: and, or, not
Combine condições com operadores lógicos.
Exemplo:
{{if eq "warning" .commonLabels.severity or eq "warning" .commonLabels.severity }} P3 alert {{ end }}
Saída:
P3 alert
Funções integradas
printf
Formate dados de saída.
Arredondar para duas casas decimais:
{{ $alert0 := index .alerts 0 }} {{ printf "%.2f" $alert0.annotations.value }}
Saída:
15.52
humanizePercentage
Converta uma string decimal em uma porcentagem legível.
Exemplo:
{{ "0.95332123123124" | humanizePercentage }}
Saída:
95.33%
humanizeDate
Converta um timestamp em milissegundos para uma data formatada. Formato padrão: yyyy-MM-dd HH:mm:ss.
Exemplo:
{{ "1671074058234" | humanizeDate }}
Saída:
2022-12-15 11:14:18
len
Retorne o comprimento de um array.
Exemplo:
{{ len .alerts }}
Saída:
1