/
silence.go
71 lines (55 loc) · 1.56 KB
/
silence.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
package nagiosapi
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/synyx/tuwat/pkg/connectors"
"github.com/synyx/tuwat/pkg/version"
)
func (c *Connector) createSilencer(alert connectors.Alert) connectors.SilencerFunc {
return func(ctx context.Context, duration time.Duration, user string) error {
return c.Silence(ctx, alert, duration, user)
}
}
func (c *Connector) Silence(ctx context.Context, alert connectors.Alert, duration time.Duration, user string) error {
payload := map[string]interface{}{
"host": alert.Labels["Hostname"],
"service": alert.Description,
"comment": fmt.Sprintf("%s: silenced via %s", user, version.Info.Application),
"author": user,
"expire": duration / time.Minute,
}
endpoint := "/acknowledge_problem"
err := c.post(ctx, endpoint, payload)
return err
}
func (c *Connector) post(ctx context.Context, endpoint string, content map[string]interface{}) error {
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
if err := encoder.Encode(content); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.config.URL+endpoint, buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var response response
err = decoder.Decode(&response)
if err != nil {
return err
}
if !response.Success {
// TODO(jo): the `content` map is overloaded with an error string
}
return nil
}