-
Notifications
You must be signed in to change notification settings - Fork 0
/
alerts.go
115 lines (92 loc) · 2.34 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/function61/gokit/ezhttp"
"github.com/function61/gokit/osutil"
"github.com/function61/james/pkg/jamestypes"
"github.com/scylladb/termtables"
"github.com/spf13/cobra"
)
func alertsList(jamesfile jamestypes.Jamesfile) error {
ctx, cancel := context.WithTimeout(context.TODO(), ezhttp.DefaultTimeout10s)
defer cancel()
alerts := GetAlertsResponse{}
if _, err := ezhttp.Get(
ctx,
jamesfile.AlertManagerEndpoint+"/alerts",
ezhttp.RespondsJson(&alerts, true),
); err != nil {
return err
}
if len(alerts) == 0 {
return nil
}
tbl := termtables.CreateTable()
tbl.AddHeaders("Key", "Time", "Subject", "Details")
for _, alert := range alerts {
tbl.AddRow(
alert.Key,
alert.Timestamp.Format(time.RFC3339),
alert.Subject,
truncate(onelinerize(alert.Details), 96))
}
fmt.Println(tbl.Render())
return nil
}
func alertsAck(key string, jamesfile jamestypes.Jamesfile) error {
ackRequest := &AcknowledgeAlertRequest{
Key: key,
}
ctx, cancel := context.WithTimeout(context.TODO(), ezhttp.DefaultTimeout10s)
defer cancel()
_, err := ezhttp.Post(
ctx,
jamesfile.AlertManagerEndpoint+"/alerts/acknowledge",
ezhttp.SendJson(ackRequest))
return err
}
func alertEntry() *cobra.Command {
cmd := &cobra.Command{
Use: "alerts",
Short: "List firing alerts",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
jamesfile, err := readJamesfile()
osutil.ExitIfError(err)
osutil.ExitIfError(alertsList(jamesfile.File))
},
}
cmd.AddCommand(&cobra.Command{
Use: "ack [key]",
Short: "Acknowledge an alert",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
jamesfile, err := readJamesfile()
osutil.ExitIfError(err)
osutil.ExitIfError(alertsAck(args[0], jamesfile.File))
},
})
return cmd
}
type AlertItem struct {
Key string `json:"alert_key"`
Subject string `json:"subject"`
Details string `json:"details"`
Timestamp time.Time `json:"timestamp"`
}
type GetAlertsResponse []AlertItem
type AcknowledgeAlertRequest struct {
Key string `json:"alert_key"`
}
func truncate(input string, maxLen int) string {
if len(input) > maxLen {
return input[0:maxLen-2] + ".."
}
return input
}
func onelinerize(input string) string {
return strings.Replace(input, "\n", "\\n", -1)
}