-
Notifications
You must be signed in to change notification settings - Fork 0
/
Testing-Jenkinsfile-Development
276 lines (222 loc) · 9.54 KB
/
Testing-Jenkinsfile-Development
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
/**
* Track Git logs
*
*/
def showChangeLogs(versionHash) {
def authors = []
def accept = []
def changeLogSets = currentBuild.rawBuild.changeSets
if (changeLogSets.size() == 0) return [];
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def author = "${entries[j].author}"
def email = "${entries[j].authorEmail}"
authors.push("${author}:${email}")
def isParent = false
def source = currentBuild.rawBuild.changeSets[i].browser.getChangeSetLink(entries[j]).toString().split('/')[4]
def sourceDirs = []
switch (source) {
case 'widgetworld':
entries[j].comment.contains(versionHash) ?: accept.push(source)
isParent = true
break
case 'intermx-cicd-helm':
sourceDirs = ['insights-ui-testing']
break
}
if (isParent) continue;
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles)
for (int k = 0; k < files.size(); k++) {
!sourceDirs.contains(files[k].path.split('/')[0]) ?: accept.push(files[k].path)
}
}
}
return accept.unique().size() == 0 ?: authors.unique()
}
/**
* TODO: Track Container Deployment Status
*
*/
def getDeploymentStatus(commitId, environment) {
sh "sleep 10s"
def status
def sleep = ['ContainerCreating', 'Pending', 'Succeeded']
def success = ['Running']
def failure = ['CrashLoopBackOff', 'Terminating', 'Error']
sh "kubectl get pods -l build=${commitId} --namespace=${environment} --sort-by=.status.startTime"
def deploymentVerify = sh (script: "kubectl get pods -l build=${commitId} --namespace=${environment} --sort-by=.status.startTime | awk 'NR==2{print \$3}'", returnStdout: true).trim()
def containerCount = sh (script: "kubectl get pods -l build=${commitId} --namespace=${environment} --sort-by=.status.startTime | awk 'NR==2{print \$4}'", returnStdout: true).trim().toInteger()
echo "Deployment Status: ${deploymentVerify}"
echo "Container Restart Count: ${containerCount}"
if (sleep.contains(deploymentVerify)) {
return getDeploymentStatus(commitId, environment)
}
if (success.contains(deploymentVerify)) {
if (containerCount == 0) {
return true
} else {
return false
}
}
if (failure.contains(deploymentVerify)) {
return false
}
}
/**
* Jenkins pipeline stages.
*
* A list of stages available in this pipeline Jenkins file will be executed
* squentially. The name of this file should be matching with Pipeline block of
* Jenkins configuration.
*
*/
node {
timeout(unit: 'HOURS', time: 5) {
/**
* Version details for tagging the image.
*
*/
def tag
/**
* Define script variables.
*
*/
def notify
def slackChannel = "#general"
def organization = "${ORGANIZATION}"
organization = organization.toUpperCase()
// Docker image
def proxy
def environment = "staging"
// AWS Credentials
def awsCredentials = "intermx-impinger-credentials"
// ECR Repository for proxy
def proxyEcrRepoName = "intermx-insights-ui-testing"
// ECR Repository Endpoint
def ecrEndpoint = 'https://${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com'
// ECR Credentials
def ecrCredentials = "ecr:us-east-1:${awsCredentials}"
// Version Hash
def versionHash = '2d3cbcc5acfa4626c44f81f33c5f7013'
// Git commit message
def commitMessage
def currRepoBranch
def commitId
def deployment
def domain
try {
/**
* Cloning the repository to workspace to build image.
*
*/
checkout scm
def (origin, branch) = scm.branches[0].name.tokenize('/')
commitMessage = sh (script: 'git log --oneline -1 ${GIT_COMMIT}', returnStdout: true).trim().substring(8)
commitId = sh (script: 'git log -1 --format=%H', returnStdout: true).trim() // %h, for short hash
notify = showChangeLogs(versionHash)
currRepoBranch = branch;
if (notify instanceof Boolean && Boolean.TRUE.equals(notify)) {
return
}
// Slack notification in progress.
notifyBuild('STARTED', currRepoBranch, commitMessage)
sh "echo ${currRepoBranch} branch"
/**
* Run Tests
*
*/
stage('Run Cypress Test') {
// Set Node tool
env.NODEJS_HOME = "${tool 'node'}"
env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"
// Prepare POD to run test
sh "apt --fix-broken -y install"
sh "apt-get update && apt-get -y install xdg-utils libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb zip unzip"
sh "wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"
sh "apt install -y ./google-chrome-stable_current_amd64.deb"
// Add required modules
sh "mv common.package.json package.json && mv common.package-lock.json package-lock.json"
sh "npm install"
sh "npm install mochawesome-merge"
// Run test (Ref: https://docs.cypress.io/guides/guides/command-line#cypress-cache-command)
try {
// handles graceful exit on failure
sh "./node_modules/.bin/cypress run --browser chrome --headless"
//sh "./node_modules/.bin/cypress run --browser chrome --headless --spec cypress//integration//geopath//11zzzzBillinExportFilterSearchByStartEndDate.js, cypress//integration//geopath//4VerifyIODatesInContractLine.js, cypress//integration//geopath//MarketPlanGridValues.js, cypress//integration//geopath//TestTheFunctionalityOfSaveAsNewInventorySetandgenerateplanValidate.js, cypress//integration//geopath//VerifyMarketPlanGridValues.js, cypress//integration//geopath//ZzzCreateScenariForInventoryFromMapView.js"
} catch(exception) {
echo "One or more test case failed"
echo "${exception}"
}
// Generate report
sh "npm run mochawesome-report-output"
sh "npm run mochawesome-report"
}
}
catch(exception) {
echo "${exception}"
// Slack notification failure.
notifyBuild('FAILURE', null, null, 'Something went wrong in one of the stages, exception found in Jenkins.', notify, slackChannel)
}
finally {
// Clean up the workspace after finish the job.
deleteDir()
}
}
}
/**
* Sending notifications to Slack channel.
*
*/
def notifyBuild(buildStatus = 'FAILURE', branch = null, commitMessage = null, message = null, notify = null, channel = null) {
// Default values
def summary
def alert = false
def baseURL = "${SLACK_BASE_URL}"
if (buildStatus == 'STARTED') {
color = 'YELLOW'
colorCode = '#FFFF00'
summary = "${buildStatus}: ${organization} - Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' is currently working on branch '${branch}' with a message: '${commitMessage}'"
} else if (buildStatus == 'SUCCESS') {
color = 'GREEN'
colorCode = '#00FF00'
summary = "${buildStatus}: ${organization} - Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' | Message: ${message}"
} else {
color = 'RED'
colorCode = '#FF0000'
summary = "${buildStatus}: ${organization} - Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' | Error: ${message} | URL: `${env.BUILD_URL}console` (please make sure, you are on VPN to access the Jenkins link)"
alert = true
}
// Send notifications to Slack.
slackSend (baseUrl: baseURL, color: colorCode, message: summary)
if (alert) {
for(int i = 0; i < notify.size(); i++) {
def notice = notify[i].split(":")
def author = notice[0]
def email = notice[1]
def domain = email.split("@")[1]
if (domain && domain == 'intermx.com') {
emailext (
to: "${email}",
subject: "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """
<html>
<body>
<p>Hi ${author},</p>
<br>
<p>The build job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' failed to complete.</p>
<p>The following error was reported:</p>
<br>
<p>${message}</p>
<br>
<p>Please review the error at <a href=\"${env.BUILD_URL}console\">${env.BUILD_URL}console</a> and resolve the issue causing the failure so that releases can continue.</p>
</body>
</html>
"""
)
}
}
slackSend (baseUrl: baseURL, channel: "${channel}", color: colorCode, message: summary)
}
}