-
Notifications
You must be signed in to change notification settings - Fork 27
/
http.go
187 lines (156 loc) · 5.82 KB
/
http.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2024 Datadog, Inc.
package datadog
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/mail"
"os"
"path/filepath"
"strings"
"time"
"github.com/DataDog/chaos-controller/api/v1beta1"
"github.com/DataDog/chaos-controller/eventnotifier/types"
"github.com/DataDog/chaos-controller/eventnotifier/utils"
"github.com/google/jsonapi"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
)
type NotifierHTTPConfig struct {
Enabled bool
URL string
Headers []string
HeadersFilepath string
}
// Notifier describes a HTTP notifier
type Notifier struct {
common types.NotifiersCommonConfig
client *http.Client
url string
headers map[string]string
logger *zap.SugaredLogger
}
type HTTPNotifierEvent struct {
ID string `jsonapi:"primary,http_notifier_events"`
NotificationTitle string `jsonapi:"attr,notification_title"`
NotificationType types.NotificationType `jsonapi:"attr,notification_type"`
EventMessage string `jsonapi:"attr,event_message"`
InvolvedObjectKind string `jsonapi:"attr,involved_object_kind"`
DisruptionName string `jsonapi:"attr,disruption_name"`
Disruption string `jsonapi:"attr,disruption"`
Timestamp int64 `jsonapi:"attr,timestamp"`
Cluster string `jsonapi:"attr,cluster"`
Namespace string `jsonapi:"attr,namespace"`
TargetsCount int `jsonapi:"attr,targets_count"`
Username string `jsonapi:"attr,username,omitempty"`
UserEmail string `jsonapi:"attr,user_email,omitempty"`
}
// New HTTP Notifier
func New(commonConfig types.NotifiersCommonConfig, httpConfig NotifierHTTPConfig, logger *zap.SugaredLogger) (*Notifier, error) {
parsedHeaders := make(map[string]string)
headers := []string{}
client := &http.Client{
Timeout: 30 * time.Second,
}
if httpConfig.URL == "" {
return nil, fmt.Errorf("notifier http: missing URL")
}
if httpConfig.HeadersFilepath != "" {
headersFile, err := os.Open(filepath.Clean(httpConfig.HeadersFilepath))
if err != nil {
return nil, fmt.Errorf("headers file not found: %w", err)
}
readHeaders, err := io.ReadAll(headersFile)
if err != nil {
return nil, fmt.Errorf("headers file could not be read: %w", err)
}
sHeaders := string(readHeaders)
if sHeaders != "" {
headers = strings.Split(sHeaders, "\n")
}
}
headers = append(headers, httpConfig.Headers...)
for _, header := range headers {
if header == "" {
continue
}
splittedHeader := strings.Split(header, ":")
if len(splittedHeader) == 2 {
parsedHeaders[splittedHeader[0]] = splittedHeader[1]
} else {
return nil, fmt.Errorf("notifier http: invalid headers in headers file. Must be of format: key:value")
}
}
return &Notifier{
common: commonConfig,
client: client,
url: httpConfig.URL,
headers: parsedHeaders,
logger: logger,
}, nil
}
// GetNotifierName returns the driver's name
func (n *Notifier) GetNotifierName() string {
return string(types.NotifierDriverHTTP)
}
// Notify generates a notification for generic k8s Warning events
func (n *Notifier) Notify(dis v1beta1.Disruption, event corev1.Event, notifType types.NotificationType) error {
emailAddr := &mail.Address{}
if userInfo, err := dis.UserInfo(); err != nil {
n.logger.Warnw("http notifier: no user info in disruption", "disruptionName", dis.Name, "disruptionNamespace", dis.Namespace, "error", err)
} else {
if userInfoEmailAddr, err := mail.ParseAddress(userInfo.Username); err != nil {
n.logger.Warnw("http notifier: user info username is not a valid email address", "disruptionName", dis.Name, "disruptionNamespace", dis.Namespace, "error", err, "username", userInfo.Username)
} else {
emailAddr = userInfoEmailAddr
}
}
disruptionStr, err := json.Marshal(dis)
if err != nil {
return fmt.Errorf("http notifier: couldn't send notification: %w", err)
}
now := time.Now()
notif := HTTPNotifierEvent{
ID: string(dis.UID),
NotificationTitle: utils.BuildHeaderMessageFromDisruptionEvent(dis, notifType),
NotificationType: notifType,
EventMessage: utils.BuildBodyMessageFromDisruptionEvent(dis, event, false),
InvolvedObjectKind: dis.Kind,
DisruptionName: dis.Name,
Disruption: string(disruptionStr),
Cluster: n.common.ClusterName,
Namespace: dis.Namespace,
TargetsCount: len(dis.Status.TargetInjections),
Username: emailAddr.Name,
UserEmail: emailAddr.Address,
Timestamp: now.UnixNano(),
}
body := bytes.NewBuffer(nil)
if err := jsonapi.MarshalOnePayloadEmbedded(body, ¬if); err != nil {
return fmt.Errorf("http notifier: couldn't marshal notification: %w", err)
}
req, err := http.NewRequest(http.MethodPost, n.url, body)
if err != nil {
return fmt.Errorf("http notifier: couldn't send notification: %w", err)
}
for headerKey, headerValue := range n.headers {
req.Header.Add(headerKey, headerValue)
}
res, err := n.client.Do(req)
if err != nil {
return fmt.Errorf("http notifier: error when sending notification: %w", err)
}
n.logger.Debugw("notifier: sending notifier event to http", "disruption", dis.Name, "eventType", event.Type, "message", notif.EventMessage)
if res.StatusCode >= 300 || res.StatusCode < 200 {
return fmt.Errorf("http notifier: receiving %d status code from sent notification", res.StatusCode)
}
if err = res.Body.Close(); err != nil {
return fmt.Errorf("http notifier: error when sending notification: %w", err)
}
return nil
}