-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtasks.gincl
More file actions
966 lines (773 loc) · 32.3 KB
/
Copy pathtasks.gincl
File metadata and controls
966 lines (773 loc) · 32.3 KB
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
import org.apache.tools.ant.filters.ReplaceTokens
apply plugin: 'war'
/**--------------------------- util classes ---------------------------------**/
/**
* this is used by loadConfig to extract the information from a script into a properties object.
*/
class ClosureScript extends groovy.lang.Script {
Closure closure
def run() {
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.delegate = this
closure.call()
}
}
class ConfigRepo {
def baseConf
def envConf
ConfigRepo() {
baseConf = new Properties()
envConf = new Properties()
}
ConfigRepo(baseConf, envConf) {
this.baseConf = baseConf
this.envConf = envConf
}
static final ConfigRepo parse(env, source) {
source = source instanceof File ? source.toURL() : source instanceof Closure ? new ClosureScript(closure: source) : source
def baseConf = new ConfigSlurper().parse(source).toProperties()
def envConf = new ConfigSlurper(env).parse(source).toProperties()
baseConf.each{ k, v ->
if (envConf.get(k).equals(v)) {
envConf.remove(k)
}
}
return new ConfigRepo(baseConf, envConf)
}
Properties flatten() {
def props = new Properties()
props.putAll(baseConf)
props.putAll(envConf)
return props
}
void merge(configRepo) {
baseConf.putAll(configRepo.baseConf)
envConf.putAll(configRepo.envConf)
}
}
/**--------------------------- utils ---------------------------------**/
task loadConfig {
description= 'Load build and app config files. Also, setup common properties like build_date, build_time, etc.'
group = MISC_GROUP
project.ext.build_time = new Date().toString()
project.ext.build_date = new Date().format("yyyy-MM-dd")
doLast {
project.ext["env"] = project.hasProperty("env") ? project.env : "local"
println ">> Environment is set to $project.env"
ConfigRepo configRepo = new ConfigRepo();
if (file("$rootDir/config/app.config").exists()) {
configRepo.merge(ConfigRepo.parse(project.env, file("$rootDir/config/app.config")))
}
if (project.hasProperty("appConfig")) {
configRepo.merge(ConfigRepo.parse(project.env, project.appConfig))
}
def props = configRepo.flatten();
// props.each{ k, v -> println "!!! ${k} => ${v}" }
if (file("$rootDir/buildScript/build.config").exists()) {
ConfigRepo.parse(project.env, file("$rootDir/buildScript/build.config"))
.flatten().each { k, v -> props.put(k,v)}
}
if (file("$gradle.gradleUserHomeDir/build.config").exists()) {
logger.info ">> loading user's build.config for env: $project.env"
ConfigRepo.parse(project.env, file("$gradle.gradleUserHomeDir/build.config"))
.flatten().each { k, v -> props.put(k,v)}
}
System.getenv().each { k,v ->
props.put(k,v)
}
project.ext.properties.each { k,v ->
props.put(k, String.valueOf(v))
}
if (!props.hasProperty('tomcat_home')) {
props.put('tomcat_home', System.getenv('CATALINA_BASE') ?: System.getenv('CATALINA_HOME') ?: '')
}
project.ext.appConfigProps = props
// project.ext.appConfigProps.each{ k, v -> println "!!!!!! ${k} => ${v}" }
}
}
task createVersionTag {
description = 'Creates version info used for tagging as well as build label.'
group = MISC_GROUP
dependsOn loadConfig
doLast {
// generate version tag
def major = appConfigProps.get('BuildMajor')
def minor = appConfigProps.get('BuildMinor')
def rev = appConfigProps.get('BuildRev')
def type = appConfigProps.get('BuildType')
def buildNum = appConfigProps.get('BuildNumber')
def branchOverride = appConfigProps.get('BranchOverride')
def tag = "${project['app-name']}_$major.$minor.${rev}_${type}-$buildNum"
def props = new Properties()
file(project.buildDir).mkdirs()
props.setProperty('BuildMajor', major)
props.setProperty('BuildMinor', minor)
props.setProperty('BuildRev', rev)
props.setProperty('BuildType', type)
props.setProperty('BuildNumber', buildNum)
props.setProperty('BuildDate', build_date)
props.setProperty('BuildTime', build_time)
props.setProperty('BuildTag', tag)
props.setProperty('BuildCommit', getCommitHash())
props.setProperty('BuildFireflyTag', getCommitTag(fireflyPath))
props.setProperty('BuildFireflyBranch', branchOverride ?: getBranch(fireflyPath))
props.setProperty('DevCycleTag', getDevCycleTag(fireflyPath, "unknown"))
props.setProperty('ExtendedCache', project.env == "local" ? (project.hasProperty("ExtendedCache") ? project.ExtendedCache : "true") : "false")
if (fireflyPath != rootDir.getPath()) {
props.setProperty('BuildCommitFirefly', getCommitHash(fireflyPath))
}
props.store(file("${project.buildDir}/version.tag").newWriter(), "Version Info")
}
}
task prepareWebapp (dependsOn: [loadConfig, createVersionTag, jar]) {
description= 'Generates the configuration files needed by the webapp, ie. app.prop, web.xml, etc.'
group = MISC_GROUP
doFirst {
// copy the content of html to war
copy {
from ("html/") { include '**/*' }
into warDir
}
copy {
from configurations.webappLib
into "${warDir}/WEB-INF/lib"
}
// temporary solution to extract fits_io.jar into WEB-INF/classes directory
// this fix the multiple nom.tam.fits issue
// copy {
// from zipTree(file("$fireflyPath/jars/fits-io/fits_io.jar"))
// into "${warDir}/WEB-INF/classes"
// }
//
copy {
from ('config') {exclude "web.xml"}
from ("${project.buildDir}/version.tag")
from ("$rootDir/config/") { include '*.prop' }
into("${warDir}/WEB-INF/config")
filter(ReplaceTokens, tokens: project.appConfigProps)
}
copy {
from("$rootDir/config/") {include '*.properties'}
into("${warDir}/WEB-INF/classes")
filter(ReplaceTokens, tokens: project.appConfigProps)
}
copy {
from("$rootDir/config") {include 'web.xml'}
from('config') {include 'web.xml'}
into("${warDir}/WEB-INF")
filter(ReplaceTokens, tokens: project.appConfigProps)
}
copy {
from("html/") { include "*.html"}
into(warDir)
filter(ReplaceTokens, tokens: project.appConfigProps)
}
// additional filter for these ehcache config files to handle replication or not
copy {
from ("$fireflyPath/config/") { include '*ehcache.xml', 'ignore_sizeof.txt' }
into("${warDir}/WEB-INF/config")
filter(ReplaceTokens, tokens: project.appConfigProps)
filter { line -> project.appConfigProps["ehcache.replicate"]?.toBoolean() ? line.replaceAll('<!--REPLICATE|REPLICATE-->', '') : line }
}
// to avoid storing multiple copies of plotly library under project html
// copy minimized plotly from firefly
// plotly script load fails if loaded from amd environment
// with a script tag (as firefly loads it)
// see DM-11341 for details
copy {
from ("$fireflyPath/src/firefly/html/") {
include 'gpu-browser*min*.js'
}
into warDir
filter { line -> line.replaceAll('\\&\\&define\\.amd', '\\&\\&false')} // instead of ant.replaceregexp to preserve file permission
}
}
}
task createTag(dependsOn: loadConfig) {
description = 'Create and push a tag to remote repo. Optional properties: ${tag_name}, ${tag_file} if ${tag_name} is missing. defaults to build/version.tag, ${tag_remote} defaults to origin, ${tag_message}.'
group = MISC_GROUP
doLast {
def tag = project.getVersionInfo('BuildTag');
println "tag: $tag"
exec {
executable 'git'
args 'tag'
args '-a'
args tag
args '-m'
if (project.hasProperty("tag_message")) {
args tag_message
} else {
args 'not given'
}
}
exec {
executable 'git'
args 'push'
if (project.hasProperty("tag_remote")) {
args tag_remote
} else {
args 'origin'
}
args tag
}
}
}
task deploy (dependsOn: [loadConfig]) {
description= 'Deploy webapp(war file) to Tomcat. Require ${tomcat_home} property'
group = MAIN_GROUP
doLast {
def tomcat_home = appConfigProps.get("tomcat_home")
if (!file(tomcat_home).exists()) {
throw ProjectConfigurationException("Tomcat installation directory does not exists: $tomcat_home")
}
def warFile = "${war.destinationDirectory.get()}/${webapp.baseWarName}.war"
if (!file(warFile).exists()) {
println ">> $warFile not found. Skipping deploy."
throw new StopExecutionException("$warFile not found. Skipping deploy.")
}
copy {
println ">> deploying file:$warFile"
delete("$tomcat_home/webapps/${webapp.baseWarName}")
from(warFile)
into "$tomcat_home/webapps/"
}
}
}
task checkoutFirefly (dependsOn: [loadConfig]) {
description= 'this task will checkout firefly to a given tag/branch'
group = MISC_GROUP
doLast {
def tag_name = appConfigProps.get('firefly.tag.name')
if (tag_name == null) {
def fireflyTagFile = appConfigProps.get('firefly.tag.file')
if (fireflyTagFile != null) {
tag_name = file(fireflyTagFile).text.trim()
}
}
if (tag_name == null || tag_name.length() == 0) {
throw new GradleException("Unable to resolve tag/branch name. Tag can be defined as a 'firefly.tag.name' property or in a file referenced by a 'firefly.tag.file' property")
}
doExec fireflyPath, 'git', 'checkout', tag_name
doExec fireflyPath, 'git', 'reset', '--hard'
}
}
/**---------------------------- test ---------------------------------**/
task jsTest (dependsOn: [loadConfig]) {
group = DEV_GROUP
doLast {
if (file("package.json").exists()) {
println ">> running JavaScript test..."
def res = project.NODE 'yarn', 'run', 'test-unit'
if (res.getExitValue() != 0) {
throw new GradleException("JavaScript test fail.")
}
}
}
}
test {
description= ''' Run Java and JavaScript unit test
Only JS test:
gradle :firefly:jsTest
Only java test:
gradle :firefly:test -x jsTest
Specific test(s):
gradle :firefly:test -x jsTest --tests <class-name-pattern>
Example: gradle :firefly:test -x jsTest --tests *HttpServicesTest
Specific category:
gradle -Pcategory=edu.caltech.ipac.TestCategory\\$Perf :firefly:test -x jsTest
Debug a specific test:
gradle :firefly:test --debug-jvm --tests <class-name-pattern> '''
group = DEV_GROUP
dependsOn prepareWebapp, jsTest
// should rerun this everytime. properties could be modified from external files.
outputs.upToDateWhen { false }
workingDir = rootDir
// explicitly include or exclude tests
include 'edu/**'
environment 'contextPath': "/${project['app-name']}"
environment 'contextName': project['app-name']
environment 'webappConfigPath': "${project.warDir}/WEB-INF/config/"
reports.junitXml.destination = file("$distDir/reports/${project['app-name']}/xml")
reports.html.destination = file("$distDir/reports/${project['app-name']}/html")
if (project.hasProperty("category")) {
if (project.category) {
logger.lifecycle("Running test for category: " + project.category)
useJUnit {
includeCategories project.category
}
}
} else {
useJUnit {
excludeCategories 'edu.caltech.ipac.TestCategory$Perf', 'edu.caltech.ipac.TestCategory$Integration'
}
}
// show standard out and standard error of the test JVM(s) on the console
testLogging.showStandardStreams = true
// set heap size for the test JVM(s)
minHeapSize = "128m"
maxHeapSize = "2g"
jvmArgs '-Djava.net.preferIPv4Stack=true'
doFirst {
copy {
from ("${fireflyPath}/config/test")
into "${warDir}/WEB-INF/config"
}
}
// listen to events in the test execution lifecycle
beforeTest { descriptor ->
logger.lifecycle("Running test: " + descriptor)
}
}
task jsTestDebug (dependsOn: [loadConfig]) {
group = DEV_GROUP
doLast {
if (file("package.json").exists()) {
println ">> running JavaScript test in debug mode..."
def res = project.NODE 'yarn', 'run', 'test-debug'
if (res.getExitValue() != 0) {
throw new GradleException("JavaScript test fail.")
}
}
}
}
task init () {
group = DEV_GROUP
doLast {
project.InitNode(rootDir)
}
}
/**----------------------------- docs ---------------------------------**/
task buildJsDoc (dependsOn: loadConfig) {
description= 'Build JSDoc.'
group = SUB_GROUP
def outdir = warDir
outputs.dir outdir
inputs.dir "${projectDir}"
inputs.dir "${fireflyPath}/docs"
inputs.dir "${fireflyPath}/src/firefly"
doLast {
// copy sources to jsdocs build directory
copy {
from ("${fireflyPath}/src/firefly") {include "js/**"}
from ("${fireflyPath}/src/firefly/jsdoc_config.json")
into "${project.buildDir}/jsdocs/"
}
// copy md files to jsdocs build directory replacing .md links to tutorial
copy {
from ("${fireflyPath}") {include "docs/*"}
into "${project.buildDir}/jsdocs/"
filter{
// replace md's link to point to docstrap's tutorial. ie [a link](a_file.md) -> [a link](tutorial-a_file.html)
String line -> line.replaceAll("(\\[.+\\])\\s*\\((.*)\\.md\\)", "\$1(tutorial-\$2.html)")
}
}
// setup tutorials
copy {
from ("${fireflyPath}/docs") {
include 'firefly-api-code-examples.md', 'firefly-external-task-launcher.md', 'fits-plotting-parameters.md'
}
into "${project.buildDir}/jsdocs/tutorial"
filter{
// replace md's link to point to docstrap's tutorial. ie [a link](a_file.md) -> [a link](tutorial-a_file.html)
String line -> line.replaceAll("(\\[.+\\])\\s*\\((.*)\\.md\\)", "\$1(tutorial-\$2.html)")
}
}
// copy files referenced by files in ./docs
copy {
from ("${fireflyPath}/docs") {
include 'firefly-api-code-examples.md', 'fits-plotting-parameters.md'
}
into "${outdir}/docs/js"
}
if (!file("jsdoc_config.json").exists()) {
println ">> jsdoc_config.json not found. Skipping buildJsDoc."
throw new StopExecutionException("jsdoc_config.json not found. Skipping buildJsDoc.")
}
def res = exec {
workingDir = "${project.buildDir}/jsdocs/"
commandLine "${fireflyPath}/node_modules/.bin/jsdoc", '-c', "${project.buildDir}/jsdocs/jsdoc_config.json", '-d', "${outdir}/docs/js"
}
if (res.getExitValue() != 0) {
throw new GradleException("Fail to build Client")
}
}
}
task publishJsDocs (dependsOn: loadConfig) {
description = 'Publish js docs to firefly.lsst.io'
group = SUB_GROUP
def docsDir = "${warDir}/docs/js"
doLast {
def res = project.publishDocs docsDir, 'firefly'
if (res.getExitValue() != 0) {
throw new GradleException("Fail to publishJsDoc")
}
}
}
task publishPythonDocs (dependsOn: loadConfig) {
description = 'Publish python docs to firefly_client.lsst.io'
group = SUB_GROUP
def docsDir = "${warDir}/docs/python"
doLast {
def res = project.publishDocs docsDir, 'firefly_client'
if (res.getExitValue() != 0) {
throw new GradleException("Fail to publishJsDoc")
}
}
}
/**--------------------------- docker ---------------------------------**/
task dockerImage (dependsOn: loadConfig) {
description = 'Create a docker image'
group = DOCKER_GROUP
ext.docker_repo = "ipac/firefly"
ext.docker_registry = ''
ext.docker_tag = 'latest'
ext.copy_res = true
doLast {
// copy artifacts to staging directory
if (copy_res) {
copy {
from ("${project.distDir}") { include '*.war' }
from ("${fireflyPath}/docker") {
include '*'
exclude 'Dockerfile.dockerignore'
}
into "${project.buildDir}/docker"
rename ('Dockerfile.orig','Dockerfile')
}
}
try {
"docker --version".execute()
} catch (Exception e) {
println ">> docker is not installed. This task required docker"
throw new GradleException("docker is not installed. This task required docker", e)
}
if (!file("${project.buildDir}/docker/Dockerfile").exists()) {
println ">> Dockerfile not found. Fail to create docker image"
throw new GradleException("Dockerfile not found. Fail to create docker image")
}
docker_repo = project.appConfigProps.docker_repo ?: docker_repo
docker_registry = project.appConfigProps.docker_registry ?: docker_registry
docker_registry = docker_registry == '' || docker_registry.endsWith('/') ? docker_registry : docker_registry + '/'
def docker_build_args = "--build-arg IMAGE_NAME=${docker_registry}${docker_repo}"
def res = exec {
workingDir "${project.buildDir}/docker"
commandLine "docker build --pull -t ${docker_registry}${docker_repo}:${docker_tag} ${docker_build_args} .".split(' ')
}
if (res.getExitValue() != 0) {
throw new GradleException("Fail to create docker image")
}
return res;
}
}
task dockerPublish (dependsOn: dockerImage) {
description = ''' Create a docker image. Build war file(s) first before running this task
Example: gradle -Pdocker_tag=<tag name> :firefly:dockerPublish
Options:
docker_repo : defaults to "ipac/firefly”
docker_registry : defaults to dockerhub
docker_tag : defaults to "latest"
docker_user : picked up from ~/.gradle/build.config or passed in
docker_passwd : picked up from ~/.gradle/build.config or passed in '''
group = DOCKER_GROUP
doLast {
try {
"docker --version".execute()
} catch (Exception e) {
println ">> docker is not installed. This task required docker"
throw new GradleException("docker is not installed. This task required docker", e)
}
if (project.appConfigProps.docker_user != '') {
def proc = "docker login --username ${project.appConfigProps.docker_user} --password ${project.appConfigProps.docker_passwd}".execute()
proc.waitForOrKill(10000)
println ">> docker login as ${project.appConfigProps.docker_user} with exit status ${proc.exitValue()}"
}
def docker_repo = project.appConfigProps.docker_repo ?: dockerImage.docker_repo
def docker_tag = project.appConfigProps.docker_tag ?: dockerImage.docker_tag
def docker_registry = project.appConfigProps.docker_registry ?: dockerImage.docker_registry
docker_registry = docker_registry == '' || docker_registry.endsWith('/') ? docker_registry : docker_registry + '/'
def docker_tags = docker_tag.split(',')
def res = ''
for (tag in docker_tags){
exec {
workingDir "${project.buildDir}/docker"
commandLine "docker tag ${docker_repo}:${dockerImage.docker_tag} ${docker_repo}:${tag}".split(' ')
}
res = exec {
workingDir "${project.buildDir}/docker"
commandLine "docker push ${docker_repo}:${tag}".split(' ')
}
if (res.getExitValue() != 0) {
throw new GradleException("Fail to push docker image")
}
}
return res;
}
}
task dockerDelete (dependsOn: loadConfig){
description = ''' Delete a docker image from docker hub.
Example: gradle -Pdocker_tag=<tag name> :firefly:dockerDelete '''
group = DOCKER_GROUP
ext.docker_repo = "ipac/firefly"
ext.docker_registry = "https://hub.docker.com/v2/repositories" //Docker registry defaults to Docker Hub. In case this needs to change, then either change this value here, or using 'project.appConfigProps'
doLast {
try {
"docker --version".execute()
} catch (Exception e) {
println ">> docker is not installed. This task required docker"
throw new GradleException("docker is not installed. This task required docker", e)
}
if (project.appConfigProps.docker_user != '') {
def proc = "docker login --username ${project.appConfigProps.docker_user} --password ${project.appConfigProps.docker_passwd}".execute()
proc.waitForOrKill(10000)
println ">> docker login as ${project.appConfigProps.docker_user} with exit status ${proc.exitValue()}"
}
docker_repo = project.appConfigProps.docker_repo ?: docker_repo
docker_registry = project.appConfigProps.docker_registry ?: docker_registry
docker_registry = docker_registry == '' || docker_registry.endsWith('/') ? docker_registry : docker_registry + '/'
//Authentication: getting auth token.
def post = new URL("https://hub.docker.com/v2/users/login/").openConnection();
def data = '{"username":"'+ docker_user+'", "password":"'+ docker_passwd+'"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(data.getBytes("UTF-8"));
if(post.getResponseCode().equals(200)) {
def response = post.getInputStream().getText();
def authToken = response.substring(11,response.length()-3)
//DELETE Restful call:
def str = "${docker_registry}${docker_repo}/tags/${docker_tag}/"
def conn = new URL(str).openConnection();
conn.setRequestMethod("DELETE")
conn.setDoOutput(true)
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
conn.setRequestProperty("Authorization", "JWT " + authToken)
conn.connect()
if(conn.getResponseCode() >= 400) {
throw new GradleException("Fail to delete docker image, using URL: ${str}\n Exception: ${conn.getResponseCode()}:${conn.getResponseMessage()}")
}
}else{
throw new GradleException("Failed to obtain authentication token!")
}
}
}
task onlinehelp () {
description = 'Bundled onlinehelp with the webapp'
group = SUB_GROUP
ext.onlineHelpDir = null
doLast {
if (onlineHelpDir != null) {
exec {
workingDir onlineHelpDir
commandLine "gradle -PaltBuildDir=${buildDir}/war/onlinehelp ${project["app-name"]}:build".split(" ")
}
}
}
}
/**-------------------------------------- misc ----------------------------------**/
task testJar(type: Jar, dependsOn: testClasses) {
archiveFileName = "test-${project.archivesBaseName}.jar"
from sourceSets.test.output
destinationDirectory = file ("$rootDir/jars/build")
}
def getReleaseTitle() {
def major = appConfigProps.get('BuildMajor')
def minor = appConfigProps.get('BuildMinor')
def rev = appConfigProps.get('BuildRev')
def type = appConfigProps.get('BuildType')
def prefix = project.hasProperty("rel_prefix") ? "${rel_prefix} " : ""
def label = prefix + "v${major}.${minor}.${rev} ${type}"
return label;
}
task publishToGithub (dependsOn: loadConfig) {
description = 'Publish the built artifacts as a GitHub release.'
group = SUB_GROUP
outputs.upToDateWhen { false }
doLast {
def tag = project.getVersionInfo('BuildTag');
def rel_title = getReleaseTitle();
try {
def process = "node -v".execute()
} catch (Exception e) {
println ">> Task failed due to missing node.js"
throw new GradleException(">> Task failed due to missing node.js", e)
}
def relConfig = sprintf("""
|{ "tag": "%s",
| "token": "%s",
| "name": "%s",
| "assets": ["%s", "%s"]
|}
""".stripMargin(),
tag,
project.property("github.auth.token"),
rel_title,
"${project.buildDir}/exec/${webapp.baseWarName}-exec.war", "${project.buildDir}/exec/${webapp.baseWarName}.war")
def res = exec {
environment 'NODE_PATH': "${fireflyPath}/node_modules"
executable "node"
args "${fireflyPath}/buildScript/publish-to-github.js", relConfig
}
if (res.getExitValue() != 0) {
throw new GradleException("Fail to build publish to Github.")
}
}
}
/**-------------------------------------- main ----------------------------------**/
task buildClient (dependsOn: [loadConfig, createVersionTag]) {
description= 'Build JavaScript portion of the application.'
group = SUB_GROUP
outputs.dir warDir
inputs.dir "${projectDir}/js"
inputs.dir "${fireflyPath}/src/firefly/js"
doLast {
if (!file("webpack.config.js").exists()) {
println ">> webpack.config.js not found. Skipping buildClient."
throw new StopExecutionException("webpack.config.js not found. Skipping buildClient.")
}
def res = project.NODE 'yarn', 'run', 'build', "--env", "baseWarName=${webapp.baseWarName}", "--env", "app-name=${project["app-name"]}"
if (res.getExitValue() != 0) {
throw new GradleException("Fail to build Client")
}
}
}
task warAll( dependsOn:[war, buildJsDoc, onlinehelp] ) {
description= 'Build the war file with JSDoc generated.'
group = MAIN_GROUP
}
task buildAndDeploy( dependsOn:[war, deploy] ) {
description= 'Build the war file and then deploy it to a local tomcat server if successful. Property ${tomcat_home} is required'
group = MAIN_GROUP
}
task buildAllAndDeploy( dependsOn:[warAll, deploy] ) {
description= 'Run test and docs first, then build the war file. Deploy it to a local tomcat server if successful. Property ${tomcat_home} is required'
group = MAIN_GROUP
}
task webapp {
description= 'Used to define or override a webapp specific attributes, for example name of the war file.'
dependsOn buildClient, prepareWebapp
outputs.upToDateWhen { false }
ext.baseWarName = jar.archiveBaseName.get()
}
task buildAndPublish( dependsOn: war ) {
description= 'Build the war file and then publish it to a remote host. Property ${publish_host} is required.'
group = MAIN_GROUP
doLast {
if (!file(war.archivePath).exists()) {
throw new StopExecutionException("$war.archivePath not found. Skipping sendArtifacts.")
}
if (!project.hasProperty("publish_host")) {
throw new StopExecutionException("publish_host not found. Skipping sendArtifacts.")
}
def rhost = project.property("publish_host")
def reposRoot = "/hydra/repos/${project['app-name']}"
def major = appConfigProps.get('BuildMajor')
def minor = appConfigProps.get('BuildMinor')
def rev = appConfigProps.get('BuildRev')
def buildNum = appConfigProps.get('BuildNumber')
def dirName = "v$major.$minor.$rev.$buildNum"
exec {
commandLine "ssh", "$rhost", "mkdir -p $reposRoot/$dirName/"
}
exec {
commandLine "scp", "$war.archivePath", "$rhost:$reposRoot/$dirName/"
}
exec {
commandLine "ssh", "$rhost", "cd $reposRoot; rm current; ln -s $dirName current"
}
}
}
task devMode (dependsOn: createVersionTag) {
description= 'JavaScript Dev Mode'
group = DEV_GROUP
outputs.upToDateWhen { false }
doLast {
def res = project.NODE 'yarn', 'run', 'dev', "--env", "baseWarName=${webapp.baseWarName}", "--env", "app-name=${project["app-name"]}"
if (res.getExitValue() == 0) {
throw new GradleException("Fail to run dev mode")
}
}
}
//-------------------------
// define task order
//-------------------------
buildClient.mustRunAfter loadConfig
prepareWebapp.mustRunAfter buildClient
buildJsDoc.mustRunAfter buildClient
onlinehelp.mustRunAfter buildJsDoc
war.mustRunAfter onlinehelp
deploy.mustRunAfter war
/**---------------------------------------------------------------------------------------------**/
/** Below are tasks for deployAllWars used by Jenkins to redeploy app to local and remote hosts **/
/**---------------------------------------------------------------------------------------------**/
def stopTomcat(remoteHost) {
def desc = execCmd (remoteHost, true, ["/etc/init.d/tomcat_init", "stop"])
println ">> Stopping Tomcat:.. $desc"
}
def startTomcat(remoteHost) {
def cmd = ["/etc/init.d/tomcat_init", "start"];
// if (project.hasProperty("tomcatDebugStart") && project.tomcatDebugStart == 'true') {
// cmd = cmd + "jpda"
// }
def desc = execCmd (remoteHost, false, cmd)
println ">> Starting Tomcat:.. $cmd ==> $desc"
}
task deployAllWars(dependsOn: loadConfig) {
description= 'Deploy all of the built war files to Tomcat. Require ${tomcat_home} property. May include ${remoteHost} as well.'
group = MISC_GROUP
doLast {
if (!project.hasProperty("tomcat_home")) {
throw ProjectConfigurationException("tomcat_home property is not found.")
}
def remoteHosts = project.hasProperty("remoteHost") ? remoteHost.split(",") : [null]
for (rhost in remoteHosts) {
println ">> deploying to host: $rhost"
// stop tomcat
stopTomcat(rhost)
execCmd(rhost, true, ["rm", "-r", "$tomcat_home/temp/ehcache"])
// copy all of the war files
def wars = fileTree(dir: "${project.distDir}", include: '*.war')
wars.each { File file ->
copyWar(file, rhost)
}
// start tomcat
startTomcat(rhost)
}
}
}
def copyWar(file, remoteHost) {
println ">> copying file: $file"
def baseName = file.name.tokenize('.')[0]
execCmd(remoteHost, true, ["rm", "-r","$tomcat_home/webapps/$baseName"])
if (remoteHost != null) {
exec {
executable "scp"
args "$file"
args "$remoteHost:/$tomcat_home/webapps/"
}
} else {
copy {
from("$file")
into "$tomcat_home/webapps/"
}
}
}
def execCmd(remoteHost, ignoreFailure, cmdLine) {
exec {
setIgnoreExitValue(ignoreFailure)
executable "ssh"
if (remoteHost != null) {
args "$remoteHost"
} else {
args "localhost"
}
cmdLine.each { arg ->
if (arg.contains("#")) {
args arg.replaceAll('\\#', '\\\\#')
} else {
args arg
}
}
logger.info( ">> execCmd: $commandLine" )
}
}