/
build.gradle
482 lines (425 loc) · 16.2 KB
/
build.gradle
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
import com.bmuschko.gradle.docker.tasks.container.DockerCreateContainer
import com.bmuschko.gradle.docker.tasks.container.DockerRemoveContainer
import com.bmuschko.gradle.docker.tasks.container.DockerStartContainer
import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage
import com.bmuschko.gradle.docker.tasks.image.DockerPushImage
import com.bmuschko.gradle.docker.tasks.image.Dockerfile
import groovy.json.JsonOutput
import groovyx.net.http.RESTClient
import jp.classmethod.aws.gradle.s3.SyncTask
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.FileEntity
import org.apache.http.impl.client.DefaultHttpClient
buildscript {
ext {
grailsVersion = project.grailsVersion
}
repositories {
mavenLocal()
if (System.getenv('MAVEN_REPO')) {
maven { url { System.getenv('MAVEN_REPO') } }
}
maven { url "https://repo.grails.org/grails/core" }
jcenter()
maven { url 'https://plugins.gradle.org/m2/' }
}
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "gradle.plugin.com.energizedwork.webdriver-binaries:webdriver-binaries-gradle-plugin:1.4"
classpath "gradle.plugin.com.energizedwork:idea-gradle-plugins:1.4"
classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.14.10"
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.2'
classpath 'com.bmuschko:gradle-docker-plugin:3.3.6'
classpath 'com.netflix.nebula:gradle-lint-plugin:9.0.0'
classpath 'com.github.ben-manes:gradle-versions-plugin:0.20.0'
classpath "jp.classmethod.aws:gradle-aws-plugin:0.38"
classpath "gradle.plugin.dk.danskespil.gradle.plugins:gradle-plugin-terraform:0.1.0"
classpath 'io.github.http-builder-ng:http-builder-ng-core:1.0.3'
}
}
plugins {
id 'com.gradle.build-scan' version '1.16'
id 'com.craigburke.client-dependencies' version '1.4.0'
id 'com.patdouble.awsecr' version '0.4.0'
id 'com.patdouble.zap' version '2.0.2'
id "org.sonarqube" version "2.6.2"
id "org.owasp.dependencycheck" version "4.0.0.1"
}
apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"war"
apply plugin:"org.grails.grails-web"
apply plugin:"org.grails.grails-gsp"
apply plugin:"asset-pipeline"
apply plugin:"com.energizedwork.webdriver-binaries"
apply plugin:"com.energizedwork.idea-project-components"
apply plugin: "com.bmuschko.docker-remote-api"
apply plugin: "jp.classmethod.aws.s3"
apply plugin: 'nebula.lint'
allprojects {
apply plugin: 'com.github.ben-manes.versions'
}
configure(project(':terraform').subprojects) { subproject ->
apply plugin: 'dk.danskespil.gradle.plugins.terraform'
tfValidate {
varfile(project(':terraform').file('common.tfvars'))
}
tfPlan {
varfile(project(':terraform').file('common.tfvars'))
out = new File(subproject.buildDir, 'plan-output.bin')
outAsText = new File(subproject.buildDir, 'plan-output.txt')
doLast {
if (!out.exists()) {
out.text = ''
}
}
}
tfApply {
plan = tfPlan.out
autoApprove = true
}
}
version "0.1"
group "pet.store"
buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
}
ext {
grailsVersion = project.grailsVersion
gradleWrapperVersion = project.gradleWrapperVersion
cacheDir = gradle.getGradleUserHomeDir() as String ?: "${System.getProperty("user.home")}/.cache/gradle"
new File(cacheDir).mkdirs()
commit = System.getenv('COMMIT_HASH') ?: System.getenv('CODEBUILD_RESOLVED_SOURCE_VERSION') ?: System.getenv('CODEBUILD_SOURCE_VERSION') ?: "git rev-parse HEAD".execute().text.trim()
shortCommit = commit.length() > 7 ? commit.substring(0, 7) : commit
applicationFile = new File(war.archivePath.parentFile, war.archivePath.name.replace('.war', '-app.war'))
}
bootRun {
jvmArgs('-Dspring.output.ansi.enabled=always')
addResources = true
}
assets {
minifyJs = true
minifyCss = true
}
/* Use the typical docker-machine environment variables to configure docker. */
ext {
dockerHost = null
repository = System.getenv('DOCKER_REGISTRY_URL') ?: 'pet-store-app'
}
docker {
if (System.getenv('DOCKER_TLS_VERIFY') == '1' && System.getenv('DOCKER_CERT_PATH')) {
url = System.getenv('DOCKER_HOST')?.replaceAll('tcp://', 'https://')
certPath = new File(System.getenv('DOCKER_CERT_PATH'))
project.dockerHost = new URL(url).host
} else if (System.getenv('DOCKER_HOST')) {
url = System.getenv('DOCKER_HOST')?.replaceAll('tcp://', 'http://')
project.dockerHost = new URL(url).host
}
if (System.getenv('DOCKER_REGISTRY_URL')) {
registryCredentials {
url = System.getenv('DOCKER_REGISTRY_URL')
}
}
}
repositories {
mavenLocal()
if (System.getenv('MAVEN_REPO')) {
maven { url { System.getenv('MAVEN_REPO') } }
}
maven { url "https://repo.grails.org/grails/core" }
jcenter()
mavenCentral()
}
dependencies {
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.grails:grails-web-boot"
compile "org.grails:grails-logging"
compile "org.grails:grails-plugin-rest"
compile "org.grails:grails-plugin-databinding"
compile "org.grails:grails-plugin-i18n"
compile "org.grails:grails-plugin-services"
compile "org.grails:grails-plugin-url-mappings"
compile "org.grails:grails-plugin-interceptors"
compile "org.grails.plugins:cache"
compile "org.grails.plugins:async"
compile "org.grails.plugins:scaffolding"
compile "org.grails.plugins:events"
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.5.Final"
compile "org.grails.plugins:gsp"
console "org.grails:grails-console"
profile "org.grails.profiles:web"
runtime "org.glassfish.web:el-impl:2.1.2-b03"
runtime "com.h2database:h2"
runtime "org.apache.tomcat:tomcat-jdbc"
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.14.10"
testCompile "org.grails:grails-gorm-testing-support"
testCompile "org.grails:grails-web-testing-support"
testCompile "org.grails.plugins:geb"
testRuntime "org.seleniumhq.selenium:selenium-chrome-driver:${seleniumVersion}"
testRuntime "org.seleniumhq.selenium:selenium-firefox-driver:${seleniumVersion}"
testRuntime "org.seleniumhq.selenium:selenium-safari-driver:${seleniumVersion}"
//testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.31.+"
testRuntime "org.seleniumhq.selenium:selenium-remote-driver:${seleniumVersion}"
testRuntime "org.seleniumhq.selenium:selenium-support:${seleniumVersion}"
testRuntime "org.seleniumhq.selenium:selenium-api:${seleniumVersion}"
}
clientDependencies {
yarn {
'jquery'('~2.1.0')
"angular"("~1.3.15")
"angular-route"("~1.3.15")
"angular-loader"("~1.3.15")
"angular-animate"("~1.3.15")
"angular-cookies"("~1.3.15")
"angular-resource"("~1.3.15")
"angular-sanitize"("~1.3.15")
"angular-touch"("~1.3.15")
"angular-mocks"("~1.3.15")
"animate.css"("3.x")
}
}
webdriverBinaries {
chromedriver "$chromeDriverVersion"
geckodriver "$geckodriverVersion"
}
allprojects {
dependencyUpdates.resolutionStrategy = {
componentSelection { rules ->
rules.all { ComponentSelection selection ->
if (['.M', '.RC', 'beta', 'alpha', '-rc'].find {
selection.candidate.version.toLowerCase().contains(it.toLowerCase())
}) {
selection.reject('unreleased')
}
}
}
}
gradleLint.rules = ['all-dependency','dependency-parenthesis','dependency-tuple']
autoLintGradle.onlyIf { false }
}
task wrapper(type: Wrapper) {
gradleVersion = gradleWrapperVersion
distributionType = Wrapper.DistributionType.ALL
}
// Using a different output file allows incremental build, 'classifier' property doesn't work
bootRepackage {
inputs.file(war.archivePath)
outputs.file(applicationFile)
setOutputFile(applicationFile)
}
/*
* Uploading a source tarball with the compiled jar and an empty maven build to make the Java buildpack happy
*/
task emptyPom {
outputs.file('build/pom.xml')
doLast {
new File('build/pom.xml').text = """
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pet.store</groupId>
<artifactId>placeholder</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>Pet Store</name>
<build>
<finalName>placeholder</finalName>
</build>
</project>
"""
}
}
task herokuSources(type: Tar, dependsOn: [emptyPom, bootRepackage]) {
description = "Package binary application into Heroku sources for faster deployment"
group = "distribution"
appendix = "heroku"
compression = Compression.GZIP
from 'Procfile'
from 'system.properties'
from 'build/pom.xml'
into('src/main/dist') {
from applicationFile
}
}
// Documentation at https://devcenter.heroku.com/articles/build-and-release-using-the-api
task deployToHeroku(dependsOn: herokuSources) {
description = 'Deploy the application to Heroku via the Platform API REST services'
group = "distribution"
doLast {
RESTClient heroku = new RESTClient("https://api.heroku.com/apps/${System.getenv("HEROKU_APP_NAME")}/")
heroku.headers['Authorization'] = "Bearer ${System.getenv('HEROKU_AUTH_TOKEN')}"
heroku.headers['Accept'] = 'application/vnd.heroku+json; version=3'
// upload sources
def sources = heroku.post(path: 'sources')
def put_url = sources.data.source_blob.put_url
def get_url = sources.data.source_blob.get_url
// upload sources, Heroku/AWS is very picky about the headers sent, so we need to use this way. For example, Content-Type must not be present
logger.info("Uploading ${herokuSources.archivePath} to ${put_url}")
def res = new DefaultHttpClient().execute(new HttpPut(URI: new URI(put_url), entity: new FileEntity(herokuSources.archivePath)))
if (res.statusLine.statusCode > 399) {
throw new IOException(res.statusLine.reasonPhrase)
}
// start the build
logger.info("Building ${get_url}")
heroku.post(path: 'builds', requestContentType: 'application/json',
body: ['source_blob': ['url':get_url, 'version': "git rev-parse HEAD".execute().text.trim() ]]
)
}
onlyIf { System.getenv('HEROKU_AUTH_TOKEN') && System.getenv('HEROKU_APP_NAME') }
}
processResources.dependsOn clientInstall
assetCompile.dependsOn clientInstall
build.dependsOn ':staticsite:generate'
/*
* Container based tasks follow. These tasks allow all build operations to be done in containers,
* thus reducing the dependencies required on the build host to be Java and Docker.
*/
/* The `dockerOutput` directory holds all build outputs from the containers. */
ext {
dockerOutput = "${project.buildDir}/docker/output"
}
task dockerResources(type: Sync) {
group = "staging"
into "${project.buildDir}/docker-resources"
from 'src/main/docker'
}
task webappContext(type: Sync) {
group = "staging"
into "${project.buildDir}/docker/webapp"
from project.buildDir
dependsOn bootRepackage, dockerResources
include applicationFile.absolutePath.replaceFirst("${project.buildDir}/", '')
include 'docker-resources/**/*'
}
task webappDockerfile(type: Dockerfile) {
group = "staging"
dependsOn bootRepackage, webappContext
destFile = project.file("${project.buildDir}/docker/webapp/Dockerfile")
from 'openjdk:8u151-jre-alpine'
environmentVariable "TERM", "dumb"
runCommand 'apk add --no-cache curl && rm -rf /tmp/*'
exposePort 8080, 8000
instruction 'HEALTHCHECK --interval=1m --timeout=20s --start-period=2m CMD curl -f http://localhost:8080/health || exit 1'
workingDir '/app'
copyFile 'docker-resources/start-grails.sh', '/app/start-grails.sh'
runCommand 'chmod +x /app/start-grails.sh'
defaultCommand '/app/start-grails.sh'
label([
'maintainer' : 'Patrick Double "pat@patdouble.com"',
//'org.label-schema.build-date': Instant.now().toString(),
'org.label-schema.vendor' : "https://github.com/double16",
'org.label-schema.license' : "Apache-2.0",
'org.label-schema.name' : "Pet Store Application",
'org.label-schema.url' : "https://github.com/double16/pet-store",
'org.label-schema.vcs-ref' : commit,
'org.label-schema.vcs-type' : 'git',
'org.label-schema.vcs-url' : "https://github.com/double16/pet-store.git"
])
copyFile applicationFile.absolutePath.replaceFirst("${project.buildDir}/", ''), '/app/'
}
task webappImage(type: DockerBuildImage) {
dependsOn webappDockerfile, webappContext
inputs.file applicationFile
dockerFile = webappDockerfile.destFile
inputDir = dockerFile.parentFile
tags << "${repository}:${shortCommit}".toString()
tags << "${repository}:latest".toString()
}
task webappImagePublish(type: DockerPushImage) {
group = "staging"
dependsOn webappImage
imageName = webappImage.tags.first() - ~/:[^:]+$/
}
integrationTest.shouldRunAfter zapStart
zapActiveScan.dependsOn integrationTest
zapConfig {
applicationUrl = "http://localhost:8080/"
activeScanTimeout = "0"
}
/*
* Static site container.
*/
task staticContext(type: Sync) {
group = "staging"
dependsOn ':staticsite:generate'
into "${project.buildDir}/docker/staticsite/content"
from project(':staticsite').file('target')
}
task staticDockerfile(type: Dockerfile) {
group = 'staging'
dependsOn staticContext
destFile = file("${project.buildDir}/docker/staticsite/Dockerfile")
from 'sebp/lighttpd:latest'
maintainer 'Patrick Double "pat@patdouble.com"'
copyFile 'content', '/var/www/localhost/htdocs/'
}
task staticImage(type: DockerBuildImage) {
group = 'staging'
dependsOn staticDockerfile
dockerFile = staticDockerfile.destFile
inputDir = staticDockerfile.destFile.parentFile
tags << "${repository}-site:${shortCommit}".toString()
tags << "${repository}-site:latest".toString()
}
task staticImagePublish(type: DockerPushImage) {
group = "staging"
dependsOn staticImage
imageName = staticImage.tags.first() - ~/:[^:]+$/
}
task staticSiteCreate(type: DockerCreateContainer) {
dependsOn staticImage
targetImageId { staticImage.getImageId() }
portBindings = ['80']
}
task staticSiteStart(type: DockerStartContainer) {
dependsOn staticSiteCreate
targetContainerId { staticSiteCreate.getContainerId() }
}
task staticSiteRemove(type: DockerRemoveContainer) {
dependsOn staticSiteCreate
targetContainerId { staticSiteCreate.getContainerId() }
force = true
}
task staticSiteS3Publish(type: SyncTask) {
dependsOn ':staticsite:generate', ':staticsite:htmlSanityCheck'
bucketName System.getenv('STATIC_BUCKET')
source project(':staticsite').file('target')
}
task testReportPublish(type: SyncTask) {
dependsOn test
bucketName System.getenv('ARTIFACT_BUCKET')
source file("${project.buildDir}/reports")
prefix "artifacts/${System.getenv('CODEBUILD_BUILD_ID')}/reports/"
}
/*
* ECS Artifacts
*/
task ecsImageDefinitions {
group = "Deployment"
description = "Generate AWS ECS imagedefinitions.json file for AWS CodeDeploy"
doFirst {
def data = [
[
name: 'app',
imageUri: webappImage.tags.first(),
],
/*
[
name: 'static-site',
imageUri: staticImage.tags.first(),
]
*/
]
new File("${project.buildDir}/imagedefinitions.json").text = JsonOutput.toJson(data)
}
}
dependencyCheck {
format='ALL'
}