-
Notifications
You must be signed in to change notification settings - Fork 2
/
Jenkinsfile
282 lines (245 loc) · 10 KB
/
Jenkinsfile
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
#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
/*
Environment variables: These environment variables should be set in Jenkins in: `https://github-demo.ci.cloudbees.com/job/<org name>/configure`:
For deployment purposes:
- HEROKU_PREVIEW=<your heroku preview app>
- HEROKU_PRODUCTION=<your heroku production app>
Please also add the following credentials to the global domain of your organization's folder:
- Heroku API key as secret text with ID 'HEROKU_API_KEY'
- GitHub Token value as secret text with ID 'TOKEN_GITHUB'
*/
pipeline {
// Run everything on an existing agent configured with a label 'docker'.
// This agent will need docker, git and a jdk installed at a minimum.
agent {
docker {
image 'maven:3.3.9-jdk-8-alpine'
args '--entrypoint=""'
}
}
stages {
stage('Build') {
steps {
sh 'mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -B -V'
stash includes: '**/target/*.jar', name: 'app'
}
post {
success {
// we only worry about archiving the jar file if the build steps are successful
archiveArtifacts(artifacts: '**/target/*.jar', allowEmptyArchive: true)
}
}
}
stage('Unit Tests') {
steps {
unitTest()
}
}
stage('Quality Tests') {
steps {
lintTest()
}
}
stage('Deploy') {
environment {
HEROKU_PREVIEW = credentials('HEROKU_PREVIEW')
HEROKU_PRODUCTION = credentials('HEROKU_PRODUCTION')
}
steps {
deploy()
}
}
}
}
def printOptions() {
echo "====Environment variable configurations===="
echo sh(script: 'env|sort', returnStdout: true)
}
def isPRMergeBuild() {
return (env.BRANCH_NAME ==~ /^PR-\d+$/)
}
def build() {
stage 'Build'
sh 'mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -B -V'
}
def unitTest() {
// stage 'Unit tests'
sh 'mvn test -B -Dmaven.javadoc.skip=true -Dcheckstyle.skip=true'
if (currentBuild.result == "UNSTABLE") {
sh "exit 1"
}
}
def allTests() {
stage 'All tests'
// don't skip anything
sh 'mvn test -B'
step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
if (currentBuild.result == "UNSTABLE") {
// input "Unit tests are failing, proceed?"
sh "exit 1"
}
}
def allCodeQualityTests() {
lintTest()
}
def lintTest() {
if (env.DEMO_DISABLE_LINT == "true") {
return
}
stage 'Code Quality - Linting'
context="continuous-integration/jenkins/linting"
setBuildStatus ("${context}", 'Checking code conventions', 'PENDING')
lintTestPass = true
try {
sh 'mvn verify -DskipTests=true'
} catch (err) {
setBuildStatus ("${context}", 'Some code conventions are broken', 'FAILURE')
lintTestPass = false
} finally {
if (lintTestPass) setBuildStatus ("${context}", 'Code conventions OK', 'SUCCESS')
}
}
def preview() {
if (env.DEMO_DISABLE_PREVIEW == "true") {
return
}
stage name: 'Deploy to Preview env', concurrency: 1
step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
def herokuApp = "${env.HEROKU_PREVIEW}"
def ref = "${env.GIT_COMMIT}"
def id = createDeployment(ref, "preview", "Deploying branch to test")
echo "Deployment ID: ${id}"
if (id != null) {
setDeploymentStatus(id, "pending", "https://${herokuApp}.herokuapp.com/", "Pending deployment to test");
herokuDeploy "${herokuApp}"
echo "app deployed to Heroku"
setDeploymentStatus(id, "success", "https://${herokuApp}.herokuapp.com/", "Successfully deployed to test");
}
}
def preProduction() {
if (env.DEMO_DISABLE_PREPROD == "true") {
return
}
stage name: 'Deploy to Pre-Production', concurrency: 1
switchSnapshotBuildToRelease()
herokuDeploy "${env.HEROKU_PREPRODUCTION}"
}
def manualPromotion() {
if (env.DEMO_DISABLE_PROD == "true") {
return
}
// we need a first milestone step so that all jobs entering this stage are tracked an can be aborted if needed
milestone 1
// time out manual approval after ten minutes
timeout(time: 10, unit: 'MINUTES') {
input message: "Does Pre-Production look good?"
}
// this will kill any job which is still in the input step
milestone 2
}
def deploy() {
if (env.BRANCH_NAME != 'master') {
preview()
}
else {
production()
}
}
def production() {
if (env.DEMO_DISABLE_PROD == "true") {
return
}
echo '<------ here ------>'
echo "${env.HEROKU_PRODUCTION}"
stage name: 'Deploy to Production', concurrency: 1
step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
herokuDeploy "${env.HEROKU_PRODUCTION}"
def version = getCurrentHerokuReleaseVersion("${env.HEROKU_PRODUCTION}")
def createdAt = getCurrentHerokuReleaseDate("${env.HEROKU_PRODUCTION}", version)
echo "Release version: ${version}"
createRelease(version, createdAt)
}
def switchSnapshotBuildToRelease() {
descriptor.version = '1.0.0'
descriptor.pomFile = 'pom.xml'
descriptor.transform()
}
def herokuDeploy (herokuApp) {
echo "deploying: ${herokuApp}"
withCredentials([[$class: 'StringBinding', credentialsId: 'HEROKU_API_KEY', variable: 'HEROKU_API_KEY']]) {
sh "mvn clean heroku:deploy -DskipTests=true -Dmaven.javadoc.skip=true -Dheroku.logProgress -B -V -D heroku.appName=${herokuApp}"
}
}
def getRepoSlug() {
tokens = "${env.JOB_NAME}".tokenize('/')
org = tokens[tokens.size()-3]
repo = tokens[tokens.size()-2]
return "birds-of-a-feather/reading-time"
//return "${org}/${repo}"
}
def getBranch() {
tokens = "${env.JOB_NAME}".tokenize('/')
branch = tokens[tokens.size()-1]
return "${branch}"
}
def createDeployment(ref, environment, description) {
withCredentials([[$class: 'StringBinding', credentialsId: 'TOKEN_GITHUB', variable: 'TOKEN_GITHUB']]) {
def payload = JsonOutput.toJson(["ref": "${ref}", "description": "${description}", "environment": "${environment}", "required_contexts": []])
def apiUrl = "https://api.github.com/repos/${getRepoSlug()}/deployments"
def response = sh(returnStdout: true, script: "curl -s -H \"Authorization: Token ${env.TOKEN_GITHUB}\" -H \"Accept: application/json\" -H \"Content-type: application/json\" -X POST -d '${payload}' ${apiUrl}").trim()
def jsonSlurper = new JsonSlurper()
def data = jsonSlurper.parseText("${response}")
return data.id
}
}
void createRelease(tagName, createdAt) {
echo "creating release"
withCredentials([[$class: 'StringBinding', credentialsId: 'TOKEN_GITHUB', variable: 'TOKEN_GITHUB']]) {
def body = "**Created at:** ${createdAt}\n**Deployment job:** [${env.BUILD_NUMBER}](${env.BUILD_URL})\n**Environment:** [${env.HEROKU_PRODUCTION}](https://dashboard.heroku.com/apps/${env.HEROKU_PRODUCTION})"
def payload = JsonOutput.toJson(["tag_name": "v${tagName}", "name": "${env.HEROKU_PRODUCTION} - v${tagName}", "body": "${body}"])
def apiUrl = "https://api.github.com/repos/${getRepoSlug()}/releases"
def response = sh(returnStdout: true, script: "curl -s -H \"Authorization: Token ${env.TOKEN_GITHUB}\" -H \"Accept: application/json\" -H \"Content-type: application/json\" -X POST -d '${payload}' ${apiUrl}").trim()
}
}
void setDeploymentStatus(deploymentId, state, targetUrl, description) {
echo "setting deployment status"
withCredentials([[$class: 'StringBinding', credentialsId: 'TOKEN_GITHUB', variable: 'TOKEN_GITHUB']]) {
def payload = JsonOutput.toJson(["state": "${state}", "target_url": "${targetUrl}", "description": "${description}"])
def apiUrl = "https://api.github.com/repos/${getRepoSlug()}/deployments/${deploymentId}/statuses"
def response = sh(returnStdout: true, script: "curl -s -H \"Authorization: Token ${env.TOKEN_GITHUB}\" -H \"Accept: application/json\" -H \"Content-type: application/json\" -X POST -d '${payload}' ${apiUrl}").trim()
echo "deployment response: ${response}"
}
}
void setBuildStatus(context, message, state) {
// partially hard coded URL because of https://issues.jenkins-ci.org`owse/JENKINS-36961, adjust to your own GitHub instance
step([
$class: "GitHubCommitStatusSetter",
contextSource: [$class: "ManuallyEnteredCommitContextSource", context: context],
reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/${getRepoSlug()}"],
errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
]);
echo 'set status'
}
def getCurrentHerokuReleaseVersion(app) {
echo "getting Heroku Release version"
withCredentials([[$class: 'StringBinding', credentialsId: 'HEROKU_API_KEY', variable: 'HEROKU_API_KEY']]) {
def apiUrl = "https://api.heroku.com/apps/${app}/dynos"
def response = sh(returnStdout: true, script: "curl -s -H \"Authorization: Bearer ${env.HEROKU_API_KEY}\" -H \"Accept: application/vnd.heroku+json; version=3\" -X GET ${apiUrl}").trim()
def jsonSlurper = new JsonSlurper()
def data = jsonSlurper.parseText("${response}")
return data[0].release.version
}
}
def getCurrentHerokuReleaseDate(app, version) {
echo "getting Heroku Release Date"
withCredentials([[$class: 'StringBinding', credentialsId: 'HEROKU_API_KEY', variable: 'HEROKU_API_KEY']]) {
def apiUrl = "https://api.heroku.com/apps/${app}/releases/${version}"
def response = sh(returnStdout: true, script: "curl -s -H \"Authorization: Bearer ${env.HEROKU_API_KEY}\" -H \"Accept: application/vnd.heroku+json; version=3\" -X GET ${apiUrl}").trim()
def jsonSlurper = new JsonSlurper()
def data = jsonSlurper.parseText("${response}")
return data.created_at
}
}