-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathslackNotifications.groovy
228 lines (187 loc) · 5.38 KB
/
slackNotifications.groovy
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
def getFailedBuildBlocks() {
def messages = [
getFailedSteps(),
getTestFailures(),
]
return messages
.findAll { !!it } // No blank strings
.collect { markdownBlock(it) }
}
def dividerBlock() {
return [ type: "divider" ]
}
// If a message is longer than the limit, split it up by '\n' into parts, and return as many parts as will fit within the limit
def shortenMessage(message, sizeLimit = 3000) {
if (message.size() <= sizeLimit) {
return message
}
def truncatedMessage = "[...truncated...]"
def parts = message.split("\n")
message = ""
for(def part in parts) {
if ((message.size() + part.size() + truncatedMessage.size() + 1) > sizeLimit) {
break;
}
message += part+"\n"
}
message += truncatedMessage
return message.size() <= sizeLimit ? message : truncatedMessage
}
def markdownBlock(message) {
return [
type: "section",
text: [
type: "mrkdwn",
text: shortenMessage(message, 3000), // 3000 is max text length for `section`s only
],
]
}
def contextBlock(message) {
return [
type: "context",
elements: [
[
type: 'mrkdwn',
text: message, // Not sure what the size limit is here, I tried 10000s of characters and it still worked
]
]
]
}
def getFailedSteps() {
try {
def steps = jenkinsApi.getFailedSteps()?.findAll { step ->
step.displayName != 'Check out from version control'
}
if (steps?.size() > 0) {
def list = steps.collect { "• <${it.logs}|${it.displayName}>" }.join("\n")
return "*Failed Steps*\n${list}"
}
} catch (ex) {
buildUtils.printStacktrace(ex)
print "Error retrieving failed pipeline steps for PR comment, will skip this section"
}
return ""
}
def getTestFailures() {
def failures = testUtils.getFailures()
if (!failures) {
return ""
}
def messages = []
messages << "*Test Failures*"
def list = failures.take(10).collect {
def name = it
.fullDisplayName
.split(/\./, 2)[-1]
// Only the following three characters need to be escaped for link text, per Slack's docs
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
return "• <${it.url}|${name}>"
}.join("\n")
def moreText = failures.size() > 10 ? "\n• ...and ${failures.size()-10} more" : ""
return "*Test Failures*\n${list}${moreText}"
}
def getDefaultDisplayName() {
return "${env.JOB_NAME} ${env.BUILD_DISPLAY_NAME}"
}
def getDefaultContext(config = [:]) {
def progressMessage = ""
if (config && !config.isFinal) {
progressMessage = "In-progress"
} else {
def duration = currentBuild.durationString.replace(' and counting', '')
progressMessage = "${buildUtils.getBuildStatus().toLowerCase().capitalize()} after ${duration}"
}
return contextBlock([
progressMessage,
"<https://ci.kibana.dev/${env.JOB_BASE_NAME}/${env.BUILD_NUMBER}|ci.kibana.dev>",
].join(' · '))
}
def getStatusIcon(config = [:]) {
if (config && !config.isFinal) {
return ':hourglass_flowing_sand:'
}
def status = buildUtils.getBuildStatus()
if (status == 'UNSTABLE') {
return ':yellow_heart:'
}
return ':broken_heart:'
}
def getBackupMessage(config) {
return "${getStatusIcon(config)} ${config.title}\n\nFirst attempt at sending this notification failed. Please check the build."
}
def sendFailedBuild(Map params = [:]) {
def config = [
channel: '#kibana-operations-alerts',
title: "*<${env.BUILD_URL}|${getDefaultDisplayName()}>*",
message: getDefaultDisplayName(),
color: 'danger',
icon: ':jenkins:',
username: 'Kibana Operations',
isFinal: false,
] + params
config.context = config.context ?: getDefaultContext(config)
def title = "${getStatusIcon(config)} ${config.title}"
def message = "${getStatusIcon(config)} ${config.message}"
def blocks = [markdownBlock(title)]
getFailedBuildBlocks().each { blocks << it }
blocks << dividerBlock()
blocks << config.context
def channel = config.channel
def timestamp = null
def previousResp = buildState.get('SLACK_NOTIFICATION_RESPONSE')
if (previousResp) {
// When using `timestamp` to update a previous message, you have to use the channel ID from the previous response
channel = previousResp.channelId
timestamp = previousResp.ts
}
def resp = slackSend(
channel: channel,
timestamp: timestamp,
username: config.username,
iconEmoji: config.icon,
color: config.color,
message: message,
blocks: blocks
)
if (!resp) {
resp = slackSend(
channel: config.channel,
username: config.username,
iconEmoji: config.icon,
color: config.color,
message: message,
blocks: [markdownBlock(getBackupMessage(config))]
)
}
if (resp) {
buildState.set('SLACK_NOTIFICATION_RESPONSE', resp)
}
}
def onFailure(Map options = [:]) {
catchError {
def status = buildUtils.getBuildStatus()
if (status != "SUCCESS") {
catchErrors {
options.isFinal = true
sendFailedBuild(options)
}
}
}
}
def onFailure(Map options = [:], Closure closure) {
if (options.disabled) {
catchError {
closure()
}
return
}
buildState.set('SLACK_NOTIFICATION_CONFIG', options)
// try/finally will NOT work here, because the build status will not have been changed to ERROR when the finally{} block executes
catchError {
closure()
}
onFailure(options)
}
return this