forked from openshift/pagerduty-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_mock.go
562 lines (501 loc) · 15.3 KB
/
service_mock.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// This contains a minimal mock PagerDuty API for testing this package in
// ways that the GoMock version in mock_service.go.
// TODO: Build out this minimal mock so that the pagerdutyintegration package
// can utilize this instead of the GoMock variant as well.
package pagerduty
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
pd "github.com/PagerDuty/go-pagerduty"
"github.com/jmleddy/pagerduty-operator/pkg/utils"
)
const (
mockAlertId string = "ALT1"
mockAlertId2 string = "ALT2"
mockEscalationPolicyId string = "ESC1"
mockEscalationPolicyId2 string = "ESC2"
mockIncidentId string = "INC1"
mockIncidentId2 string = "INC2"
mockIntegrationId string = "INT1"
mockIntegrationId2 string = "INT2"
mockIntegrationId3 string = "INT3"
mockIntegrationKey string = "KEY1"
mockIntegrationKey2 string = "KEY2"
mockIntegrationKey3 string = "KEY3"
mockServiceId string = "SVC1"
mockServiceId2 string = "SVC2"
mockServicePrefix string = "servicePrefix"
mockClusterId string = "clusterID"
mockClusterId2 string = "clusterID2"
mockBaseDomain string = "baseDomain"
mockServiceName string = mockServicePrefix + "-" + mockClusterId + "." + mockBaseDomain + "-hive-cluster"
)
type mockApi struct {
Client *mockClient
State *mockState
mux *http.ServeMux
server *httptest.Server
}
type mockState struct {
Alerts map[string][]*pd.IncidentAlert
EscalationPolicies map[string]*pd.EscalationPolicy
Incidents []*pd.Incident
Integrations []*pd.Integration
Services map[string]*pd.Service
}
type mockClient struct {
SvcClient
}
// defaultMockPagerdutyState returns a default mock state that's interesting for this operator
func defaultMockPagerdutyState() *mockState {
return &mockState{
Alerts: map[string][]*pd.IncidentAlert{
mockIncidentId: {
{
APIObject: pd.APIObject{ID: mockAlertId},
Status: "triggered",
Service: pd.APIObject{ID: mockServiceId},
Incident: pd.APIReference{ID: mockIncidentId},
Integration: pd.APIObject{ID: mockIntegrationId},
},
},
mockIncidentId2: {
{
APIObject: pd.APIObject{ID: mockAlertId2},
Status: "resolved",
Service: pd.APIObject{ID: mockServiceId},
Incident: pd.APIReference{ID: mockIncidentId2},
Integration: pd.APIObject{ID: mockIntegrationId2},
},
},
},
EscalationPolicies: map[string]*pd.EscalationPolicy{
mockEscalationPolicyId: {
APIObject: pd.APIObject{ID: mockEscalationPolicyId},
Services: []pd.APIObject{
{ID: mockServiceId},
},
},
mockEscalationPolicyId2: {
APIObject: pd.APIObject{ID: mockEscalationPolicyId2},
},
},
Incidents: []*pd.Incident{
{
APIObject: pd.APIObject{ID: mockIncidentId},
Service: pd.APIObject{ID: mockServiceId},
Status: "triggered",
AlertCounts: pd.AlertCounts{
Triggered: 1,
Resolved: 0,
All: 1,
},
},
{
APIObject: pd.APIObject{ID: mockIncidentId2},
Service: pd.APIObject{ID: mockServiceId},
Status: "resolved",
AlertCounts: pd.AlertCounts{
Triggered: 0,
Resolved: 1,
All: 1,
},
},
},
Integrations: []*pd.Integration{
{
APIObject: pd.APIObject{ID: mockIntegrationId},
IntegrationKey: mockIntegrationKey,
Service: &pd.APIObject{ID: mockServiceId},
},
{
APIObject: pd.APIObject{
ID: mockIntegrationId2,
Type: "events_api_v2_inbound_integration",
},
IntegrationKey: mockIntegrationKey2,
Service: &pd.APIObject{ID: mockServiceId},
},
},
Services: map[string]*pd.Service{
mockServiceId: {
APIObject: pd.APIObject{ID: mockServiceId},
Name: mockServiceName,
Status: "disabled",
EscalationPolicy: pd.EscalationPolicy{
APIObject: pd.APIObject{ID: mockEscalationPolicyId},
},
Integrations: []pd.Integration{
{
APIObject: pd.APIObject{ID: mockIntegrationId},
IntegrationKey: mockIntegrationKey,
Service: &pd.APIObject{ID: mockServiceId},
},
{
APIObject: pd.APIObject{
ID: mockIntegrationId2,
Type: "events_api_v2_inbound_integration_reference",
},
IntegrationKey: mockIntegrationKey2,
Service: &pd.APIObject{ID: mockServiceId},
},
},
},
},
}
}
func defaultMockApi() *mockApi {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
mockApi := &mockApi{
Client: newMockClient(server),
State: defaultMockPagerdutyState(),
mux: mux,
server: server,
}
mockApi.setupServicesHandler()
mockApi.setupDefaultServiceHandlers()
mockApi.setupDefaultGetIntegrationHandler()
mockApi.setupDefaultGetEscalationPolicyHandler()
mockApi.setupDefaultListIncidentsHandler()
mockApi.setupDefaultListIncidentAlertsHandler()
mockApi.setupV2EventsHandler()
return mockApi
}
func (m *mockApi) cleanup() {
m.server.Close()
}
// withTestHttpClient is meant to be used with httptest when testing to pass a mock http client
func withTestHttpClient(testClient *http.Client) pd.ClientOptions {
return func(c *pd.Client) {
c.HTTPClient = testClient
}
}
func newMockClient(server *httptest.Server) *mockClient {
return &mockClient{
SvcClient{
APIKey: "apiKey",
PdClient: pd.NewClient(
"apiKey",
withTestHttpClient(server.Client()),
pd.WithAPIEndpoint(server.URL),
pd.WithV2EventsAPIEndpoint(server.URL),
),
},
}
}
// setupDefaultServiceHandlers sets up handlers to get and update mock services
// as well as creating integrations for those services
func (m *mockApi) setupDefaultServiceHandlers() {
for _, svc := range m.State.Services {
m.setupCreateIntegrationHandler(svc.ID)
m.mux.HandleFunc(fmt.Sprintf("/services/%s", svc.ID), func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
serviceData := map[string]pd.Service{
"service": *svc,
}
resp, err := json.Marshal(serviceData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(resp)
if err != nil {
return
}
case http.MethodPut:
// Update default mock service
var serviceData map[string]pd.Service
err := json.NewDecoder(r.Body).Decode(&serviceData)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
service, ok := serviceData["service"]
if !ok {
http.Error(w, "Could not find expected key: service", http.StatusBadRequest)
return
}
service.ID = svc.ID
m.State.Services[svc.ID] = &service
processedService := map[string]pd.Service{
"service": service,
}
resp, err := json.Marshal(processedService)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
_, err = w.Write(resp)
if err != nil {
return
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
}
}
// setupDefaultListIncidentsHandler sets up a handler to respond to listing incidents
func (m *mockApi) setupDefaultListIncidentsHandler() {
var incidents []pd.Incident
for _, inc := range m.State.Incidents {
incidents = append(incidents, *inc)
}
incidentsData := map[string][]pd.Incident{
"incidents": incidents,
}
m.mux.HandleFunc("/incidents", func(w http.ResponseWriter, r *http.Request) {
filteredIncidentsData := processListIncidentsQueryParams(r.URL.Query(), incidentsData)
resp, err := json.Marshal(filteredIncidentsData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(resp)
if err != nil {
return
}
})
}
// setupDefaultListIncidentAlertsHandler sets up a handler to respond to listing alerts
func (m *mockApi) setupDefaultListIncidentAlertsHandler() {
for incidentId, alerts := range m.State.Alerts {
// Convert []*pd.IncidentAlert to []pd.IncidentAlert
var alertSlice []pd.IncidentAlert
for _, alert := range alerts {
alertSlice = append(alertSlice, *alert)
}
alertsData := map[string][]pd.IncidentAlert{
"alerts": alertSlice,
}
m.mux.HandleFunc(fmt.Sprintf("/incidents/%s/alerts", incidentId), func(w http.ResponseWriter, r *http.Request) {
filteredAlertsData := processListIncidentAlertsQueryParams(r.URL.Query(), alertsData)
resp, err := json.Marshal(filteredAlertsData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(resp)
if err != nil {
return
}
})
}
}
// setupServicesHandler sets up a handler to respond to creating a service with ID mockServiceId2
func (m *mockApi) setupServicesHandler() {
m.mux.HandleFunc("/services", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
var services []pd.Service
for _, svc := range m.State.Services {
services = append(services, *svc)
}
servicesData := map[string][]pd.Service{
"services": services,
}
resp, err := json.Marshal(servicesData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(resp)
case http.MethodPost:
var serviceData map[string]pd.Service
err := json.NewDecoder(r.Body).Decode(&serviceData)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
service, ok := serviceData["service"]
if !ok {
http.Error(w, "could not find expected key: service", http.StatusBadRequest)
return
}
for _, svc := range m.State.Services {
if service.Name == svc.Name {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("{\"error\":{\"message\":\"Name has already been taken\",\"code\":2100}}"))
return
}
}
service.ID = mockServiceId2
m.State.Services[service.ID] = &service
m.setupCreateIntegrationHandler(service.ID)
processedService := map[string]pd.Service{
"service": service,
}
resp, err := json.Marshal(processedService)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = w.Write(resp)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
}
// setupDefaultGetEscalationPolicyHandler sets up a mock escalation policy to interact with since the PagerDuty operator
// expects an escalation policy to already exist.
func (m *mockApi) setupDefaultGetEscalationPolicyHandler() {
for _, ep := range m.State.EscalationPolicies {
escalationPolicyData := map[string]pd.EscalationPolicy{
"escalation_policy": *ep,
}
m.mux.HandleFunc(fmt.Sprintf("/escalation_policies/%s", ep.ID), func(w http.ResponseWriter, r *http.Request) {
resp, err := json.Marshal(escalationPolicyData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(resp)
if err != nil {
return
}
})
}
}
// setupCreateIntegrationHandler sets up a handler to create new integrations for a provided service ID
func (m *mockApi) setupCreateIntegrationHandler(serviceId string) {
m.mux.HandleFunc(fmt.Sprintf("/services/%s/integrations", serviceId), func(w http.ResponseWriter, r *http.Request) {
var integrationData map[string]pd.Integration
err := json.NewDecoder(r.Body).Decode(&integrationData)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
integration, ok := integrationData["integration"]
if !ok {
http.Error(w, "Could not find expected key: integration", http.StatusBadRequest)
return
}
integration.ID = mockIntegrationId3
integration.IntegrationKey = mockIntegrationKey3
m.State.Integrations = append(m.State.Integrations, &integration)
processedIntegration := map[string]pd.Integration{
"integration": integration,
}
resp, err := json.Marshal(processedIntegration)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
_, err = w.Write(resp)
if err != nil {
return
}
})
}
// setupDefaultGetIntegrationHandler sets up a handler for mocking get integration calls for a provided service
func (m *mockApi) setupDefaultGetIntegrationHandler() {
for _, svc := range m.State.Services {
for _, integration := range svc.Integrations {
if integration.APIObject.ID == "" {
panic("integration is missing required field: ID")
}
integrationData := map[string]pd.Integration{
"integration": integration,
}
m.mux.HandleFunc(fmt.Sprintf("/services/%s/integrations/%s", svc.APIObject.ID, integration.APIObject.ID), func(w http.ResponseWriter, r *http.Request) {
resp, err := json.Marshal(integrationData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(resp)
if err != nil {
return
}
})
}
}
}
func (m *mockApi) setupV2EventsHandler() {
success := pd.V2EventResponse{
Status: "success",
DedupKey: "",
Message: "Event processed",
Errors: nil,
}
failure := pd.V2EventResponse{
Status: "Unrecognized object",
Message: "Event object format is unrecognized",
Errors: []string{"JSON parse error"},
}
m.mux.HandleFunc("/v2/enqueue", func(w http.ResponseWriter, r *http.Request) {
var eventReq pd.V2Event
err := json.NewDecoder(r.Body).Decode(&eventReq)
if err != nil || eventReq.RoutingKey == "" || eventReq.Action == "" {
w.WriteHeader(http.StatusInternalServerError)
resp, err := json.Marshal(failure)
if err != nil {
return
}
if _, err = w.Write(resp); err != nil {
return
}
return
}
// TODO: Actually resolve the alerts
success.DedupKey = eventReq.DedupKey
resp, err := json.Marshal(success)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if _, err = w.Write(resp); err != nil {
return
}
})
}
// processListIncidentAlertsQueryParams filters the list of alerts to return based on query params
// currently only "statuses" is supported
func processListIncidentAlertsQueryParams(queries map[string][]string, alerts map[string][]pd.IncidentAlert) map[string][]pd.IncidentAlert {
statuses := queries["statuses[]"]
if len(statuses) == 0 {
return alerts
}
filteredAlerts := map[string][]pd.IncidentAlert{
"alerts": {},
}
for _, alert := range alerts["alerts"] {
if utils.Contains(statuses, alert.Status) {
filteredAlerts["alerts"] = append(filteredAlerts["alerts"], alert)
}
}
return filteredAlerts
}
// processListIncidentsQueryParams filters the list of incidents to return based on query params
// currently only "service_ids" and "statuses" are supported
func processListIncidentsQueryParams(queries map[string][]string, incidents map[string][]pd.Incident) map[string][]pd.Incident {
serviceIds := queries["service_ids[]"]
statuses := queries["statuses[]"]
if len(serviceIds) == 0 && len(statuses) == 0 {
return incidents
}
filteredIncidents := map[string][]pd.Incident{
"incidents": {},
}
for _, inc := range incidents["incidents"] {
if utils.Contains(serviceIds, inc.Service.ID) && utils.Contains(statuses, inc.Status) {
filteredIncidents["incidents"] = append(filteredIncidents["incidents"], inc)
}
}
return filteredIncidents
}