This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
eventhandlers.go
499 lines (404 loc) · 16.9 KB
/
eventhandlers.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
cloudevents "github.com/cloudevents/sdk-go/v2" // make sure to use v2 cloudevents here
keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0"
jira "gopkg.in/andygrunwald/go-jira.v1"
)
func HandleEvaluationFinishedEvent(myKeptn *keptnv2.Keptn, incomingEvent cloudevents.Event, data *keptnv2.EvaluationFinishedEventData) {
log.Println("[eventhandlers.go] Handling evaluation.finished Event:", incomingEvent.Context.GetID())
if !JIRA_DETAILS.TicketForEvaluations {
log.Println("[eventhandlers.go] TicketForEvaluations flag is set to false. Got an evaluation.finished from Keptn but doing nothing. If you want a ticket, set flag to true")
return
}
issueKey := createJIRATicketForEvaluationFinished(myKeptn, data)
ticketURL := JIRA_DETAILS.BaseURL + "/browse/" + issueKey
// If the SEND_EVENT flag is set in service.yaml send an event to the relevant tool
SEND_EVENT, _ := strconv.ParseBool(os.Getenv("SEND_EVENT"))
if SEND_EVENT {
sendEventForEvaluationFinishedEvents("dynatrace", "CUSTOM_INFO", ticketURL, data, myKeptn)
}
}
func HandleProblemEvent(myKeptn *keptnv2.Keptn, incomingEvent cloudevents.Event, data *keptnv2.ActionFinishedEventData) {
log.Printf("[eventhandlers.go] Handling problem event: %s", incomingEvent.Context.GetID())
if !JIRA_DETAILS.TicketForProblems {
log.Println("[eventhandlers.go] TicketForProblems flag is set to false. Got a problem from Keptn but doing nothing. If you want a ticket, set flag to true")
return
}
issueKey := createJIRATicketForProblem(myKeptn, data)
ticketURL := JIRA_DETAILS.BaseURL + "/browse/" + issueKey
// If the SEND_EVENT flag is set in service.yaml send an event to the relevant tool
SEND_EVENT, _ := strconv.ParseBool(os.Getenv("SEND_EVENT"))
if SEND_EVENT {
sendEventForProblemEvents("dynatrace", "CUSTOM_INFO", ticketURL, data, myKeptn)
}
}
//*******************************
// Helper functions
//*******************************
/********************************************
* PROBLEM SPECIFIC METHODS
*********************************************/
func createCustomPropertiesForProblemEvents(myKeptn *keptnv2.Keptn, data *keptnv2.ActionFinishedEventData, ticketURL string) map[string]string {
var customProperties = make(map[string]string)
customProperties["Result"] = string(data.Result)
customProperties["Keptn Project"] = data.EventData.GetProject()
customProperties["Keptn Service"] = data.EventData.GetService()
customProperties["Keptn Stage"] = data.EventData.GetStage()
customProperties["Ticket"] = ticketURL
customProperties["SentBy"] = "Keptn"
bridgeURL := KEPTN_DETAILS.BridgeURL + "/project/" + data.EventData.GetProject() + "/sequence/" + myKeptn.KeptnContext
customProperties["BridgeURL"] = bridgeURL
return customProperties
}
// This function relies on standard keptn tags:
// keptn_project, keptn_service and keptn_stage being present
//
// Note: This method might be replaced in future if we can send events that the dynatrace-service consumes
// As the dynatrace-service contains nice helper methods to send events.
func sendEventForProblemEvents(eventDestination string, eventType string, ticketURL string, data *keptnv2.ActionFinishedEventData, myKeptn *keptnv2.Keptn) {
log.Println("[eventhandlers.go] Sending event to:", eventDestination, " as type:", eventType)
// Split ticketURL by last forward slash to get the project key
projectKey := ticketURL[strings.LastIndex(ticketURL, "/")+1:]
// Send Dynatrace Event
if eventDestination == "dynatrace" && os.Getenv("DT_TENANT") != "" && os.Getenv("DT_API_TOKEN") != "" {
dynatraceTenant := os.Getenv("DT_TENANT")
dynatraceAPIToken := os.Getenv("DT_API_TOKEN")
dynatraceAPITokenHeader := "Api-Token " + dynatraceAPIToken
// Build data
var dtInfoEvent = new(DtInfoEvent)
dtInfoEvent.EventType = eventType
dtInfoEvent.Source = "jira-service"
dtInfoEvent.Title = "Ticket Created: " + projectKey
dtInfoEvent.AttachRules = createAttachRulesForProblemEvents(data)
dtInfoEvent.Description = "Keptn Problem"
customProperties := createCustomPropertiesForProblemEvents(myKeptn, data, ticketURL)
dtInfoEvent.CustomProperties = customProperties
//Encode the data
jsonString, _ := json.Marshal(dtInfoEvent)
client := &http.Client{}
dtTenantURL := "https://" + dynatraceTenant + "/api/v1/events"
req, _ := http.NewRequest("POST", dtTenantURL, bytes.NewReader(jsonString))
req.Header.Add("accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", dynatraceAPITokenHeader)
// Send Request
resp, err := client.Do(req)
//Handle Error
if err != nil {
log.Fatalf("[eventhandlers.go] An Error Occured Sending POSt to JIRA %v", err)
}
defer resp.Body.Close()
//Read the response body
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
}
}
func createJIRATicketForProblem(myKeptn *keptnv2.Keptn, data *keptnv2.ActionFinishedEventData) string {
log.Println("[eventhandlers.go] Creating JIRA Body details for problem...")
// Build summary field (JIRA ticket title)
summary := "[PROBLEM] " + data.GetProject() + " - " + data.GetService() + " - " + data.GetStage() + " - Result: " + string(data.Result)
description := "||*PROBLEM Status*||*Project*||*Service*||*Stage*||\n"
/* Add nice JIRA icons
* Emojis via API don't follow the UI standard
* (/) = :check_mark:
* (!) = :warning:
* (x) = :cross_mark:
*/
stringResult := string(data.Result)
result := ""
if stringResult == "pass" {
result += stringResult + " (/)"
} else if stringResult == "warning" {
result += stringResult + " (!)"
} else if stringResult == "fail" {
result += stringResult + " (x)"
} else {
result += stringResult
}
description += "|" + result + "|" + data.GetProject() + "|" + data.GetService() + "|" + data.GetStage() + "|\n\n"
// Add Message
description += "Message: " + data.Message + "\n\n"
// Add Keptn Context
description += "Keptn Context ID: " + myKeptn.KeptnContext + "\n"
// Add link to Keptn Bridge
bridgeURL := KEPTN_DETAILS.BridgeURL + "/project/" + data.EventData.GetProject() + "/sequence/" + myKeptn.KeptnContext
description += "[Link To Keptn's Bridge|" + bridgeURL + "]"
// Build map of labels which we take from the cloudevent, which we then attach to the JIRA ticket
labels := createJIRALabelsForProblemEvents(data)
// Send the POST to JIRA
issueKey := createJIRATicket(summary, description, labels)
return issueKey
}
func createJIRALabelsForProblemEvents(data *keptnv2.ActionFinishedEventData) []string {
//[]string{"foo:bar", "this:that"}
labels := []string{}
// Add Keptn Project, Service and Stage as labels
// JIRA labels don't accept spaces so convert spaces to dashes
value := strings.ReplaceAll(data.EventData.GetProject(), " ", "-")
labels = append(labels, "keptn_project:"+value)
value = strings.ReplaceAll(data.EventData.GetService(), " ", "-")
labels = append(labels, "keptn_service:"+value)
value = strings.ReplaceAll(data.EventData.GetStage(), " ", "-")
labels = append(labels, "keptn_service:"+value)
// Add result as a label (pass, warning or fail)
labels = append(labels, "keptn_result:"+string(data.Result))
for labelKey, labelValue := range data.Labels {
// Replace spaces with dashes for the Key and Value
labelKeyClean := strings.ReplaceAll(labelKey, " ", "-")
labelValueClean := strings.ReplaceAll(labelValue, " ", "-")
//Stick the cleaned key and value back together
cleanKeyValueLabel := fmt.Sprint(labelKeyClean, ":", labelValueClean)
// Skip labels that are too long for JIRA to handle
// Max length is 255 chars
if len(cleanKeyValueLabel) > 255 {
log.Println("[eventhandlers.go] Skipping label: ", cleanKeyValueLabel, ": Reason: label too long. JIRA accepts labels of max 255 chars and this label has:", len(cleanKeyValueLabel))
}
labels = append(labels, fmt.Sprint(labelKeyClean, ":", labelValueClean)) // Append this "key":"value" using Sprint so as to not add spaces
}
return labels
}
func createAttachRulesForProblemEvents(data *keptnv2.ActionFinishedEventData) DtAttachRules {
attachRule := DtAttachRules{
TagRule: []DtTagRule{
{
MeTypes: []string{"SERVICE"},
Tags: []DtTag{
{
Context: "CONTEXTLESS",
Key: "keptn_project",
Value: data.GetProject(),
},
{
Context: "CONTEXTLESS",
Key: "keptn_stage",
Value: data.GetStage(),
},
{
Context: "CONTEXTLESS",
Key: "keptn_service",
Value: data.GetService(),
},
},
},
},
}
return attachRule
}
/********************************************
* EVALUATION.FINISHED SPECIFIC METHODS
*********************************************/
// This function relies on standard keptn tags:
// keptn_project, keptn_service and keptn_stage being present
//
// Note: This method might be replaced in future if we can send events that the dynatrace-service consumes
// As the dynatrace-service contains nice helper methods to send events.
func sendEventForEvaluationFinishedEvents(eventDestination string, eventType string, ticketURL string, data *keptnv2.EvaluationFinishedEventData, myKeptn *keptnv2.Keptn) {
log.Println("[eventhandlers.go] Sending event to:", eventDestination, " as type:", eventType)
// Split ticketURL by last forward slash to get the project key
projectKey := ticketURL[strings.LastIndex(ticketURL, "/")+1:]
// Send Dynatrace Event
if eventDestination == "dynatrace" && os.Getenv("DT_TENANT") != "" && os.Getenv("DT_API_TOKEN") != "" {
dynatraceTenant := os.Getenv("DT_TENANT")
dynatraceAPIToken := os.Getenv("DT_API_TOKEN")
dynatraceAPITokenHeader := "Api-Token " + dynatraceAPIToken
// Build data
var dtInfoEvent = new(DtInfoEvent)
dtInfoEvent.EventType = eventType
dtInfoEvent.Source = "jira-service"
dtInfoEvent.Title = "Ticket Created: " + projectKey
dtInfoEvent.AttachRules = createAttachRulesForEvaluationFinishedEvents(data)
dtInfoEvent.Description = "Keptn Quality Gate Evaluation"
customProperties := createCustomPropertiesForEvaluationFinishedEvents(myKeptn, data, ticketURL)
dtInfoEvent.CustomProperties = customProperties
//Encode the data
jsonString, _ := json.Marshal(dtInfoEvent)
client := &http.Client{}
dtTenantURL := "https://" + dynatraceTenant + "/api/v1/events"
req, _ := http.NewRequest("POST", dtTenantURL, bytes.NewReader(jsonString))
req.Header.Add("accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", dynatraceAPITokenHeader)
// Send Request
resp, err := client.Do(req)
//Handle Error
if err != nil {
log.Fatalf("[eventhandlers.go] An Error Occured Sending POSt to JIRA %v", err)
}
defer resp.Body.Close()
//Read the response body
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
}
}
func createAttachRulesForEvaluationFinishedEvents(data *keptnv2.EvaluationFinishedEventData) DtAttachRules {
attachRule := DtAttachRules{
TagRule: []DtTagRule{
{
MeTypes: []string{"SERVICE"},
Tags: []DtTag{
{
Context: "CONTEXTLESS",
Key: "keptn_project",
Value: data.EventData.GetProject(),
},
{
Context: "CONTEXTLESS",
Key: "keptn_stage",
Value: data.EventData.GetStage(),
},
{
Context: "CONTEXTLESS",
Key: "keptn_service",
Value: data.EventData.GetService(),
},
},
},
},
}
return attachRule
}
func createCustomPropertiesForEvaluationFinishedEvents(myKeptn *keptnv2.Keptn, data *keptnv2.EvaluationFinishedEventData, ticketURL string) map[string]string {
var customProperties = make(map[string]string)
//customProperties = make(map[string]string)
customProperties["Quality Gate Result"] = data.Evaluation.Result
customProperties["Quality Gate Score"] = fmt.Sprint(data.Evaluation.Score)
customProperties["Keptn Project"] = data.EventData.GetProject()
customProperties["Keptn Service"] = data.EventData.GetService()
customProperties["Keptn Stage"] = data.EventData.GetStage()
customProperties["Ticket"] = ticketURL
customProperties["SentBy"] = "Keptn"
bridgeURL := KEPTN_DETAILS.BridgeURL + "/project/" + data.EventData.GetProject() + "/sequence/" + myKeptn.KeptnContext
customProperties["BridgeURL"] = bridgeURL
return customProperties
}
func createJIRALabelsForEvaluationFinishedEvents(data *keptnv2.EvaluationFinishedEventData) []string {
//[]string{"foo:bar", "this:that"}
labels := []string{}
// Add Keptn Project, Service and Stage as labels
// JIRA labels don't accept spaces so convert spaces to dashes
value := strings.ReplaceAll(data.EventData.GetProject(), " ", "-")
labels = append(labels, "keptn_project:"+value)
value = strings.ReplaceAll(data.EventData.GetService(), " ", "-")
labels = append(labels, "keptn_service:"+value)
value = strings.ReplaceAll(data.EventData.GetStage(), " ", "-")
labels = append(labels, "keptn_service:"+value)
// Add result as a label (pass, warning or fail)
labels = append(labels, "keptn_result:"+string(data.Result))
for labelKey, labelValue := range data.Labels {
// Replace spaces with dashes for the Key and Value
labelKeyClean := strings.ReplaceAll(labelKey, " ", "-")
labelValueClean := strings.ReplaceAll(labelValue, " ", "-")
//Stick the cleaned key and value back together
cleanKeyValueLabel := fmt.Sprint(labelKeyClean, ":", labelValueClean)
// Skip labels that are too long for JIRA to handle
// Max length is 255 chars
if len(cleanKeyValueLabel) > 255 {
log.Println("[eventhandlers.go] Skipping label: ", cleanKeyValueLabel, ": Reason: label too long. JIRA accepts labels of max 255 chars and this label has:", len(cleanKeyValueLabel))
}
labels = append(labels, fmt.Sprint(labelKeyClean, ":", labelValueClean)) // Append this "key":"value" using Sprint so as to not add spaces
}
return labels
}
func createJIRATicketForEvaluationFinished(myKeptn *keptnv2.Keptn, data *keptnv2.EvaluationFinishedEventData) string {
log.Println("[eventhandlers.go] Creating JIRA Body details for evaluation.finished...")
// Build summary field (JIRA ticket title)
stringResult := string(data.Result)
summary := "[EVALUATION] " + data.EventData.GetProject() + " - " + data.EventData.GetService() + " - " + data.EventData.GetStage() + " - Result: " + stringResult
// Build description field (JIRA ticket body)
// Build result table
description := "||*Result*||*Score*||\n"
/* Add nice JIRA icons
* Emojis via API don't follow the UI standard
* (/) = :check_mark:
* (!) = :warning:
* (x) = :cross_mark:
*/
result := ""
if stringResult == "pass" {
result += stringResult + " (/)"
} else if stringResult == "warning" {
result += stringResult + " (!)"
} else if stringResult == "fail" {
result += stringResult + " (x)"
} else {
result += stringResult
}
description += "|" + result + "|" + fmt.Sprint(data.Evaluation.Score) + "|" + "\n\n"
// Add Start Time and End Time
description += "Start Time: " + data.Evaluation.TimeStart + "\n"
description += "End Time: " + data.Evaluation.TimeEnd + "\n"
// Add Keptn Context
description += "Keptn Context ID: " + myKeptn.KeptnContext + "\n"
description += "Message: " + data.EventData.Message + "\n"
// Add link to Keptn Bridge
bridgeURL := KEPTN_DETAILS.BridgeURL + "/project/" + data.EventData.GetProject() + "/sequence/" + myKeptn.KeptnContext
description += "[Link To Keptn's Bridge|" + bridgeURL + "]"
// Build map of labels which we take from the cloudevent, which we then attach to the JIRA ticket
labels := createJIRALabelsForEvaluationFinishedEvents(data)
// Send the POST to JIRA
issueKey := createJIRATicket(summary, description, labels)
return issueKey
}
/**************************************
* GENERIC METHODS
***************************************/
// Shared Function between evaluations and problem events to create a JIRA ticket
// By this point, summary and description are correctly formulated
// Depending on the type of ticket so this function can be shared
// As it just sends the POST to JIRA
func createJIRATicket(summary string, description string, labels []string) string {
tp := jira.BasicAuthTransport{
Username: JIRA_DETAILS.Username,
Password: JIRA_DETAILS.APIToken,
}
jiraClient, err := jira.NewClient(tp.Client(), JIRA_DETAILS.BaseURL)
if err != nil {
panic(err)
}
i := jira.Issue{
Fields: &jira.IssueFields{
Assignee: &jira.User{
AccountID: JIRA_DETAILS.AssigneeID,
},
Reporter: &jira.User{
AccountID: JIRA_DETAILS.ReporterID,
},
Description: description,
Type: jira.IssueType{
Name: JIRA_DETAILS.IssueType,
},
Project: jira.Project{
Key: JIRA_DETAILS.ProjectKey,
},
Summary: summary,
Labels: labels,
},
}
// Create ticket
issue, response, err := jiraClient.Issue.Create(&i)
if err != nil {
data, err2 := ioutil.ReadAll(response.Body)
if err != nil {
log.Println(err2)
log.Println(string(data))
}
log.Println(err)
log.Println(string(data))
} else {
log.Println("[eventhandlers.go] Created ticket successfully: ", issue.Key)
}
return issue.Key
}