forked from OpenLiberty/ci.common
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevUtil.java
More file actions
6108 lines (5663 loc) · 300 KB
/
Copy pathDevUtil.java
File metadata and controls
6108 lines (5663 loc) · 300 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.common.plugins.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.nio.file.SensitivityWatchEventModifier;
import io.openliberty.tools.ant.ServerTask;
import io.openliberty.tools.common.plugins.util.ServerFeatureUtil.FeaturesPlatforms;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Utility class for dev mode.
*/
public abstract class DevUtil extends AbstractContainerSupportUtil {
private static final String START_SERVER_MESSAGE_PREFIX = "CWWKF0011I:";
private static final String START_APP_MESSAGE_REGEXP = "CWWKZ0001I:";
private static final String UPDATED_APP_MESSAGE_REGEXP = "CWWKZ0003I:";
private static final String STOPPED_APP_MESSAGE_REGEXP = "CWWKZ0009I:";
private static final String PORT_IN_USE_MESSAGE_PREFIX = "CWWKO0221E:";
private static final String WEB_APP_AVAILABLE_MESSAGE_PREFIX = "CWWKT0016I:";
private static final String LISTENING_ON_PORT_MESSAGE_PREFIX = "CWWKO0219I:";
private static final String HTTP_PREFIX = "http://";
private static final String HTTP_PREFIX_ESCAPED = "http:\\/\\/";
private static final String HTTPS_PREFIX = "https://";
private static final String HTTPS_PREFIX_ESCAPED = "https:\\/\\/";
private static final String DEVMODE_DIR_NAME = "/devmode";
public static final String DEVMODE_PROJECT_ROOT = "io.openliberty.tools.projectRoot";
private static final String GENERATED_HEADER_REGEX = "# Generated by liberty-.*-plugin";
private static final String DEVMODE_CONTAINER_BASE_NAME = "liberty-dev";
private static final String DEVC_CONTAINER_DOCKER = "docker";
private static final String DEVC_CONTAINER_PODMAN = "podman";
private static final String DEVMODE_IMAGE_SUFFIX = "-dev-mode";
public static final String SKIP_BETA_INSTALL_WARNING = "skipBetaInstallFeatureWarning";
public static final String DEVC_HIDDEN_FOLDER = ".libertyDevc";
private static final String[] IGNORE_DIRECTORY_PREFIXES = new String[] { "." };
private static final String[] IGNORE_FILE_PREFIXES = new String[] { "." };
private static final String[] IGNORE_FILE_POSTFIXES = new String[] {
// core dumps
".dmp",
// vim
"~",
// intellij
"___jb_tmp___", "___jb_old___" };
private static final String[] DEFAULT_COMPILER_OPTIONS = new String[] { "-g", "-parameters" };
private static final int LIBERTY_DEFAULT_HTTP_PORT = 9080;
private static final int LIBERTY_DEFAULT_HTTPS_PORT = 9443;
/**
* Log debug
*
* @param msg
*/
public abstract void debug(String msg);
/**
* Log debug
*
* @param msg
* @param e
*/
public abstract void debug(String msg, Throwable e);
/**
* Log debug
*
* @param e
*/
public abstract void debug(Throwable e);
/**
* Log warning
*
* @param msg
*/
public abstract void warn(String msg);
/**
* Log info
*
* @param msg
*/
public abstract void info(String msg);
/**
* Log error
*
* @param msg
*/
public abstract void error(String msg);
/**
* Log error
*
* @param msg
* @param e
*/
public abstract void error(String msg, Throwable e);
/**
* Returns whether debug is enabled by the current logger
*
* @return whether debug is enabled
*/
public abstract boolean isDebugEnabled();
/**
* Recompile the build file
*
* @param buildFile
* @param compileArtifactPaths
* @param testArtifactPaths
* @param generateFeatures boolean, true if auto generation of features is
* on
* @param executor The thread pool executor
* @throws PluginExecutionException if there was an error when restarting the
* server
* @return true if the build file was recompiled with changes
*/
public abstract boolean recompileBuildFile(File buildFile, Set<String> compileArtifactPaths,
Set<String> testArtifactPaths, boolean generateFeatures, ThreadPoolExecutor executor)
throws PluginExecutionException;
/**
* Updates the compile artifact paths of the given project module. Only used in
* multi module scenario.
*
* @param projectModule The corresponding project module to update artifact
* paths for
* @param redeployCheck Whether to redeploy the application if changes in the
* dependencies are detected
* @param generateFeatures boolean, true if auto generation of features is on
* @param executor The thread pool executor
* @return true if the compile artifact paths are updated
* @throws PluginExecutionException if there was an error when restarting the
* server
*/
public abstract boolean updateArtifactPaths(ProjectModule projectModule, boolean redeployCheck,
boolean generateFeatures, ThreadPoolExecutor executor) throws PluginExecutionException;
/**
* Update the compile artifact paths of any child modules of the given build
* file.
*
* @param parentBuildFile The parent build file
* @return true if the compile artifact paths are updated
*/
public abstract boolean updateArtifactPaths(File parentBuildFile);
/**
* Run the unit tests
*
* @param buildFile corresponding build file to run tests on
* @throws PluginScenarioException if unit tests failed
* @throws PluginExecutionException if unit tests could not be run
*/
public abstract void runUnitTests(File buildFile) throws PluginScenarioException, PluginExecutionException;
/**
* Run the integration tests
*
* @param buildFile corresponding buildFile to run tests on
* @throws PluginScenarioException if integration tests failed
* @throws PluginExecutionException if integration tests could not be run
*/
public abstract void runIntegrationTests(File buildFile) throws PluginScenarioException, PluginExecutionException;
/**
* Check the configuration file for new features and install features if needed
*
* @param configFile
* @param serverDir
* @param generateFeatures
*/
public abstract void installFeatures(File configFile, File serverDir, boolean generateFeatures);
/**
* Get the ServerFeatureUtil object
*
* @return ServerFeatureUtil object
*/
public abstract ServerFeatureUtil getServerFeatureUtilObj();
/**
* Get the set of existing features
*
* @return existing features set
*/
public abstract Set<String> getExistingFeatures();
/**
* Update the existing features list using the files in the server directory.
* Called on configuration file change to ensure we have the most current
* feature list.
*/
public abstract void updateExistingFeatures();
/**
* Compile the specified directory
*
* @param dir
* @return
*/
public abstract boolean compile(File dir);
/**
* Compile the specified directory for the project module
*
* @param dir
* @param project project module (used in multi-module scenario)
* @return
*/
public abstract boolean compile(File dir, ProjectModule project);
/**
* Stop the server
*/
public abstract void stopServer();
/**
* Get the ServerTask to start the server, which can be in either "run" or
* "debug" mode
*
* @return ServerTask the task to start the server
* @throws Exception if there was an error copying/creating config files
*/
public abstract ServerTask getServerTask() throws Exception;
/**
* Redeploy the application
*/
public abstract void redeployApp() throws PluginExecutionException;
/**
* Get an example command using the server start timeout parameter. The example
* command is unique to each plugin.
*
* @return String containing the example command
*/
public abstract String getServerStartTimeoutExample();
/**
* Get the name of the current project running dev mode.
*
* @return String of the project name
*/
public abstract String getProjectName();
/**
* Is the application deployed as a loose application.
*/
public abstract boolean isLooseApplication();
/**
* Get the loose application configuration file.
* @return File loose application configuration file
*/
public abstract File getLooseApplicationFile();
private enum FileTrackMode {
NOT_SET, FILE_WATCHER, POLLING
}
private File serverDirectory;
private File sourceDirectory;
private File testSourceDirectory;
private File configDirectory;
private File projectDirectory;
private File multiModuleProjectDirectory;
protected List<File> resourceDirs;
// Not all webResource dirs need to be monitored, but those for which a Maven filtering will be applied do, since they can't be added to the loose app as source
protected List<Path> monitoredWebResourceDirs;
private boolean hotTests;
private Path tempConfigPath;
private boolean changeOnDemandTestsAction;
private boolean skipTests;
private boolean skipUTs;
private boolean skipITs;
private String applicationId;
private int appStartupTimeout;
private int appUpdateTimeout;
private Thread serverThread;
private PluginExecutionException serverThreadException;
/** If user stopped dev mode manually, this is true. If an external process caused dev mode to stop, this is false */
private AtomicBoolean devStop;
private String hostName;
private String httpPort;
private String httpsPort;
private String containerHttpPort;
private String containerHttpsPort;
private final long compileWaitMillis;
private AtomicBoolean inputUnavailable;
private int alternativeDebugPort = -1;
private boolean libertyDebug;
private int libertyDebugPort;
private AtomicBoolean detectedAppStarted;
private long serverStartTimeout;
private boolean useBuildRecompile;
private Map<File, Properties> propertyFilesMap;
final private Set<FileAlterationObserver> fileObservers;
final private Set<FileAlterationObserver> newFileObservers;
final private Set<FileAlterationObserver> cancelledFileObservers;
private AtomicBoolean calledShutdownHook;
private boolean gradle;
private long pollingInterval;
private FileTrackMode trackingMode;
private final boolean container;
private String imageName;
private String containerName;
private File containerfile;
private File containerBuildContext;
private Path tempContainerfilePath = null;
private String containerRunOpts;
private volatile Process containerRunProcess;
private File defaultContainerfile;
private int containerBuildTimeout;
private boolean skipDefaultPorts;
private boolean keepTempContainerfile;
protected List<String> srcMount = new ArrayList<String>();
protected List<String> destMount = new ArrayList<String>();
private boolean firstStartup = true;
private Set<Path> containerfileDirectoriesToWatch = new HashSet<Path>();
private Set<Path> containerfileDirectoriesTracked = new HashSet<Path>();
private Set<WatchKey> containerfileDirectoriesWatchKeys = new HashSet<WatchKey>();
private Set<FileAlterationObserver> containerfileDirectoriesFileObservers = new HashSet<FileAlterationObserver>();
private JavaCompilerOptions compilerOptions;
private final String mavenCacheLocation;
private AtomicBoolean externalContainerShutdown;
private AtomicBoolean shownFeaturesShWarning;
protected AtomicBoolean hasFeaturesSh;
protected AtomicBoolean serverFullyStarted;
private final File buildDirectory;
private List<ProjectModule> upstreamProjects; // supports multi module scenario, null for single module projects
private boolean recompileDependencies;
private String packagingType;
protected File buildFile;
/** Map of parent build files (parent build file, list of children build files) */
protected Map<String, List<String>> parentBuildFiles;
private boolean generateFeatures;
private boolean generateToSrc;
private Set<String> generatedFeaturesSet; // set of features in generated-features.xml file
private boolean generatedFeaturesModified;
private boolean generatedFeaturesCopied;
private Set<String> compileArtifactPaths;
private Set<String> testArtifactPaths;
protected File generateFeaturesFile; // the file that is created from the generate-features goal/task
protected File generateFeaturesOutputDir; // output directory for the generate-features goal/task (i.e. where the file is generated)
protected File generateFeaturesTmpDir; // the location where the generated features file is written during dev mode loop when generateToSrc is false
private File modifiedSrcBuildFile;
protected boolean skipInstallFeature;
// for gradle, this map will be kept as null
protected Map<String, Boolean> projectRecompileMap;
// constructor for maven
public DevUtil(File buildDirectory, File serverDirectory, File sourceDirectory, File testSourceDirectory,
File configDirectory, File projectDirectory, File multiModuleProjectDirectory, List<File> resourceDirs, boolean changeOnDemandTestsAction,
boolean hotTests, boolean skipTests, boolean skipUTs, boolean skipITs, boolean skipInstallFeature, String applicationId,
long serverStartTimeout, int appStartupTimeout, int appUpdateTimeout, long compileWaitMillis,
boolean libertyDebug, boolean useBuildRecompile, boolean gradle, boolean pollingTest, boolean container,
File containerfile, File containerBuildContext, String containerRunOpts, int containerBuildTimeout,
boolean skipDefaultPorts, JavaCompilerOptions compilerOptions, boolean keepTempContainerfile,
String mavenCacheLocation, List<ProjectModule> upstreamProjects, boolean recompileDependencies,
String packagingType, File buildFile, Map<String, List<String>> parentBuildFiles, boolean generateFeatures, boolean generateToSrc,
Set<String> compileArtifactPaths, Set<String> testArtifactPaths, List<Path> monitoredWebResourceDirs, Map<String, Boolean> projectRecompileMap) {
this(buildDirectory, serverDirectory, sourceDirectory, testSourceDirectory,
configDirectory, projectDirectory, multiModuleProjectDirectory, resourceDirs, changeOnDemandTestsAction,
hotTests, skipTests, skipUTs, skipITs, skipInstallFeature, applicationId,
serverStartTimeout, appStartupTimeout, appUpdateTimeout, compileWaitMillis,
libertyDebug, useBuildRecompile, gradle, pollingTest, container,
containerfile, containerBuildContext, containerRunOpts, containerBuildTimeout,
skipDefaultPorts, compilerOptions, keepTempContainerfile,
mavenCacheLocation, upstreamProjects, recompileDependencies,
packagingType, buildFile, parentBuildFiles, generateFeatures, generateToSrc,
compileArtifactPaths, testArtifactPaths, monitoredWebResourceDirs);
// setting projectRecompileMap as empty if input is null from ci.maven
this.projectRecompileMap = projectRecompileMap != null ? projectRecompileMap : new HashMap<>();
}
// constructor for gradle
public DevUtil(File buildDirectory, File serverDirectory, File sourceDirectory, File testSourceDirectory,
File configDirectory, File projectDirectory, File multiModuleProjectDirectory, List<File> resourceDirs, boolean changeOnDemandTestsAction,
boolean hotTests, boolean skipTests, boolean skipUTs, boolean skipITs, boolean skipInstallFeature, String applicationId,
long serverStartTimeout, int appStartupTimeout, int appUpdateTimeout, long compileWaitMillis,
boolean libertyDebug, boolean useBuildRecompile, boolean gradle, boolean pollingTest, boolean container,
File containerfile, File containerBuildContext, String containerRunOpts, int containerBuildTimeout,
boolean skipDefaultPorts, JavaCompilerOptions compilerOptions, boolean keepTempContainerfile,
String mavenCacheLocation, List<ProjectModule> upstreamProjects, boolean recompileDependencies,
String packagingType, File buildFile, Map<String, List<String>> parentBuildFiles, boolean generateFeatures, boolean generateToSrc,
Set<String> compileArtifactPaths, Set<String> testArtifactPaths, List<Path> monitoredWebResourceDirs) {
this.buildDirectory = buildDirectory;
this.serverDirectory = serverDirectory;
this.sourceDirectory = sourceDirectory;
this.testSourceDirectory = testSourceDirectory;
this.configDirectory = configDirectory;
this.projectDirectory = projectDirectory;
this.multiModuleProjectDirectory = multiModuleProjectDirectory;
this.resourceDirs = resourceDirs;
this.changeOnDemandTestsAction = changeOnDemandTestsAction;
this.hotTests = hotTests;
this.skipTests = skipTests;
this.skipUTs = skipUTs;
this.skipITs = skipITs;
this.skipInstallFeature = skipInstallFeature;
this.applicationId = applicationId;
this.serverStartTimeout = serverStartTimeout;
this.appStartupTimeout = appStartupTimeout;
this.appUpdateTimeout = appUpdateTimeout;
this.devStop = new AtomicBoolean(false);
this.compileWaitMillis = compileWaitMillis;
this.inputUnavailable = new AtomicBoolean(false);
this.libertyDebug = libertyDebug;
this.detectedAppStarted = new AtomicBoolean(false);
this.useBuildRecompile = useBuildRecompile;
this.calledShutdownHook = new AtomicBoolean(false);
this.gradle = gradle;
this.fileObservers = new HashSet<FileAlterationObserver>();
this.newFileObservers = new HashSet<FileAlterationObserver>();
this.cancelledFileObservers = new HashSet<FileAlterationObserver>();
this.pollingInterval = 100;
if (pollingTest) {
this.trackingMode = FileTrackMode.POLLING;
} else {
this.trackingMode = FileTrackMode.NOT_SET;
}
this.container = container;
this.containerfile = containerfile;
this.containerBuildContext = containerBuildContext;
this.containerRunOpts = containerRunOpts;
if (projectDirectory != null) {
//Use Containerfile if it exists, but default to Dockerfile if both present or neither exist
File defaultDockerFile = new File(projectDirectory, "Dockerfile");
File userDefaultContainerFile = new File(projectDirectory, "Containerfile");
if (!defaultDockerFile.exists() && userDefaultContainerFile.exists()) {
this.defaultContainerfile = userDefaultContainerFile;
} else {
this.defaultContainerfile = defaultDockerFile;
}
}
if (containerBuildTimeout < 1) {
this.containerBuildTimeout = 600;
} else {
this.containerBuildTimeout = containerBuildTimeout;
}
this.skipDefaultPorts = skipDefaultPorts;
this.compilerOptions = compilerOptions;
this.keepTempContainerfile = keepTempContainerfile;
this.mavenCacheLocation = mavenCacheLocation;
this.upstreamProjects = upstreamProjects;
this.recompileDependencies = recompileDependencies;
this.externalContainerShutdown = new AtomicBoolean(false);
this.shownFeaturesShWarning = new AtomicBoolean(false);
this.hasFeaturesSh = new AtomicBoolean(false);
this.serverFullyStarted = new AtomicBoolean(false);
this.packagingType = packagingType;
this.buildFile = buildFile;
if (parentBuildFiles == null) {
this.parentBuildFiles = new HashMap<String, List<String>>();
} else {
this.parentBuildFiles = parentBuildFiles;
}
this.generateFeatures = generateFeatures;
this.generateToSrc = generateToSrc;
this.generateFeaturesTmpDir = new File(buildDirectory, FeatureGeneratorUtil.GENERATED_FEATURES_TEMP_DIR);
initGenerationContext();
this.compileArtifactPaths = compileArtifactPaths;
this.testArtifactPaths = testArtifactPaths;
this.monitoredWebResourceDirs = monitoredWebResourceDirs;
this.generatedFeaturesModified = false;
this.generatedFeaturesCopied = false;
if (this.generateFeatures) {
this.generatedFeaturesSet = getGeneratedFeatures();
} else {
this.generatedFeaturesSet = new HashSet<String>();
}
this.modifiedSrcBuildFile = null;
}
private void initGenerationContext() {
this.generateFeaturesOutputDir = generateToSrc ? configDirectory : generateFeaturesTmpDir;
this.generateFeaturesFile = new File(generateFeaturesOutputDir, FeatureGeneratorUtil.GENERATED_FEATURES_FILE_PATH);
}
public void copyGeneratedFeaturesFile(File destinationDir) throws IOException {
copyFile(generateFeaturesFile, generateFeaturesOutputDir, destinationDir, null);
if (destinationDir.equals(serverDirectory)) {
generatedFeaturesCopied = true; // features copied into server dir and not some temp dir
}
}
/**
* Run unit and/or integration tests
*
* @param waitForApplicationUpdate Whether to wait for the application to update
* before running integration tests
* @param messageOccurrences The previous number of times the application
* updated message has appeared.
* @param executor The thread pool executor
* @param forceSkipTests Whether to force skip all tests
* @param forceSkipUTs Whether to force skip the unit tests
* @param forceSkipITs Whether to force skip the integration tests
* @param currentBuildFile The build file to run tests against
* @param projectName The name of the current project, null if only
* one project exists
*/
public void runTests(boolean waitForApplicationUpdate, int messageOccurrences, ThreadPoolExecutor executor,
boolean forceSkipTests, boolean forceSkipUTs, boolean forceSkipITs, File currentBuildFile,
String projectName) {
debug("Running tests for: " + currentBuildFile + "; skipTests: " + forceSkipTests + "; skipITs: " + forceSkipITs
+ "; skipUTs: " + forceSkipUTs);
if (!forceSkipTests) {
ServerTask serverTask = null;
try {
serverTask = getServerTask();
} catch (Exception e) {
// not expected since server should already have been started
error("Could not get the server task for running tests.", e);
}
File logFile = getMessagesLogFile(serverTask);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
debug("Thread interrupted while waiting to start tests.", e);
}
// if queue size >= 1, it means a newer test has been queued so we
// should skip this and let that run instead
if (executor.getQueue().size() >= 1) {
Runnable head = executor.getQueue().peek();
boolean manualInvocation = ((TestJob) head).isManualInvocation();
if (manualInvocation) {
debug("Tests were re-invoked before previous tests began. Cancelling previous tests and resubmitting them.");
} else {
debug("Changes were detected before tests began. Cancelling tests and resubmitting them.");
}
return;
}
// skip unit tests if invoked by Gradle
if (!gradle && !(forceSkipUTs)) {
if (projectName != null) {
info("Running unit tests for " + projectName + " ...");
} else {
info("Running unit tests...");
}
try {
runUnitTests(currentBuildFile);
if (projectName != null) {
info("Unit tests for " + projectName + " finished.");
info("");
} else {
info("Unit tests finished.");
info("");
}
} catch (PluginScenarioException e) {
debug(e);
error(e.getMessage());
// if unit tests failed, don't run integration tests
return;
} catch (PluginExecutionException e) {
error(e.getMessage(), e);
}
}
// if queue size >= 1, it means a newer test has been queued so we
// should skip this and let that run instead
if (executor.getQueue().size() >= 1) {
Runnable head = executor.getQueue().peek();
boolean manualInvocation = ((TestJob) head).isManualInvocation();
if (manualInvocation) {
info("Tests were invoked while previous tests were running. Restarting tests.");
} else {
info("Changes were detected while tests were running. Restarting tests.");
}
return;
}
if (!forceSkipITs) {
if (!detectedAppStarted.get()) {
// very first time app is started wait for START_APP or UPDATED_APP message
if (appStartupTimeout < 0) {
warn("The verifyTimeout (verifyAppStartTimeout) value needs to be an integer greater than or equal to 0. The default value of 30 seconds will be used.");
appStartupTimeout = 30;
}
long timeout = appStartupTimeout * 1000;
// Wait for the app started message in messages.log
info("Waiting up to " + appStartupTimeout
+ " seconds to find the application start up or update message...");
String startMessage = serverTask.waitForStringInLog(
"(" + START_APP_MESSAGE_REGEXP + "|" + UPDATED_APP_MESSAGE_REGEXP + ")",
timeout, logFile);
if (startMessage == null) {
error("Unable to verify if the application was started after " + appStartupTimeout
+ " seconds. Consider increasing the verifyTimeout value if this continues to occur.");
} else {
detectedAppStarted.set(true);
}
} else if (waitForApplicationUpdate) {
// wait until application has been updated
int timesStopped = serverTask.countStringOccurrencesInFile(STOPPED_APP_MESSAGE_REGEXP, logFile);
int timesUpdated = serverTask.countStringOccurrencesInFile(UPDATED_APP_MESSAGE_REGEXP, logFile);
debug("timesStopped=" + timesStopped + " timesUpdated=" + timesUpdated);
if (timesStopped > timesUpdated) {
// timesStopped == timesUpdated indicates the app is already updated and no wait for update required
if (appUpdateTimeout < 0) {
appUpdateTimeout = 5;
}
long timeout = appUpdateTimeout * 1000;
serverTask.waitForUpdatedStringInLog(UPDATED_APP_MESSAGE_REGEXP, timeout, logFile, messageOccurrences);
}
}
if (gradle) {
info("Running tests...");
} else {
if (projectName != null) {
info("Running integration tests for " + projectName + "...");
} else {
info("Running integration tests...");
}
}
try {
runIntegrationTests(currentBuildFile);
if (gradle) {
info("Tests finished.");
} else {
if (projectName != null) {
info("Integration tests for " + projectName + " finished.");
info("");
} else {
info("Integration tests finished.");
info("");
}
}
} catch (PluginScenarioException e) {
debug(e);
error(e.getMessage());
// if unit tests failed, don't run integration tests
return;
} catch (PluginExecutionException e) {
error(e.getMessage(), e);
}
}
} else {
if (projectName != null) {
info("Tests will not run on demand for " + projectName + " because skipTests is set to true.");
} else {
info("Tests will not run on demand because skipTests is set to true.");
}
}
}
/**
* Get the number of times the application updated message has appeared in the
* application log
*
* @return the number of times the application has updated
*/
public int countApplicationUpdatedMessages() {
int messageOccurrences = -1;
if (!(skipTests || skipITs)) {
try {
ServerTask serverTask = getServerTask();
File logFile = getMessagesLogFile(serverTask);
String regexp = UPDATED_APP_MESSAGE_REGEXP;
messageOccurrences = serverTask.countStringOccurrencesInFile(regexp, logFile);
debug("Message occurrences before compile: " + messageOccurrences);
} catch (Exception e) {
debug("Failed to get message occurrences before compile", e);
}
}
return messageOccurrences;
}
/**
* Get the log file from server directory if using container, or from server task otherwise.
*
* @param serverTask the server task
* @return the messages log file for the server
*/
private File getMessagesLogFile(ServerTask serverTask) {
File logFile;
if (container) {
logFile = new File(serverDirectory, "logs/messages.log");
} else {
logFile = serverTask.getLogFile();
}
return logFile;
}
public void startServer() throws PluginExecutionException {
startServer(true, true);
}
/**
* Start the server and keep it running in a background thread.
*
* @param buildContainer Force a Docker build when in container mode. Ignored
* otherwise.
* @param pullParentImage If buildContainer is true, this determines whether the
* Docker build should also pull the latest parent image.
* Ignored otherwise.
*
* @throws PluginExecutionException If the server startup could not be verified
* within the timeout, or server startup
* failed.
*/
public void startServer(boolean buildContainer, boolean pullParentImage) throws PluginExecutionException {
try {
final ServerTask serverTask;
try {
serverTask = getServerTask();
} catch (Exception e) {
throw new PluginExecutionException("An error occurred while starting the server: " + e.getMessage(), e);
}
// Set debug variables in server.env if debug enabled
enableServerDebug();
if (container) {
if (!checkDockerVersion()) {
// Did not find valid docker or podman installation
throw new PluginExecutionException("Could not find a valid Docker or Podman installation.");
}
}
// build container image if in container mode
if (container && buildContainer) {
File containerfileToUse = getContainerfile();
debug("Containerfile to use: " + containerfileToUse);
if (containerfileToUse.exists()) {
// The build context comes from the specified containerBuildContext (or the user's Containerfile location by default)
File buildContext = containerBuildContext == null ? containerfileToUse.getParentFile() : containerBuildContext;
String buildContextString = buildContext.getAbsolutePath();
debug("Container build context: " + buildContextString);
File tempContainerfile = prepareTempContainerfile(containerfileToUse, buildContextString);
buildContainerImage(tempContainerfile, containerfileToUse, pullParentImage, buildContext);
} else {
// this message is mainly for the default containerfile scenario, since the containerfile parameter was already validated in Maven/Gradle plugin.
throw new PluginExecutionException("No Containerfile or Dockerfile was found at " + containerfileToUse.getAbsolutePath() + ". Create a Containerfile/Dockerfile at the specified location to use dev mode with container support. For an example of how to configure a Dockerfile, see https://github.com/OpenLiberty/ci.docker");
}
}
String logsDirectory = serverDirectory.getCanonicalPath() + "/logs";
final File messagesLogFile = new File(logsDirectory + "/messages.log");
// Watch logs directory if it already exists
boolean logsExist = new File(logsDirectory).isDirectory();
// Start server
serverThread = new Thread(new Runnable() {
@Override
public void run() {
try {
if (container) {
startContainer();
} else {
serverTask.execute();
}
} catch (RuntimeException e) {
// If devStop is true server was stopped with Ctl-c, do not throw exception
if (devStop.get() == false) {
// If a runtime exception occurred in the server task, log and set the exception field
PluginExecutionException e2;
if (container) {
e2 = new PluginExecutionException("An error occurred while running the container: " + e.getMessage(), e);
} else {
e2 = new PluginExecutionException("An error occurred while starting the server: " + e.getMessage(), e);
}
error(e2.getMessage());
serverThreadException = e2;
}
} catch (PluginExecutionException pe) {
error(pe.getMessage());
serverThreadException = pe;
}
}
});
serverThread.start();
// If the server thread dies at any point after this, allow the error to say
// that the server stopped
setDevStop(false);
// If there were already logs from a previous server run, wait for it to be updated.
if (logsExist) {
final AtomicBoolean messagesModified = new AtomicBoolean(false);
// If logs already exist, then watch the directory to ensure
// messages.log is modified before continuing.
FileFilter singleFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
try {
if (file.getCanonicalFile().equals(messagesLogFile.getCanonicalFile())) {
return true;
}
} catch (IOException e) {
if (file.equals(messagesLogFile)) {
return true;
}
}
return false;
}
};
FileAlterationObserver observer = new FileAlterationObserver(logsDirectory, singleFileFilter);
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
messagesModified.set(true);
}
@Override
public void onFileChange(File file) {
messagesModified.set(true);
}
});
try {
observer.initialize();
while (!messagesModified.get()) {
checkStopDevMode(false); // stop dev mode if the server thread was terminated
observer.checkAndNotify();
// wait for the log file to update during server startup
Thread.sleep(500);
}
debug("messages.log has been changed");
} catch (PluginScenarioException e) {
if (serverThreadException != null) {
throw serverThreadException;
} else {
// the server/container failed to start, so wrap this as an execution exception
throw new PluginExecutionException(e);
}
} catch (Exception e) {
error("An error occurred while waiting for the server to update messages.log: " + e.getMessage(), e);
} finally {
try {
observer.destroy();
} catch (Exception e) {
debug("Could not destroy FileAlterationObserver for logs directory " + logsDirectory, e);
}
}
} else {
// Wait until log exists
try {
while (!messagesLogFile.exists()) {
checkStopDevMode(false); // stop dev mode if the server thread was terminated
// wait for the log file to appear during server startup
Thread.sleep(500);
}
debug("messages.log has been created");
} catch (PluginScenarioException e) {
if (serverThreadException != null) {
throw serverThreadException;
} else {
// the server/container failed to start, so wrap this as an execution exception
throw new PluginExecutionException(e);
}
} catch (Exception e) {
error("An error occurred while waiting for the server to create messages.log: " + e.getMessage(), e);
}
}
// Set server start timeout
if (serverStartTimeout < 0) {
warn("The serverStartTimeout value needs to be an integer greater than or equal to 0. The default value of 90 seconds will be used.");
serverStartTimeout = 90;
}
long serverStartTimeoutMillis = serverStartTimeout * 1000;
// Wait for the server started message in messages.log
String startMessage = serverTask.waitForStringInLog(START_SERVER_MESSAGE_PREFIX, serverStartTimeoutMillis,
messagesLogFile);
if (startMessage == null) {
setDevStop(true);
if (container) {
stopContainer();
} else {
stopServer();
}
throw new PluginExecutionException("The server has not started within " + serverStartTimeout + " seconds. " +
"Consider increasing the server start timeout if this continues to occur. " +
"For example, " + getServerStartTimeoutExample());
} else {
serverFullyStarted.set(true);
}
// Check for port already in use error
String portError = serverTask.findStringInFile(PORT_IN_USE_MESSAGE_PREFIX, messagesLogFile);
if (portError != null) {
error(portError.split(PORT_IN_USE_MESSAGE_PREFIX)[1]);
}
// Parse hostname, http, https ports for integration tests to use
parseHostNameAndPorts(serverTask, messagesLogFile);
} catch (IOException e) {
throw new PluginExecutionException("An error occurred while starting the server: " + e.getMessage(), e);