-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathalerts.go
76 lines (60 loc) · 1.76 KB
/
alerts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package client
import (
"context"
"io"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
const alertmanagerAPIPath = "/api/v1/alerts"
type configCompat struct {
TemplateFiles map[string]string `yaml:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config"`
}
// CreateAlertmanagerConfig creates a new alertmanager config
func (r *LokiClient) CreateAlertmanagerConfig(ctx context.Context, cfg string, templates map[string]string) error {
payload, err := yaml.Marshal(&configCompat{
TemplateFiles: templates,
AlertmanagerConfig: cfg,
})
if err != nil {
return err
}
res, err := r.doRequest(ctx, alertmanagerAPIPath, "POST", payload)
if err != nil {
return err
}
res.Body.Close()
return nil
}
// DeleteAlermanagerConfig deletes the users alertmanagerconfig
func (r *LokiClient) DeleteAlermanagerConfig(ctx context.Context) error {
res, err := r.doRequest(ctx, alertmanagerAPIPath, "DELETE", nil)
if err != nil {
return err
}
res.Body.Close()
return nil
}
// GetAlertmanagerConfig retrieves a rule group
func (r *LokiClient) GetAlertmanagerConfig(ctx context.Context) (string, map[string]string, error) {
res, err := r.doRequest(ctx, alertmanagerAPIPath, "GET", nil)
if err != nil {
log.Debugln("no alert config present in response")
return "", nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return "", nil, err
}
compat := configCompat{}
err = yaml.Unmarshal(body, &compat)
if err != nil {
log.WithFields(log.Fields{
"body": string(body),
}).Debugln("failed to unmarshal rule group from response")
return "", nil, errors.Wrap(err, "unable to unmarshal response")
}
return compat.AlertmanagerConfig, compat.TemplateFiles, nil
}