Skip to content
This repository was archived by the owner on Apr 7, 2024. It is now read-only.

Commit 515b287

Browse files
Первая попытка модификации саммари (#14)
* Куча проблем * прикрепил аттачменты * gitignore * Delete .gitignore * asdf * fix config * рабочий ресивер * Vladimir EDITED * рабочая логика(почти) * добавил проверки на резолв, добавил очистку * добавил бесконечный цикл для очистки * Delete slack.tmpl * fix old mistakes * fix gorutine, islomal logic * поправил горутину, логику наполнения массива ТСок, переопределение значений алертов в сторадже * Внес небольшие правки в форматирование и поправил пару багов * add ci * add ci * add ci * почистил конфиг от лишних полей, добавил логику here * fix merge conflicts ci * удалил говнокод * подумать еще над here * ignore tempalte * пытаюсь в блоки * Add blocks * fix url encode * add mentions * fix mentions * дебаг на проде * добавил каст для старых алертов * add divider * удалил старый код * Первая попытка модификации саммари * небольшая косметика * Update summary merger * добавил обрезку длинны саммари до 500 строк Co-authored-by: Vladimir Buyanov <b.vladimir@clickadu.com>
1 parent 230e1ea commit 515b287

File tree

4 files changed

+92
-5
lines changed

4 files changed

+92
-5
lines changed

config/notifiers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ func (c *SlackConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
396396
type SlackConfigV2 struct {
397397
NotifierConfig `yaml:",inline" json:",inline"`
398398

399-
Token string `yaml:"token,omitempty" json:"token,omitempty"`
399+
Token Secret `yaml:"token,omitempty" json:"token,omitempty"`
400400
Channel string `yaml:"channel,omitempty" json:"channel,omitempty"`
401401
Color string `yaml:"color,omitempty" json:"color,omitempty"`
402402
Debug bool `yaml:"debug" json:"debug"`

notify/slackV2/blocks.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,12 +127,16 @@ func (n *Notifier) formatMessage(data *template.Data) slack.Blocks {
127127
if val := getMapValue(data.CommonAnnotations, "summary"); len(val) > 0 {
128128
block.Elements = append(block.Elements, &Element{Type: slack.MarkdownType, Text: fmt.Sprintf("*Summary:* %s", val)})
129129
} else {
130+
summary := make([]string, 0)
130131
for _, al := range data.Alerts {
131132
if val, ok := al.Annotations["summary"]; ok && len(val) > 0 {
132-
block.Elements = append(block.Elements, &Element{Type: slack.MarkdownType, Text: fmt.Sprintf("*Summary:* %s", val)})
133-
break
133+
summary = append(summary, val)
134134
}
135135
}
136+
summary = mergeSameMessages(summary)
137+
if len(summary) > 0 {
138+
block.Elements = append(block.Elements, &Element{Type: slack.MarkdownType, Text: fmt.Sprintf("*Summary:* %s", cut(strings.Join(summary, ";\n"), 500))})
139+
}
136140
}
137141

138142
if val := getMapValue(data.CommonAnnotations, "description"); len(val) > 0 {

notify/slackV2/slackV2.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ type Data struct {
4545

4646
// New returns a new Slack notification handler.
4747
func New(c *config.SlackConfigV2, t *template.Template, l log.Logger) (*Notifier, error) {
48-
token := c.Token
48+
token := string(c.Token)
4949
client := slack.New(token, slack.OptionDebug(c.Debug))
5050

5151
notifier := &Notifier{

notify/slackV2/utils.go

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
package slackV2
22

3-
import "github.com/prometheus/alertmanager/template"
3+
import (
4+
"github.com/prometheus/alertmanager/template"
5+
"unicode/utf8"
6+
)
7+
8+
const SummaryMessageDiffThreshold = 3
49

510
func UniqStr(input []string) []string {
611
u := make([]string, 0, len(input))
@@ -22,3 +27,81 @@ func getMapValue(data template.KV, key string) string {
2227
return ""
2328
}
2429
}
30+
31+
func levenshteinDistance(s1, s2 string) int {
32+
if len(s1) == 0 {
33+
return utf8.RuneCountInString(s2)
34+
} else if len(s2) == 0 {
35+
return utf8.RuneCountInString(s1)
36+
} else if s1 == s2 {
37+
return 0
38+
}
39+
40+
min := func(values ...int) int {
41+
m := values[0]
42+
for _, v := range values {
43+
if v < m {
44+
m = v
45+
}
46+
}
47+
return m
48+
}
49+
r1, r2 := []rune(s1), []rune(s2)
50+
n, m := len(r1), len(r2)
51+
if n > m {
52+
r1, r2 = r2, r1
53+
n, m = m, n
54+
}
55+
currentRow := make([]int, n+1)
56+
previousRow := make([]int, n+1)
57+
for i := range currentRow {
58+
currentRow[i] = i
59+
}
60+
for i := 1; i <= m; i++ {
61+
for j := range currentRow {
62+
previousRow[j] = currentRow[j]
63+
if j == 0 {
64+
currentRow[j] = i
65+
continue
66+
} else {
67+
currentRow[j] = 0
68+
}
69+
add, del, change := previousRow[j]+1, currentRow[j-1]+1, previousRow[j-1]
70+
if r1[j-1] != r2[i-1] {
71+
change++
72+
}
73+
currentRow[j] = min(add, del, change)
74+
}
75+
}
76+
return currentRow[n]
77+
}
78+
79+
func mergeSameMessages(arr []string) []string {
80+
result := make([]string, 0)
81+
if len(arr) > 0 {
82+
result = append(result, arr[0])
83+
}
84+
85+
for _, val := range arr {
86+
differs := 0
87+
for _, res := range result {
88+
if levenshteinDistance(val, res) > SummaryMessageDiffThreshold {
89+
differs++
90+
}
91+
}
92+
if differs == len(result) {
93+
result = append(result, val)
94+
}
95+
}
96+
97+
result = UniqStr(result)
98+
return result
99+
}
100+
101+
func cut(text string, limit int) string {
102+
runes := []rune(text)
103+
if len(runes) >= limit {
104+
return string(runes[:limit])
105+
}
106+
return text
107+
}

0 commit comments

Comments
 (0)