This repository has been archived by the owner on Jun 21, 2022. It is now read-only.
/
channel_helpers.go
374 lines (307 loc) · 9.11 KB
/
channel_helpers.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// pmm-managed
// Copyright (C) 2017 Percona LLC
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package models
import (
"fmt"
"strings"
"github.com/google/uuid"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/reform.v1"
)
var invalidConfigurationError = status.Error(codes.InvalidArgument, "Channel should contain only one type of channel configuration.")
func checkUniqueChannelID(q *reform.Querier, id string) error {
if id == "" {
panic("empty Channel ID")
}
agent := &Channel{ID: id}
switch err := q.Reload(agent); err {
case nil:
return status.Errorf(codes.AlreadyExists, "Channel with ID %q already exists.", id)
case reform.ErrNoRows:
return nil
default:
return errors.WithStack(err)
}
}
func checkEmailConfig(c *EmailConfig) error {
if c == nil {
return status.Error(codes.InvalidArgument, "Email config is empty.")
}
if len(c.To) == 0 {
return status.Error(codes.InvalidArgument, "Email to field is empty.")
}
return nil
}
func checkPagerDutyConfig(c *PagerDutyConfig) error {
if c == nil {
return status.Error(codes.InvalidArgument, "Pager duty config is empty.")
}
if (c.RoutingKey == "" && c.ServiceKey == "") || (c.RoutingKey != "" && c.ServiceKey != "") {
return status.Error(codes.InvalidArgument, "Exactly one key should be present in pager duty configuration.")
}
return nil
}
func checkSlackConfig(c *SlackConfig) error {
if c == nil {
return status.Error(codes.InvalidArgument, "Slack config is empty.")
}
if c.Channel == "" {
return status.Error(codes.InvalidArgument, "Slack channel field is empty.")
}
return nil
}
func checkWebHookConfig(c *WebHookConfig) error {
if c == nil {
return status.Error(codes.InvalidArgument, "Webhook config is empty.")
}
if c.URL == "" {
return status.Error(codes.InvalidArgument, "Webhook url field is empty.")
}
return nil
}
// FindChannels returns saved notification channels configuration.
func FindChannels(q *reform.Querier) ([]*Channel, error) {
rows, err := q.SelectAllFrom(ChannelTable, "")
if err != nil {
return nil, errors.Wrap(err, "failed to select notification channels")
}
channels := make([]*Channel, len(rows))
for i, s := range rows {
channels[i] = s.(*Channel)
}
return channels, nil
}
// FindChannelsOnPage returns a page with saved notification channels.
func FindChannelsOnPage(q *reform.Querier, pageIndex, pageSize int) ([]*Channel, error) {
rows, err := q.SelectAllFrom(ChannelTable, "ORDER BY id LIMIT $1 OFFSET $2", pageSize, pageIndex*pageSize)
if err != nil {
return nil, errors.Wrap(err, "failed to select notification channels")
}
channels := make([]*Channel, len(rows))
for i, s := range rows {
channels[i] = s.(*Channel)
}
return channels, nil
}
// CountChannels returns number of notification channels.
func CountChannels(q *reform.Querier) (int, error) {
count, err := q.Count(ChannelTable, "")
if err != nil {
return 0, errors.Wrap(err, "failed to count notification channels")
}
return count, nil
}
// FindChannelByID finds Channel by ID.
func FindChannelByID(q *reform.Querier, id string) (*Channel, error) {
if id == "" {
return nil, status.Error(codes.InvalidArgument, "Empty Channel ID.")
}
channel := &Channel{ID: id}
switch err := q.Reload(channel); err {
case nil:
return channel, nil
case reform.ErrNoRows:
return nil, status.Errorf(codes.NotFound, "Channel with ID %q not found.", id)
default:
return nil, errors.WithStack(err)
}
}
// FindChannelsByIDs finds channels by IDs.
func FindChannelsByIDs(q *reform.Querier, ids []string) ([]*Channel, error) {
if len(ids) == 0 {
return []*Channel{}, nil
}
p := strings.Join(q.Placeholders(1, len(ids)), ", ")
tail := fmt.Sprintf("WHERE id IN (%s) ORDER BY id", p) //nolint:gosec
args := make([]interface{}, len(ids))
for i, id := range ids {
args[i] = id
}
structs, err := q.SelectAllFrom(ChannelTable, tail, args...)
if err != nil {
return nil, errors.WithStack(err)
}
res := make([]*Channel, len(structs))
for i, s := range structs {
res[i] = s.(*Channel)
}
return res, nil
}
// CreateChannelParams are params for creating new channel.
type CreateChannelParams struct {
Summary string
EmailConfig *EmailConfig
PagerDutyConfig *PagerDutyConfig
SlackConfig *SlackConfig
WebHookConfig *WebHookConfig
Disabled bool
}
// CreateChannel persists notification channel.
func CreateChannel(q *reform.Querier, params *CreateChannelParams) (*Channel, error) {
id := "/channel_id/" + uuid.New().String()
if err := checkUniqueChannelID(q, id); err != nil {
return nil, err
}
if params.Summary == "" {
return nil, status.Error(codes.InvalidArgument, "Channel summary can't be empty.")
}
row := &Channel{
ID: id,
Summary: params.Summary,
Disabled: params.Disabled,
}
if params.EmailConfig != nil {
if err := checkEmailConfig(params.EmailConfig); err != nil {
return nil, err
}
row.Type = Email
row.EmailConfig = params.EmailConfig
}
if params.PagerDutyConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkPagerDutyConfig(params.PagerDutyConfig); err != nil {
return nil, err
}
row.Type = PagerDuty
row.PagerDutyConfig = params.PagerDutyConfig
}
if params.SlackConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkSlackConfig(params.SlackConfig); err != nil {
return nil, err
}
row.Type = Slack
row.SlackConfig = params.SlackConfig
}
if params.WebHookConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkWebHookConfig(params.WebHookConfig); err != nil {
return nil, err
}
row.Type = WebHook
row.WebHookConfig = params.WebHookConfig
}
if row.Type == "" {
return nil, status.Error(codes.InvalidArgument, "Missing channel configuration.")
}
if err := q.Insert(row); err != nil {
return nil, errors.Wrap(err, "failed to create notifications channel")
}
return row, nil
}
// ChangeChannelParams is params for changing existing channel.
type ChangeChannelParams struct {
Summary string
EmailConfig *EmailConfig
PagerDutyConfig *PagerDutyConfig
SlackConfig *SlackConfig
WebHookConfig *WebHookConfig
Disabled bool
}
// ChangeChannel updates existing notifications channel.
func ChangeChannel(q *reform.Querier, channelID string, params *ChangeChannelParams) (*Channel, error) {
row, err := FindChannelByID(q, channelID)
if err != nil {
return nil, err
}
// remove previous configuration
row.Type = ""
row.EmailConfig = nil
row.PagerDutyConfig = nil
row.SlackConfig = nil
row.WebHookConfig = nil
if params.Summary != "" {
row.Summary = params.Summary
}
if params.EmailConfig != nil {
if err := checkEmailConfig(params.EmailConfig); err != nil {
return nil, err
}
row.Type = Email
row.EmailConfig = params.EmailConfig
}
if params.PagerDutyConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkPagerDutyConfig(params.PagerDutyConfig); err != nil {
return nil, err
}
row.Type = PagerDuty
row.PagerDutyConfig = params.PagerDutyConfig
}
if params.SlackConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkSlackConfig(params.SlackConfig); err != nil {
return nil, err
}
row.Type = Slack
row.SlackConfig = params.SlackConfig
}
if params.WebHookConfig != nil {
if row.Type != "" {
return nil, invalidConfigurationError
}
if err := checkWebHookConfig(params.WebHookConfig); err != nil {
return nil, err
}
row.Type = WebHook
row.WebHookConfig = params.WebHookConfig
}
row.Disabled = params.Disabled
if err = q.Update(row); err != nil {
return nil, errors.Wrap(err, "failed to update notifications channel")
}
return row, nil
}
// RemoveChannel removes notification channel with specified id.
func RemoveChannel(q *reform.Querier, id string) error {
if _, err := FindChannelByID(q, id); err != nil {
return err
}
inUse, err := channelInUse(q, id)
if err != nil {
return err
}
if inUse {
return status.Errorf(codes.FailedPrecondition, "Failed to delete notification channel %s, as it is being used by some rule.", id)
}
if err = q.Delete(&Channel{ID: id}); err != nil {
return errors.Wrap(err, "failed to delete notification channel")
}
return nil
}
func channelInUse(q *reform.Querier, id string) (bool, error) {
_, err := q.SelectOneFrom(RuleTable, "WHERE channel_ids ? $1", id)
switch err {
case nil:
return true, nil
case reform.ErrNoRows:
return false, nil
default:
return false, errors.WithStack(err)
}
}