forked from OpenLiberty/ci.gradle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevTask.groovy
More file actions
1700 lines (1462 loc) · 81.8 KB
/
Copy pathDevTask.groovy
File metadata and controls
1700 lines (1462 loc) · 81.8 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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* (C) Copyright IBM Corporation 2019, 2026.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.openliberty.tools.gradle.tasks
import groovy.xml.XmlParser
import io.openliberty.tools.ant.ServerTask
import io.openliberty.tools.common.plugins.util.BinaryScannerUtil
import io.openliberty.tools.common.plugins.util.DevUtil
import io.openliberty.tools.common.plugins.util.InstallFeatureUtil
import io.openliberty.tools.common.plugins.util.JavaCompilerOptions
import io.openliberty.tools.common.plugins.util.LibertyPropFilesUtility
import io.openliberty.tools.common.plugins.util.PluginExecutionException
import io.openliberty.tools.common.plugins.util.PluginScenarioException
import io.openliberty.tools.common.plugins.util.ProjectModule
import io.openliberty.tools.common.plugins.util.ServerFeatureUtil
import io.openliberty.tools.common.plugins.util.ServerFeatureUtil.FeaturesPlatforms
import io.openliberty.tools.common.plugins.util.ServerStatusUtil
import io.openliberty.tools.gradle.utils.CommonLogger
import io.openliberty.tools.gradle.utils.DevTaskHelper
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.internal.file.DefaultFilePropertyFactory
import org.gradle.api.logging.LogLevel
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.testfixtures.ProjectBuilder
import org.gradle.tooling.BuildException
import org.gradle.tooling.BuildLauncher
import org.gradle.tooling.GradleConnector
import org.gradle.tooling.ProjectConnection
import java.nio.file.Path
import java.util.Map.Entry
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
class DevTask extends AbstractFeatureTask {
private static final String LIBERTY_HOSTNAME = "liberty.hostname";
private static final String LIBERTY_HTTP_PORT = "liberty.http.port";
private static final String LIBERTY_HTTPS_PORT = "liberty.https.port";
private static final String MICROSHED_HOSTNAME = "microshed_hostname";
private static final String MICROSHED_HTTP_PORT = "microshed_http_port";
private static final String MICROSHED_HTTPS_PORT = "microshed_https_port";
private static final String WLP_USER_DIR_PROPERTY_NAME = "wlp.user.dir";
private static final String GEN_FEAT_LIBERTY_DEP_WARNING = "Liberty feature dependencies were detected in the build.gradle file and automatic generation of features is [On]. " +
"Automatic generation of features does not support Liberty feature dependencies. " +
"Remove any Liberty feature dependencies from the build.gradle file or disable automatic generation of features by typing 'g' and press Enter.";
DevTask() {
configure({
description = 'Runs a Liberty server in dev mode'
group = 'Liberty'
})
}
@Optional
@Input
DevTaskUtil util = null;
// Default DevMode argument values
// DevMode uses CLI Arguments if provided, otherwise it uses ServerExtension properties if one exists, fallback to default value if neither are provided.
private static final int DEFAULT_VERIFY_TIMEOUT = 30;
private static final int DEFAULT_SERVER_TIMEOUT = 90;
private static final double DEFAULT_COMPILE_WAIT = 0.5;
private static final int DEFAULT_DEBUG_PORT = 7777;
private static final boolean DEFAULT_HOT_TESTS = false;
private static final boolean DEFAULT_SKIP_TESTS = false;
private static final boolean DEFAULT_LIBERTY_DEBUG = true;
private static final boolean DEFAULT_POLLING_TEST = false;
private static final boolean DEFAULT_CONTAINER = false;
private static final boolean DEFAULT_SKIP_DEFAULT_PORTS = false;
private static final boolean DEFAULT_KEEP_TEMP_CONTAINERFILE = false;
private static final boolean DEFAULT_GENERATE_FEATURES = false;
private static final boolean DEFAULT_SKIP_INSTALL_FEATURE = false;
private static final boolean DEFAULT_CHANGE_ON_DEMAND_TESTS_ACTION = false;
// Debug port for BuildLauncher tasks launched from DevTask as parent JVM
// (parent defaults to '5005')
private Integer childDebugPort = null; // cache
private static final int DEFAULT_CHILD_DEBUG_PORT = 6006;
protected final String CONTAINER_PROPERTY_ARG = '-P'+CONTAINER_PROPERTY+'=true';
private Boolean changeOnDemandTestsAction;
@Option(option = 'changeOnDemandTestsAction', description = 'If this option is enabled, change the action for running on demand tests from Enter to type t and press Enter. The default value is false.')
void setChangeOnDemandTestsAction(boolean changeOnDemandTestsAction) {
this.changeOnDemandTestsAction = changeOnDemandTestsAction;
project.liberty.dev.changeOnDemandTestsAction = this.changeOnDemandTestsAction;
}
private Boolean hotTests;
@Option(option = 'hotTests', description = 'If this option is enabled, run tests automatically after every change. The default value is false.')
void setHotTests(boolean hotTests) {
this.hotTests = hotTests;
}
private Boolean skipTests;
@Option(option = 'skipTests', description = 'If this option is enabled, do not run any tests in dev mode. The default value is false.')
void setSkipTests(boolean skipTests) {
this.skipTests = skipTests;
}
@Optional
@Input
Boolean libertyDebug;
// Need to use a string value to allow someone to specify --libertyDebug=false
// bool @Options only allow you to specify "--libertyDebug" or nothing.
// So there is no way to explicitly set libertyDebug to false if we want the default behavior to be true
@Option(option = 'libertyDebug', description = 'Whether to allow attaching a debugger to the running server. The default value is true.')
void setLibertyDebug(String libertyDebug) {
this.libertyDebug = Boolean.parseBoolean(libertyDebug)
}
@Optional
@Input
Integer libertyDebugPort;
@Option(option = 'libertyDebugPort', description = 'The debug port that you can attach a debugger to. The default value is 7777.')
void setLibertyDebugPort(String libertyDebugPort) {
try {
this.libertyDebugPort = Integer.valueOf(libertyDebugPort);
} catch (NumberFormatException e) {
logger.error(String.format("Unexpected value: %s for dev mode option libertyDebugPort. libertyDebugPort should be a valid integer.", libertyDebugPort));
throw e;
}
}
private Double compileWait;
@Option(option = 'compileWait', description = 'Time in seconds to wait before processing Java changes and deletions. The default value is 0.5 seconds.')
void setCompileWait(String compileWait) {
try {
this.compileWait = Double.valueOf(compileWait);
} catch (NumberFormatException e) {
logger.error(String.format("Unexpected value: %s for dev mode option compileWait. compileWait should be a valid number.", compileWait));
throw e;
}
}
private Integer verifyAppStartTimeout;
@Option(option = 'verifyAppStartTimeout', description = 'Maximum time to wait (in seconds) to verify that the application has started or updated before running tests. The default value is 30 seconds.')
void setVerifyAppStartTimeout(String verifyAppStartTimeout) {
try {
this.verifyAppStartTimeout = Integer.valueOf(verifyAppStartTimeout);
} catch (NumberFormatException e) {
logger.error(String.format("Unexpected value: %s for dev mode option verifyAppStartTimeout. verifyAppStartTimeout should be a valid integer.", verifyAppStartTimeout));
throw e;
}
}
private Integer serverStartTimeout;
@Option(option = 'serverStartTimeout', description = 'Time in seconds to wait while verifying that the server has started. The default value is 90 seconds.')
void setServerStartTimeout(String serverStartTimeout) {
try {
this.serverStartTimeout = Integer.valueOf(serverStartTimeout);
} catch (NumberFormatException e) {
logger.error(String.format("Unexpected value: %s for dev mode option serverStartTimeout. serverStartTimeout should be a valid integer.", serverStartTimeout));
throw e;
}
}
private Boolean pollingTest;
@Option(option = 'pollingTest', description = 'This option is only for testing dev mode using polling to track file changes instead of using file system notifications. The default value is false, in which case dev mode will rely on file system notifications but will automatically fall back to polling if file system notifications are not available.')
void setPollingTest(boolean pollingTest) {
this.pollingTest = pollingTest;
}
@Optional
@Input
private Boolean container = null;
@Option(option = 'container', description = 'Run the server in a container instead of locally. The default value is false for the libertyDev task, and true for the libertyDevc task.')
void setContainer(boolean container) {
this.container = container;
project.liberty.dev.container = container; // Needed in DeployTask and AbstractServerTask
}
Boolean getContainer() {
return container;
}
private File containerfile;
@Option(option = 'containerfile', description = 'Dev mode will build a container image from the provided Containerfile/Dockerfile and start a container from the new image.')
void setContainerfile(String containerfile) {
if (containerfile != null) {
// ensures the containerfile is defined with the full path - matches how maven behaves
this.containerfile = convertParameterToCanonicalFile(containerfile, "containerfile");
project.liberty.dev.containerfile = this.containerfile;
}
}
private File dockerfile;
@Option(option = 'dockerfile', description = 'Alias for containerfile')
void setDockerfile(String dockerfile) {
if (dockerfile != null && containerfile == null) {
setContainerFile(dockerfile)
}
}
private File containerBuildContext;
@Option(option = 'containerBuildContext', description = 'The container build context used when building the container in dev mode. Defaults to the directory of the Containerfile/Dockerfile if not specified.')
void setContainerBuildContext(String containerBuildContext) {
if (containerBuildContext != null) {
// ensures the containerBuildContext is defined with the full path - matches how maven behaves
this.containerBuildContext = convertParameterToCanonicalFile(containerBuildContext, "containerBuildContext");
project.liberty.dev.containerBuildContext = this.containerBuildContext;
}
}
private File dockerBuildContext;
@Option(option = 'dockerBuildContext', description = 'Alias for containerBuildContext')
void setDockerBuildContext(String dockerBuildContext) {
if (dockerBuildContext != null && containerBuildContext == null) {
setContainerBuildContext(dockerBuildContext)
}
}
private convertParameterToCanonicalFile(String relativeOrAbsolutePath, String parameterName) {
File result = null;
if (relativeOrAbsolutePath != null) {
File file = new File(relativeOrAbsolutePath);
try {
if (file.isAbsolute()) {
result = file.getCanonicalFile();
} else {
result = new File(project.getRootDir(), relativeOrAbsolutePath).getCanonicalFile();
}
} catch (IOException e) {
throw new PluginExecutionException("Could not resolve canonical path of the " + parameterName + " parameter: " + parameterName, e);
}
}
return result;
}
private String containerRunOpts;
@Option(option = 'containerRunOpts', description = 'Additional options for the container run command when dev mode starts a container.')
void setContainerRunOpts(String containerRunOpts) {
this.containerRunOpts = containerRunOpts;
project.liberty.dev.containerRunOpts = this.containerRunOpts;
}
private String dockerRunOpts;
@Option(option = 'dockerRunOpts', description = 'Alias for containerRunOpts')
void setDockerRunOpts(String dockerRunOpts) {
if (dockerRunOpts != null && containerRunOpts == null) {
setContainerRunOpts(dockerRunOpts)
}
}
private int containerBuildTimeout;
@Option(option = 'containerBuildTimeout', description = 'Specifies the amount of time to wait (in seconds) for the completion of the container operation to build the image.')
void setContainerBuildTimeout(String inputValue) {
try {
this.containerBuildTimeout = Integer.valueOf(inputValue);
project.liberty.dev.containerBuildTimeout = this.containerBuildTimeout;
} catch (NumberFormatException e) {
logger.error(String.format("Unexpected value: %s for dev mode option containerBuildTimeout. containerBuildTimeout should be a valid integer.", inputValue));
throw e;
}
}
private int dockerBuildTimeout;
@Option(option = 'dockerBuildTimeout', description = 'Alias for containerBuildTimeout')
void setDockerBuildTimeout(String inputValue) {
if (inputValue != null && containerBuildTimeout == null) {
setContainerBuildTimeout(inputValue)
}
}
private Boolean skipDefaultPorts;
@Option(option = 'skipDefaultPorts', description = 'If true, the default container port mappings are skipped in the container run command.')
void setSkipDefaultPorts(boolean skipDefaultPorts) {
this.skipDefaultPorts = skipDefaultPorts;
project.liberty.dev.skipDefaultPorts = this.skipDefaultPorts;
}
private Boolean keepTempContainerfile;
@Option(option = 'keepTempContainerfile', description = 'If true, preserve the temporary Containerfile/Dockerfile used to build the container.')
void setKeepTempContainerfile(boolean keepTempContainerfile) {
this.keepTempContainerfile = keepTempContainerfile;
project.liberty.dev.keepTempContainerfile = this.keepTempContainerfile;
}
private Boolean keepTempDockerfile;
@Option(option = 'keepTempDockerfile', description = 'Alias for keepTempContainerfile')
void setKeepTempDockerfile(boolean keepTempDockerfile) {
if (keepTempDockerfile != null && keepTempContainerfile == null) {
setKeepTempContainerfile(keepTempDockerfile)
}
}
@Optional
@Input
Boolean generateFeatures;
// Need to use a string value to allow someone to specify --generateFeatures=false, if not explicitly set defaults to true
@Option(option = 'generateFeatures', description = 'If true, scan the application binary files to determine which Liberty features should be used. The default value is false.')
void setGenerateFeatures(String generateFeatures) {
this.generateFeatures = Boolean.parseBoolean(generateFeatures);
}
@Optional
@Input
Boolean skipInstallFeature;
// Need to use a string value to allow someone to specify --skipInstallFeature=true, if not explicitly set defaults to false
@Option(option = 'skipInstallFeature', description = 'If set to true, the installFeature task will be skipped when dev mode is started on an already existing Liberty runtime installation. It will also be skipped when dev mode is running and a restart of the server is triggered either directly by the user or by application changes. The installFeature task will be invoked though when dev mode is running and a change to the configured features is detected. The default value is false.')
void setSkipInstallFeature(String skipInstallFeature) {
this.skipInstallFeature = Boolean.parseBoolean(skipInstallFeature);
project.liberty.dev.skipInstallFeature = this.skipInstallFeature;
}
@Optional
@Input
Boolean clean;
@Option(option = 'clean', description = 'Clean all cached information on server start up. The default value is false.')
void setClean(boolean clean) {
this.clean = clean;
}
@Optional
@InputDirectory
File sourceDirectory;
@Optional
@InputDirectory
File testSourceDirectory;
private class DevTaskUtil extends DevUtil {
Set<String> existingFeatures;
Set<String> existingPlatforms;
Set<String> existingLibertyFeatureDependencies;
Map<String, File> libertyDirPropertyFiles = new HashMap<String, File> ();
private ServerTask serverTask = null;
DevTaskUtil(File buildDir, File installDirectory, File userDirectory, File serverDirectory, File sourceDirectory, File testSourceDirectory,
File configDirectory, File projectDirectory, List<File> resourceDirs, boolean changeOnDemandTestsAction,
boolean hotTests, boolean skipTests, boolean skipInstallFeature, String artifactId, int serverStartTimeout,
int verifyAppStartTimeout, int appUpdateTimeout, double compileWait,
boolean libertyDebug, boolean pollingTest, boolean container, File containerfile, File containerBuildContext,
String containerRunOpts, int containerBuildTimeout, boolean skipDefaultPorts, boolean keepTempContainerfile,
String mavenCacheLocation, String packagingType, File buildFile, boolean generateFeatures, List<Path> webResourceDirs,
List<ProjectModule> projectModuleList, Map<String, List<String>> parentBuildGradle, File serverOutputDir
) throws IOException, PluginExecutionException {
super(buildDir, serverDirectory, sourceDirectory, testSourceDirectory, configDirectory, projectDirectory, /* multi module project directory */ projectDirectory,
resourceDirs, changeOnDemandTestsAction, hotTests, skipTests, false /* skipUTs */, false /* skipITs */, skipInstallFeature, artifactId, serverStartTimeout,
verifyAppStartTimeout, appUpdateTimeout, ((long) (compileWait * 1000L)), libertyDebug,
true /* useBuildRecompile */, true /* gradle */, pollingTest, container, containerfile, containerBuildContext, containerRunOpts, containerBuildTimeout, skipDefaultPorts,
null /* compileOptions not needed since useBuildRecompile is true */, keepTempContainerfile, mavenCacheLocation, projectModuleList /* multi module upstream projects */,
projectModuleList.size() > 0 /* recompileDependencies as true for multi module */, packagingType, buildFile, parentBuildGradle /* parent build files */, generateFeatures, null /* compileArtifactPaths */, null /* testArtifactPaths */, webResourceDirs /* webResources */
);
this.libertyDirPropertyFiles = LibertyPropFilesUtility.getLibertyDirectoryPropertyFiles(new CommonLogger(project), installDirectory, userDirectory, serverDirectory, serverOutputDir);
ServerFeatureUtil servUtil = getServerFeatureUtil(true, libertyDirPropertyFiles);
FeaturesPlatforms fp = servUtil.getServerFeatures(serverDirectory, libertyDirPropertyFiles);
if (fp != null) {
this.existingFeatures = fp.getFeatures()
this.existingPlatforms = fp.getPlatforms()
}
this.existingLibertyFeatureDependencies = new HashSet<String>();
project.configurations.getByName('libertyFeature').dependencies.each {
dep -> this.existingLibertyFeatureDependencies.add(dep.name)
}
setContainerEngine(this)
}
@Override
public void debug(String msg) {
logger.debug(msg);
}
@Override
public void debug(String msg, Throwable e) {
logger.debug(msg, (Throwable) e)
}
@Override
public void debug(Throwable e) {
logger.debug("Throwable exception received: "+e.getMessage(), (Throwable) e)
}
@Override
public void warn(String msg) {
logger.warn(msg);
}
@Override
public void info(String msg) {
logger.lifecycle(msg);
}
@Override
public void error(String msg) {
logger.error(msg);
}
@Override
public void error(String msg, Throwable e) {
logger.error(msg, e);
}
@Override
public boolean isDebugEnabled() {
return logger.isEnabled(LogLevel.DEBUG);
}
@Override
public String getServerStartTimeoutExample() {
return "'gradle libertyDev --serverStartTimeout=120'";
}
@Override
public String getProjectName() {
return project.getName();
}
@Override
public void stopServer() {
super.serverFullyStarted.set(false);
if (container) {
// Shouldn't get here, DevUtil should stop the container instead
logger.debug('DevUtil called stopServer when the server should be running in a container.')
return;
}
if (isLibertyInstalledAndValid(project)) {
if (getServerDir(project).exists()) {
ServerTask serverTaskStop = createServerTask(project, "stop");
serverTaskStop.execute();
} else {
logger.error('There is no server to stop. The server has not been created.');
}
} else {
logger.error('There is no server to stop. The runtime has not been installed.');
}
}
@Override
public ServerTask getServerTask() throws Exception {
if (serverTask != null) {
Map<String, String> envVars = getToolchainEnvVar();
updateServerTaskEnvironmentVariables(envVars)
return serverTask;
}
copyConfigFiles();
if (libertyDebug) {
serverTask = createServerTask(project, "debug");
setLibertyDebugPort(libertyDebugPort);
updateServerTaskEnvironmentVariables(getDebugEnvironmentVariables())
} else {
serverTask = createServerTask(project, "run");
}
serverTask.setClean(clean);
return serverTask;
}
/**
* set environment map passed to server task
* @param envVars variables map
*/
@Internal
private void updateServerTaskEnvironmentVariables(Map<String, String> envVars) {
if (!envVars.isEmpty()) {
if (serverTask.getEnvironmentVariables() != null && !serverTask.getEnvironmentVariables().isEmpty()) {
Map<String, String> mergedEnv = new HashMap<>(serverTask.getEnvironmentVariables());
mergedEnv.putAll(envVars);
serverTask.setEnvironmentVariables(mergedEnv);
} else {
serverTask.setEnvironmentVariables(envVars);
}
}
}
@Override
public boolean updateArtifactPaths(ProjectModule projectModule, boolean redeployCheck, boolean generateFeatures, ThreadPoolExecutor executor)
throws PluginExecutionException {
// for multi module, unable to identify the changes made, showing option for user. return true to trigger recompile
if (isMultiModuleProject()) {
warn("A change was detected in a build file. The libertyDev task could not determine if a server restart is required. To restart server, type 'r' and press Enter.");
return true;
}
return false;
}
@Override
public boolean updateArtifactPaths(File parentBuildFile) {
// for multi module, unable to identify the changes made, showing option for user. return true to trigger recompile
if (isMultiModuleProject()) {
warn("A change was detected in a build file. The libertyDev task could not determine if a server restart is required. To restart server, type 'r' and press Enter.");
return true;
}
return false;
}
@Override
protected void updateLooseApp() throws PluginExecutionException {
// not supported for Gradle, only used for exploded war Maven projects
}
@Override
protected void resourceDirectoryCreated() throws IOException {
// Nothing to do
}
@Override
protected void resourceModifiedOrCreated(File fileChanged, File resourceParent, File outputDirectory) throws IOException {
copyFile(fileChanged, resourceParent, outputDirectory, null);
}
@Override
protected void resourceDeleted(File fileChanged, File resourceParent, File outputDirectory) throws IOException {
deleteFile(fileChanged, resourceParent, outputDirectory, null);
}
@Override
public boolean recompileBuildFile(File buildFile, Set<String> compileArtifactPaths, Set<String> testArtifactPaths, boolean generateFeatures, ThreadPoolExecutor executor) {
boolean restartServer = false;
boolean installFeatures = false;
boolean optimizeGenerateFeatures = false;
// for multi module, unable to identify the changes made, showing option for user. return true to trigger recompile
if (isMultiModuleProject()) {
warn("A change was detected in a build file. The libertyDev task could not determine if a server restart is required. To restart server, type 'r' and press Enter.");
return true;
}
ProjectBuilder builder = ProjectBuilder.builder();
Project newProject;
try {
newProject = builder
.withProjectDir(project.rootDir)
.withGradleUserHomeDir(project.gradle.gradleUserHomeDir)
.withName(project.name)
.build();
// need this for gradle to evaluate the project
// and load the different plugins and extensions
newProject.evaluate();
} catch (Exception e) {
logger.error("Could not parse build.gradle " + e.getMessage());
logger.debug('Error parsing build.gradle', e);
return false;
}
// Detect change in installation configuration that requires restart of dev mode. Throw error.
if (hasInstallationConfigChanged(newProject, project)) {
// Note that a change in some config values requires a 'clean' because the install location is the same, but the
// artifact that gets installed would be different. This can happen when using 'libertyRuntime' for example and
// only changing the 'version'. The 'installLiberty' task cannot detect that difference today and would report the task as upToDate.
// It only detects changes in install location currently. It would not be trivial to detect the other types of changes.
logger.error("A change in Liberty runtime installation configuration requires a 'clean'. Stopping dev mode.");
util.stopServer();
throw new PluginExecutionException("A change in Liberty runtime installation configuration requires a 'clean'. After running the 'clean' task, please run the 'libertyDev' task again for the change to take effect.");
}
if(hasServerConfigBootstrapPropertiesChanged(newProject, project)) {
logger.debug('Bootstrap properties changed');
restartServer = true;
project.liberty.server.bootstrapProperties = newProject.liberty.server.bootstrapProperties;
}
if (hasServerConfigBootstrapPropertiesFileChanged(newProject, project)) {
logger.debug('Bootstrap properties file changed');
restartServer = true;
project.liberty.server.bootstrapPropertiesFile = newProject.liberty.server.bootstrapPropertiesFile;
}
if (hasServerConfigJVMOptionsChanged(newProject, project)) {
logger.debug('JVM Options changed');
restartServer = true;
project.liberty.server.jvmOptions = newProject.liberty.server.jvmOptions;
}
if (hasServerConfigJVMOptionsFileChanged(newProject, project)) {
logger.debug('JVM Options file changed');
restartServer = true;
project.liberty.server.jvmOptionsFile = newProject.liberty.server.jvmOptionsFile;
}
if (hasServerConfigEnvFileChanged(newProject, project)) {
logger.debug('Server Env file changed');
restartServer = true;
project.liberty.server.serverEnvFile = newProject.liberty.server.serverEnvFile;
}
if (hasServerConfigDirectoryChanged(newProject, project)) {
logger.debug('Server config directory changed');
restartServer = true;
project.liberty.server.configDirectory = newProject.liberty.server.configDirectory;
initializeConfigDirectory(); // make sure that the config dir is set if it was null in the new project
}
if (hasServerConfigEnvChanged(newProject, project)) {
logger.debug('Server env changed');
restartServer = true;
project.liberty.server.env = newProject.liberty.server.env;
}
if (hasServerConfigVarChanged(newProject, project)) {
logger.debug('Server var changed');
restartServer = true;
project.liberty.server.var = newProject.liberty.server.var;
}
if (hasServerConfigDefaultVarChanged(newProject, project)) {
logger.debug('Server default var changed');
restartServer = true;
project.liberty.server.defaultVar = newProject.liberty.server.defaultVar;
}
if (hasCopyLibsDirectoryChanged(newProject, project)) {
logger.debug('copyLibsDirectory changed');
restartServer = true;
project.liberty.server.deploy.copyLibsDirectory = newProject.liberty.server.deploy.copyLibsDirectory;
}
if (hasMergeServerEnvChanged(newProject, project)) {
logger.debug('mergeServerEnv changed');
restartServer = true;
project.liberty.server.mergeServerEnv = newProject.liberty.server.mergeServerEnv;
}
// if we don't already need to restart the server
// check if we need to install any additional features
if (!restartServer) {
List<String> oldFeatureNames = project.liberty.server.features.name;
List<String> newFeatureNames = newProject.liberty.server.features.name;
if (oldFeatureNames != newFeatureNames) {
logger.debug('Server feature changed');
installFeatures = true;
project.liberty.server.features.name = newFeatureNames;
}
// check if compile dependencies have changed
Configuration existingProjectCompileConfiguration = project.configurations.getByName('providedCompile');
List<String> existingProjectCompileDependencies = new ArrayList<String>();
existingProjectCompileConfiguration.dependencies.each { dep -> existingProjectCompileDependencies.add(dep.group + ":" + dep.name + ":" + dep.version) }
Configuration newProjectCompileConfiguration = newProject.configurations.getByName('providedCompile');
List<String> newProjectCompileDependencies = new ArrayList<String>();
newProjectCompileConfiguration.dependencies.each { dep -> newProjectCompileDependencies.add(dep.group + ":" + dep.name + ":" + dep.version) }
newProjectCompileDependencies.removeAll(existingProjectCompileDependencies);
if (!newProjectCompileDependencies.isEmpty()) {
logger.debug("Compile dependencies changed");
optimizeGenerateFeatures = true;
}
Configuration newLibertyFeatureConfiguration = newProject.configurations.getByName('libertyFeature');
List<String> newLibertyFeatureDependencies = new ArrayList<String>();
newLibertyFeatureConfiguration.dependencies.each { dep -> newLibertyFeatureDependencies.add(dep.name) }
newLibertyFeatureDependencies.removeAll(existingLibertyFeatureDependencies);
if (!newLibertyFeatureDependencies.isEmpty()) {
logger.debug('libertyFeature dependency changed');
installFeatures = true;
existingLibertyFeatureDependencies.addAll(newLibertyFeatureDependencies);
}
}
if (optimizeGenerateFeatures && generateFeatures) {
logger.debug("Detected a change in the compile dependencies, regenerating features");
// optimize generate features on build dependency change
boolean generateFeaturesSuccess = libertyGenerateFeatures(null, true);
if (generateFeaturesSuccess) {
util.javaSourceClassPaths.clear();
} else {
installFeatures = false;
}
}
if (restartServer) {
// - stop Server
// - create server or runBoostMojo
// - install feature
// - deploy app
// - start server
util.restartServer();
return true;
} else if (installFeatures) {
try {
libertyInstallFeature();
} catch (PluginExecutionException e) {
// display warning if install feature fails, generateFeatures is on, and Liberty features are in buildfile
if (e.getCause() instanceof BuildException && generateFeatures) {
libertyDependencyWarning(e.getCause());
}
}
}
return true;
}
// Check if BuildException contains InstallFeature feature conflict error message
// This method is only meant to be called if generateFeatures == true and Liberty feature dependencies
// are detected in the build file
private void libertyDependencyWarning(BuildException e) {
if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() != null) {
// PluginExecutionException from installFeature will be 3 layers deep
if (e.getCause().getCause().getCause().getMessage().contains(InstallFeatureUtil.CONFLICT_MESSAGE)) {
logger.warn(GEN_FEAT_LIBERTY_DEP_WARNING);
}
}
}
private boolean hasInstallationConfigChanged(Project newProject, Project oldProject) {
// The following project configuration is used for the Liberty installation
// liberty extension: installDir, baseDir, cacheDir, outputDir, userDir, runtime
// libertyRuntime dependency
// liberty->install block: type, runtimeUrl, version, useOpenLiberty
if (newProject.liberty.installDir != oldProject.liberty.installDir) {
logger.debug('liberty.installDir changed')
return true
}
if (newProject.liberty.baseDir != oldProject.liberty.baseDir) {
logger.debug('liberty.baseDir changed')
return true
}
if (newProject.liberty.cacheDir != oldProject.liberty.cacheDir) {
logger.debug('liberty.cacheDir changed')
return true
}
if (newProject.liberty.outputDir != oldProject.liberty.outputDir) {
logger.debug('liberty.outputDir changed')
return true
}
if (newProject.liberty.userDir != oldProject.liberty.userDir) {
logger.debug('liberty.userDir changed')
return true
}
if (newProject.liberty.install.type != oldProject.liberty.install.type) {
logger.debug('liberty.install.type changed')
return true
}
if (newProject.liberty.install.runtimeUrl != oldProject.liberty.install.runtimeUrl) {
logger.debug('liberty.install.runtimeUrl changed')
return true
}
if (newProject.liberty.install.version != oldProject.liberty.install.version) {
logger.debug('liberty.install.version changed')
return true
}
if (newProject.liberty.install.useOpenLiberty != oldProject.liberty.install.useOpenLiberty) {
logger.debug('liberty.install.useOpenLiberty changed')
return true
}
if (newProject.liberty.runtime != oldProject.liberty.runtime) {
logger.debug('liberty.runtime changed')
return true
}
if (newProject.configurations.libertyRuntime != oldProject.configurations.libertyRuntime) {
logger.debug('libertyRuntime changed')
return true
}
return false
}
private boolean hasServerConfigBootstrapPropertiesChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.bootstrapProperties != oldProject.liberty.server.bootstrapProperties;
}
private boolean hasServerConfigBootstrapPropertiesFileChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.bootstrapPropertiesFile != oldProject.liberty.server.bootstrapPropertiesFile;
}
private boolean hasServerConfigJVMOptionsChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.jvmOptions != oldProject.liberty.server.jvmOptions;
}
private boolean hasServerConfigJVMOptionsFileChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.jvmOptionsFile != oldProject.liberty.server.jvmOptionsFile;
}
private boolean hasServerConfigEnvFileChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.serverEnvFile != oldProject.liberty.server.serverEnvFile;
}
private boolean hasServerConfigDirectoryChanged(Project newProject, Project oldProject) {
File newServerConfigDir = newProject.liberty.server.configDirectory;
File oldServerConfigDir = oldProject.liberty.server.configDirectory;
// Since no tasks have been run on the new project the initializeConfigDirectory()
// method has not been ran yet, so the file may still be null. But for the old project
// this method is guaranteed to have ran at the start of DevMode. So we need to initialize
// the config directory on the new project or else it would report that the directory has changed
if (newServerConfigDir == null) {
newServerConfigDir = new File(newProject.projectDir, "src/main/liberty/config");
}
return newServerConfigDir != oldServerConfigDir;
}
private boolean hasServerConfigEnvChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.env != oldProject.liberty.server.env;
}
private boolean hasServerConfigVarChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.var != oldProject.liberty.server.var;
}
private boolean hasServerConfigDefaultVarChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.defaultVar != oldProject.liberty.server.defaultVar;
}
private boolean hasMergeServerEnvChanged(Project newProject, Project oldProject) {
return newProject.liberty.server.mergeServerEnv != oldProject.liberty.server.mergeServerEnv;
}
private boolean hasCopyLibsDirectoryChanged(Project newProject, Project oldProject) {
File newCopyLibsDir = newProject.liberty.server.deploy.copyLibsDirectory;
File oldCopyLibsDirDir = oldProject.liberty.server.deploy.copyLibsDirectory;
return newCopyLibsDir != oldCopyLibsDirDir;
}
@Override
public void installFeatures(File configFile, File serverDir, boolean generateFeatures) {
ServerFeatureUtil servUtil = getServerFeatureUtil(true, libertyDirPropertyFiles);
FeaturesPlatforms fp = servUtil.getServerFeatures(serverDir, libertyDirPropertyFiles);
Set<String> features = fp == null ? null : fp.getFeatures();
if (features == null) {
return;
}
Set<String> featuresCopy = new HashSet<String>(features);
if (existingFeatures != null) {
features.removeAll(existingFeatures);
// check if features have been removed
Set<String> existingFeaturesCopy = new HashSet<String> (existingFeatures);
existingFeaturesCopy.removeAll(featuresCopy);
if (!existingFeaturesCopy.isEmpty()) {
logger.info("Configuration features have been removed: " + existingFeaturesCopy);
}
}
if (!features.isEmpty()) {
logger.info("Configuration features have been added: " + features);
// Call the installFeature gradle task using the temporary serverDir directory that DevMode uses
ProjectConnection gradleConnection = initGradleProjectConnection();
BuildLauncher gradleBuildLauncher = gradleConnection.newBuild();
// Exclude libertyCreate from the task dependencies, so that it will not update the server features
// before the features are installed.
gradleBuildLauncher.withArguments("--exclude-task", "libertyCreate");
try {
List<String> options = new ArrayList<String>();
options.add("--serverDir=${serverDir.getAbsolutePath()}");
if (container) {
options.add("--containerName=${super.getContainerName()}");
}
runInstallFeatureTask(gradleBuildLauncher, options);
} catch (BuildException e) {
// stdout/stderr from the installFeature task is sent to the terminal
// only need to log the actual stacktrace when debugging
logger.error('Failed to install features from configuration file' + e.getMessage())
if (generateFeatures && !project.configurations.getByName('libertyFeature').dependencies.isEmpty()) {
libertyDependencyWarning(e);
}
} finally {
gradleConnection.close();
}
}
}
@Override
public ServerFeatureUtil getServerFeatureUtilObj() {
// suppress logs from ServerFeatureUtil so that dev console is not flooded
return getServerFeatureUtil(true, libertyDirPropertyFiles);
}
@Override
public Set<String> getExistingFeatures() {
return this.existingFeatures;
}
@Override
public void updateExistingFeatures() {
ServerFeatureUtil servUtil = getServerFeatureUtil(true, libertyDirPropertyFiles);
FeaturesPlatforms fp = servUtil.getServerFeatures(getServerDir(project), libertyDirPropertyFiles);
this.existingFeatures = fp == null ? new HashSet<String>() : fp.getFeatures();
this.existingPlatforms = fp == null ? new HashSet<String>() : fp.getPlatforms();
}
@Override
public boolean compile(File dir) {
ProjectConnection gradleConnection = initGradleProjectConnection();
BuildLauncher gradleBuildLauncher = gradleConnection.newBuild();
try {
boolean isMain = dir.equals(sourceDirectory);
boolean isTest = dir.equals(testSourceDirectory);
if (isMain || isTest) {
def launcher = getJavaLauncher();
def scopeString = isTest ? "test " : "";
if (launcher != null && launcher.metadata != null) {
if (isJavaHomeSetForEnvProperties || isJavaHomeSetForJvmOptions) {
logger.debug("JAVA_HOME is set in ${isJavaHomeSetForEnvProperties ? 'server.env' : 'jvm.options'}, " +
"taking precedence over Java toolchain for dev mode ${scopeString}compilation.");
} else {
def metadata = launcher.metadata;
logger.lifecycle(
"Using Java toolchain for dev mode ${scopeString}compilation: " +
"version=${metadata.languageVersion}, javaHome=${metadata.installationPath.asFile}"
);
}
} else {
logger.debug("No Java toolchain launcher is configured for dev mode ${scopeString}compilation.");
}
}
if (isMain) {
runGradleTask(gradleBuildLauncher, 'compileJava', 'processResources');
}
if (isTest) {
runGradleTask(gradleBuildLauncher, 'compileTestJava', 'processTestResources');
}
return true;
} catch (BuildException e) {
// stdout/stderr from the compile task is sent to the terminal
// only need to log the actual stacktrace when debugging
logger.debug('Unable to compile', e);
return false;
} finally {
gradleConnection.close();
}
}
@Override
public boolean compile(File dir, ProjectModule project) {
// used for multi module scenario, not yet supported in ci.gradle
return false;
}
@Override
public void runUnitTests(File buildFile) throws PluginExecutionException, PluginScenarioException {
// Not needed for gradle.
}
@Override
public void runIntegrationTests(File buildFile) throws PluginExecutionException, PluginScenarioException {
// buildFile parameter is not used, implemented for multi module projects, which is not supported in Gradle
ProjectConnection gradleConnection = initGradleProjectConnection();
BuildLauncher gradleBuildLauncher = gradleConnection.newBuild();