-
Notifications
You must be signed in to change notification settings - Fork 29
/
WLPManagedContainer.java
1841 lines (1591 loc) · 71.6 KB
/
WLPManagedContainer.java
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
/*
* Copyright 2012, 2023 IBM Corporation, Red Hat Middleware LLC, and individual contributors
* identified by the Git commit log.
*
* 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.arquillian.managed;
import static java.util.logging.Level.FINER;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet;
import org.jboss.arquillian.container.test.api.Testable;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ArchivePath;
import org.jboss.shrinkwrap.api.asset.ArchiveAsset;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.asset.ClassAsset;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import io.openliberty.arquillian.managed.exceptions.CDILogExceptionLocator;
import io.openliberty.arquillian.managed.exceptions.DeploymentExceptionLocator;
import io.openliberty.arquillian.managed.exceptions.FFDCExceptionLocator;
import io.openliberty.arquillian.managed.exceptions.SupportFeatureSerializedExceptionLocator;
import io.openliberty.arquillian.managed.exceptions.SupportFeatureTextExceptionLocator;
public class WLPManagedContainer implements DeployableContainer<WLPManagedContainerConfiguration>
{
// Environment variables that Liberty takes account of for messages.log location:
// The precedence of the variables below can be thought of as building up from the bottom .
// Strings that are "UPPER_CASE" are environment variables and Strings that are "camelCase"
// can be set as properties. For properties, bootstrap.properties is read and used earlier
// in the Liberty start process but once the server.xml <logging> element is read,
// any equivalent value from there takes precedence.
//
private static final String DEFAULT_MESSAGES_LOG_NAME = "messages.log";
private static final String MESSAGE_FILE_NAME = "messageFileName";
private static final String MESSAGE_FILE_PROPERTY = "com.ibm.ws.logging.message.file.name";
private static final String LOG_DIRECTORY = "logDirectory";
private static final String LOG_DIRECTORY_PROPERTY = "com.ibm.ws.logging.log.directory";
private static final String LOG_DIR = "LOG_DIR";
private static final String WLP_OUTPUT_DIR = "WLP_OUTPUT_DIR";
private static final String WLP_USER_DIR = "WLP_USER_DIR";
private static final String JAVA_TOOL_OPTIONS = "JAVA_TOOL_OPTIONS";
private static final String ARQUILLIAN_SERVLET_NAME = "ArquillianServletRunnerEE9";
private static final String ARQUILLIAN_REST_NAME = "ArquillianRESTRunnerEE9";
private static final String className = WLPManagedContainer.class.getName();
private static Logger log = Logger.getLogger(className);
private static final String javaVmArgumentsDelimiter = " ";
private static final String javaVmArgumentsIndicator = "-";
private enum CommandType{
RUN,
STOP
}
private WLPManagedContainerConfiguration containerConfiguration;
private JMXConnector jmxConnector;
private MBeanServerConnection mbsc;
private Process wlpProcess;
private Thread shutdownThread;
private Map<String, Long>archiveDeployTimes = new HashMap<>();
private List<DeploymentExceptionLocator> exceptionLocators;
@Override
public void setup(WLPManagedContainerConfiguration configuration)
{
if (log.isLoggable(Level.FINER)) {
log.entering(className, "setup");
}
this.containerConfiguration = configuration;
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "setup");
}
}
// This method includes parts heavily based on the ManagedDeployableContainer.java in the jboss-as
// managed container implementation as written by Thomas.Diesler@jboss.com
@Override
public void start() throws LifecycleException
{
if (log.isLoggable(Level.FINER)) {
log.entering(className, "start");
}
// Find WebSphere Liberty Profile VMs by looking for ws-launch.jar and the name of the server
String vmid;
VirtualMachine wlpvm = null;
String serviceURL = null;
try {
vmid = findVirtualMachineIdByName(containerConfiguration.getServerName());
// If it has already been started, throw exception unless we explicitly allow connecting to a running server
if (vmid != null) {
if (!containerConfiguration.isAllowConnectingToRunningServer())
throw new LifecycleException("Connecting to an already running server is not allowed");
wlpvm = VirtualMachine.attach(vmid);
serviceURL = getVMLocalConnectorAddress(wlpvm);
if (serviceURL == null)
throw new LifecycleException("Unable to retrieve connector address for localConnector."
+ "Ensure the `localConnector-1.0` feature is included in the server.xml and installed correctly");
} else {
if (containerConfiguration.isAddLocalConnector()) {
// Get path to server.xml
String serverXML = getServerXML();
if ("defaultServer".equals(containerConfiguration.getServerName()) && !new File(serverXML).exists()) {
// If server.xml doesn't exist for the default server, we may be dealing with a new
// installation where the server will be created at first
// startup. Get the default template server.xml instead. The server.xml for "defaultServer"
// will be created from this.
serverXML = getDefaultServerXML();
}
// Read server.xml file into Memory
Document document = readServerXML(serverXML);
addFeatures(document, "localConnector-1.0");
writeServerXML(document, serverXML);
}
// Start the WebSphere Liberty Profile VM
List<String> cmd = getServerCommand(CommandType.RUN);
ProcessBuilder pb = new ProcessBuilder(cmd);
// Merge any errors with stdout
pb.redirectErrorStream(true);
// Set the working directory to the wlp home. Seems to be required to get server.env properly processed
pb.directory(new File(containerConfiguration.getWlpHome()));
// Process JVM args and add JAVA_TOOL_OPTIONS to pb.environment()
List<String> javaVmArguments = parseJvmArgs(containerConfiguration.getJavaVmArguments());
StringBuilder vmArgs = new StringBuilder("-Dcom.ibm.ws.logging.console.log.level=INFO");
for (String javaVmArgument : javaVmArguments )
vmArgs.append(javaVmArgumentsDelimiter)
.append(javaVmArgument);
log.finer("Setting JVM arguments: " + vmArgs.toString());
pb.environment().put(JAVA_TOOL_OPTIONS, vmArgs.toString());
if(containerConfiguration.getUsrDir() != null) {
pb.environment().put(WLP_USER_DIR, new File(containerConfiguration.getUsrDir()).getCanonicalPath());
}
log.finer("Starting server with command: " + cmd.toString());
wlpProcess = pb.start();
new Thread(new ConsoleConsumer(wlpProcess)).start();
cmd = getServerCommand(CommandType.STOP);
shutdownThread = getShutDownThread(cmd);
Runtime.getRuntime().addShutdownHook(shutdownThread);
// Wait up to 30s for the server to start
int startupTimeout = containerConfiguration.getServerStartTimeout() * 1000;
while (startupTimeout > 0 && serviceURL == null) {
startupTimeout -= 500;
Thread.sleep(500);
// Verify that the process we're looking for is actually running
int ev = Integer.MIN_VALUE; // exit value of the process
IllegalThreadStateException itse = null; // Will be thrown when process is still running
try {
ev = wlpProcess.exitValue();
} catch (IllegalThreadStateException e) {
itse = e;
}
if (itse == null)
throw new LifecycleException("Process terminated prematurely; ev = " + ev);
if (vmid == null)
// Find WebSphere Liberty Profile VMs by looking for ws-launch.jar and the name of the server
vmid = findVirtualMachineIdByName(containerConfiguration.getServerName());
if (wlpvm == null && vmid != null)
wlpvm = VirtualMachine.attach(vmid);
if (serviceURL == null && wlpvm != null)
serviceURL = getVMLocalConnectorAddress(wlpvm);
}
// If serviceURL is still null, we were unable to start the virtual machine
if (serviceURL == null)
throw new LifecycleException(
"Unable to retrieve connector address for localConnector of started VM. vmid: " + vmid
+ " connectedVM: " + wlpvm
+ ". Ensure the `localConnector-1.0` feature is included in the server.xml and installed correctly");
log.finer("vmid: " + vmid);
}
} catch (Exception e) {
throw new LifecycleException("Could not start container", e);
}
try {
JMXServiceURL url = new JMXServiceURL(serviceURL);
jmxConnector = JMXConnectorFactory.connect(url);
mbsc = jmxConnector.getMBeanServerConnection();
} catch (IOException e) {
throw new LifecycleException("Connecting to the JMX MBean Server failed", e);
}
initExceptionLocators();
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "start");
}
}
/***
* Returns an OS specific server command based on provided CommandType
*
* @param type
* @return appropriate ProcessBuilder command based on CommandType enum
*/
private List<String> getServerCommand(CommandType type) {
List<String> cmd = new ArrayList<>();
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win"))
cmd.add(containerConfiguration.getWlpHome() + "/bin/server.bat");
else {
String serverCommand = containerConfiguration.getWlpHome() + "/bin/server";
cmd.add(serverCommand);
// Attempt to make sure the server script is executable. Arquillian Chameleon needs this.
File f = new File(serverCommand);
if (!f.canExecute()) {
f.setExecutable(true, true);
}
}
switch (type){
case RUN:
cmd.add("run");
break;
case STOP:
cmd.add("stop");
break;
}
cmd.add(containerConfiguration.getServerName());
return cmd;
}
/***
* Initializes a thread as a shutdown-hook to run <i>bin/server stop</i> shell
* script command upon JVM shut-down.
*
* Utilizes the initial command list for startup by just replacing start-up command (run)
* with shut-down (stop).
*
* @param cmd
* @return an initialized unstarted thread to be registered as a shutdown hook.
*/
private Thread getShutDownThread(final List<String> cmd) {
final ProcessBuilder shutDownProcessBuilder = new ProcessBuilder(cmd);
try {
if (containerConfiguration.getUsrDir() != null) {
shutDownProcessBuilder.environment().put(WLP_USER_DIR, new File(containerConfiguration.getUsrDir()).getCanonicalPath());
}
} catch (IOException e) {
log.finer("Failed to set WLP_USER_DIR for shut-down shell command.");
}
return new Thread(new Runnable() {
@Override
public void run() {
try {
// Upon JVM shut-down run the shut-down shell command
Process proc = shutDownProcessBuilder.start();
proc.waitFor();
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
});
}
private List<String> parseJvmArgs(String javaVmArguments) {
List<String> parsedJavaVmArguments = new ArrayList<>();
String[] splitJavaVmArguments = javaVmArguments.split(javaVmArgumentsDelimiter);
if (splitJavaVmArguments.length > 1) {
for (String javaVmArgument : splitJavaVmArguments) {
if (javaVmArgument.trim().length() > 0) {
// remove precessing spaces
if(javaVmArgument.startsWith(javaVmArgumentsIndicator)) {
// vm argument without spaces
parsedJavaVmArguments.add(javaVmArgument);
} else {
// space handling -> concat with the precessing argument
String javaVmArgumentExtension = javaVmArgument;
javaVmArgument = parsedJavaVmArguments.remove(parsedJavaVmArguments.size() - 1) + javaVmArgumentsDelimiter + javaVmArgumentExtension;
parsedJavaVmArguments.add(javaVmArgument);
}
}
}
} else {
parsedJavaVmArguments.add(javaVmArguments);
}
return parsedJavaVmArguments;
}
private String getVMLocalConnectorAddress(VirtualMachine wlpvm)
throws IOException {
String serviceURL;
String PROPERTY_NAME = "com.sun.management.jmxremote.localConnectorAddress";
serviceURL = wlpvm.getAgentProperties().getProperty(PROPERTY_NAME);
// On some environments like the IBM JVM the localConnectorAddress is not
// in the AgentProperties but in the SystemProperties.
if (serviceURL == null)
serviceURL = wlpvm.getSystemProperties().getProperty(PROPERTY_NAME);
if (serviceURL == null) {
File jmxAddr = new File(getServerOutputDir() + "/logs/state/com.ibm.ws.jmx.local.address");
if (log.isLoggable(Level.FINER)) {
log.info("Checking local connector address file for JMX address at " + jmxAddr.getAbsolutePath());
}
if (jmxAddr.exists() && jmxAddr.isFile() && jmxAddr.canRead()) {
List<String> lines = Files.readAllLines(jmxAddr.toPath(), StandardCharsets.UTF_8);
if (lines != null && lines.size() > 0) {
if (log.isLoggable(Level.FINER)) {
log.info("Checking local connector address file for JMX address at " + lines.get(0));
}
return lines.get(0);
}
}
}
if (log.isLoggable(Level.FINER)) {
log.finer("service url: " + serviceURL);
}
return serviceURL;
}
private String findVirtualMachineIdByName(String serverName) {
if (log.isLoggable(Level.FINER)) {
log.entering(className, "findVirtualMachineIdByName");
}
List<VirtualMachineDescriptor> vmds = VirtualMachine.list();
for (VirtualMachineDescriptor vmd : vmds) {
String displayName = vmd.displayName();
if (log.isLoggable(Level.FINER)) {
log.finer("VMD displayName: " + displayName);
log.finer("VMD id: " + vmd.id());
}
if (displayName.contains(serverName) && (displayName.contains("ws-server.jar") || displayName.contains("ws-launch.jar"))) {
// If VM's display name matches, return.
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "findVirtualMachineIdByName", vmd.id());
}
return vmd.id();
}
}
// Only reached when VM is not found
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "findVirtualMachineIdByName");
}
return null;
}
private void initExceptionLocators() throws LifecycleException {
try {
// Attempt to find the exception that occurred on the server
exceptionLocators = new ArrayList<>();
exceptionLocators.add(new SupportFeatureSerializedExceptionLocator(mbsc));
exceptionLocators.add(new SupportFeatureTextExceptionLocator(mbsc));
exceptionLocators.add(new FFDCExceptionLocator(getLogsDirectory()));
exceptionLocators.add(new CDILogExceptionLocator());
} catch (Exception e) {
throw new LifecycleException("Failed to initialize exception locators", e);
}
}
@Override
public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException
{
if (log.isLoggable(Level.FINER)) {
log.entering(className, "deploy");
log.finer("Archive provided to deploy method: " + archive.toString(true));
}
waitForVerifyApps();
String archiveName = archive.getName();
String archiveType = createDeploymentType(archiveName);
String deployName = createDeploymentName(archiveName);
archiveDeployTimes.put(deployName, System.currentTimeMillis());
try {
// If the deployment is to server.xml, then update server.xml with the application information
if (containerConfiguration.isDeployTypeXML()) {
if (log.isLoggable(FINER)) {
log.finer("Deploying using server.xml");
}
// Throw error if deployment type is not ear, war, or eba
if (!archiveType.equalsIgnoreCase("ear") && !archiveType.equalsIgnoreCase("war") && !archiveType.equalsIgnoreCase("eba"))
throw new DeploymentException("Invalid archive type: " + archiveType + ". Valid archive types are ear, war, and eba.");
// Save the archive to disk so it can be loaded by the container.
String appDir = getAppDirectory();
File exportedArchiveLocation = new File(appDir, archiveName);
archive.as(ZipExporter.class).exportTo(exportedArchiveLocation, true);
// Read server.xml file into Memory
Document document = readServerXML();
// Add the archive as appropriate to the server.xml file
addApplication(document, deployName, archiveName, archiveType);
// Update server.xml on file system
writeServerXML(document);
}
// Otherwise put the application in the dropins directory
else {
if (log.isLoggable(FINER)) {
log.finer("Deploying using dropins");
}
// Save the archive to disk so it can be loaded by the container.
String dropInDir = getDropInDirectory();
File exportedArchiveLocation = new File(dropInDir, archiveName);
String tempDir = getDropInTempDirectory();
File tempArchiveLocation = new File(tempDir, archiveName);
// Create the archive in a temporary location, then move it to the dropins directory
// to prevent liberty trying to start the archive before it's complete
archive.as(ZipExporter.class).exportTo(tempArchiveLocation, true);
Files.move(tempArchiveLocation.toPath(), exportedArchiveLocation.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
if (log.isLoggable(FINER)) {
log.finer("Deployment done");
}
waitForApplicationTargetState(new String[] {deployName}, true, containerConfiguration.getAppDeployTimeout());
// Return metadata on how to contact the deployed application
ProtocolMetaData metaData = new ProtocolMetaData();
HTTPContext httpContext = new HTTPContext("localhost", getHttpPort());
List<WebModule> modules;
if (archive instanceof EnterpriseArchive) {
modules = getWebModules((EnterpriseArchive) archive);
} else if (archive instanceof WebArchive) {
WebModule m = new WebModule();
m.name = deployName;
m.archive = (WebArchive) archive;
m.contextRoot = getContextRoot(m.archive);
modules = Collections.singletonList(m);
} else {
modules = Collections.emptyList();
}
// register servlets
boolean addedSomeServlets = false;
for (WebModule module : modules) {
List<String> servlets = getServletNames(module);
for (String servlet : servlets) {
httpContext.add(new Servlet(servlet, module.contextRoot));
addedSomeServlets = true;
}
}
String servletToAdd = null;
if (!containerConfiguration.isServletTestProtocol()) {
servletToAdd = ARQUILLIAN_REST_NAME;
} else if (!addedSomeServlets) {
servletToAdd = ARQUILLIAN_SERVLET_NAME;
}
if (servletToAdd != null) {
// Urk, we found no servlets at all probably because we don't have the J2EE management mbeans
// Make a best guess at where servlets might be. Even if the servlet names are wrong, this at
// least allows basic URL injection to work.
if (modules.size() == 1) {
// If there's only one web module, add that
WebModule m = modules.get(0);
httpContext.add(new Servlet(servletToAdd, m.contextRoot));
} else {
httpContext.add(new Servlet(servletToAdd, deployName));
}
}
metaData.addContext(httpContext);
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "deploy");
}
return metaData;
} catch ( DeploymentException de ) {
// Keep any more specific raised DeploymentExceptions
throw de;
}
catch (Exception e) {
// Wrap generic exceptions as DeploymentExceptions
throw new DeploymentException("Exception while deploying application.", e);
}
}
private void waitForVerifyApps() throws DeploymentException {
String verifyApps = containerConfiguration.getVerifyApps();
if(verifyApps != null && verifyApps.length() > 0) {
String[] verifyAppArray = verifyApps.split(",");
Set<String> verifyAppSet = new HashSet<String>();
// Trim the whitespace off each app name
for (int i = 0; i < verifyAppArray.length; i++) {
String appToVerify = verifyAppArray[i];
appToVerify = appToVerify.trim();
if(appToVerify.length() > 0) {
verifyAppSet.add(appToVerify);
}
}
int totalTimeout = containerConfiguration.getVerifyAppDeployTimeout() * verifyAppSet.size();
waitForApplicationTargetState(verifyAppSet.toArray(new String[verifyAppSet.size()]), true, totalTimeout);
}
}
private List<WebModule> getWebModules(final EnterpriseArchive ear) throws DeploymentException {
List<WebModule> modules = new ArrayList<WebModule>();
for (ArchivePath path : ear.getContent().keySet()) {
if (path.get().endsWith("war")) {
WebModule module = new WebModule();
module.archive = ear.getAsType(WebArchive.class, path);
module.name = module.archive.getName().replaceFirst("^\\/", "").replaceFirst("\\.war$", "");
module.contextRoot = getContextRoot(ear, module.archive);
modules.add(module);
}
}
return modules;
}
/**
* Returns the servlet name(s).
* <p>
* Attempts to resolve the classes within the Web Archive and detect servlets.
* Falls back to just returning ArquillianServletRunner for testable archives
* and returns an empty list otherwise.
*/
private List<String> getServletNames(WebModule webModule) throws DeploymentException {
try {
List<String> servletNames = new ArrayList<String>();
getServletNames(webModule.archive, servletNames);
// If we didn't find any servlets and this is a testable archive it ought to
// contain the arquillian test servlet, which is all that most tests need to
// work
if (servletNames.isEmpty() && Testable.isArchiveToTest(webModule.archive)) {
servletNames.add(containerConfiguration.isServletTestProtocol() ? ARQUILLIAN_SERVLET_NAME : ARQUILLIAN_REST_NAME);
}
return servletNames;
} catch (Exception e) {
throw new DeploymentException("Error trying to retrieve servlet names", e);
}
}
/**
* Recursively search for servlets within the Web Archive and add servlet names.
* Only searches for classes within the war file and recursively searches within
* the WEB-INF/lib directory. Detects servlets if defined in the web.xml or
* annotated with @WebServlet.
*/
private void getServletNames(Archive archive, List<String> servletNames) throws DeploymentException {
try {
Map<ArchivePath, org.jboss.shrinkwrap.api.Node> content = archive.getContent();
for (ArchivePath key : content.keySet()) {
org.jboss.shrinkwrap.api.Node node = content.get(key);
// want to scan all libraries in web-inf/lib
boolean isWebINF = node.getPath().get().startsWith("/WEB-INF/lib");
if (node.getAsset() != null && node.getAsset() instanceof ArchiveAsset && isWebINF) {
ArchiveAsset archiveAsset = (ArchiveAsset) node.getAsset();
// recursively search web archives within the web-inf/lib directory
getServletNames(archiveAsset.getArchive(), servletNames);
}
// some classes are registered as ClassLoaderAssets or ByteArrayAssets
if (node.getAsset() != null
&& (node.getAsset() instanceof ClassLoaderAsset || node.getAsset() instanceof ByteArrayAsset)
&& key.get().endsWith(".class")) {
byte[] ba = null;
try {
// only load ClassLoaderAssets from WEB-INF dir to avoid excessive class loading
if (node.getAsset() instanceof ClassLoaderAsset && key.get().contains("WEB-INF")) {
ClassLoaderAsset classLoaderAsset = (ClassLoaderAsset) node.getAsset();
InputStream inputStream = classLoaderAsset.openStream();
ba = IOUtils.toByteArray(inputStream);
inputStream.close();
} else if (node.getAsset() instanceof ByteArrayAsset) {
ByteArrayAsset byteArrayAsset = (ByteArrayAsset) node.getAsset();
ba = byteArrayAsset.getSource();
}
if (ba != null) {
// try to load byte array with system class loader as parent classloader
ByteClassLoader loader = new ByteClassLoader(ClassLoader.getSystemClassLoader(), ba);
Class<?> c = loader.findClass(null);
String name = getServletNameFromAnnotation(c);
if (name != null) {
servletNames.add(name);
}
loader = null;
ba = null;
c = null;
}
} catch (IOException | IndexOutOfBoundsException | LinkageError e) {
// cannot get access to the class associated with the ClassLoaderAsset or
// ByteArrayAsset
// do nothing
log.warning("Failed to resolve servlet names for:" + key.get() + ". " + e.toString());
}
}
// if asset is a class
if (node.getAsset() != null && node.getAsset() instanceof ClassAsset) {
ClassAsset classAsset = (ClassAsset) node.getAsset();
Class<?> c = classAsset.getSource();
String name = getServletNameFromAnnotation(c);
if (name != null) {
servletNames.add(name);
}
}
// if the current resource is a web.xml / web-fragment.xml file read the servlet
// names from the xml
if (key.get().endsWith("/web.xml") || key.get().endsWith("/web-fragment.xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(node.getAsset().openStream());
servletNames.addAll(getServletNamesFromWebXML(doc));
}
}
} catch (Exception e) {
throw new DeploymentException("Error trying to retrieve servlet names", e);
}
}
/**
* Returns the servlet name(s) based on the @WebServlet annotation(s).
* <p>
* Detect servlets from the @WebServlet annotation. First tries to use the name
* property set explicitly on the @WebServlet annotation, otherwise use the
* class name. If none of the classes detected have the @WebServlet annotation,
* returns null
*/
private String getServletNameFromAnnotation(Class<?> c) throws DeploymentException {
try {
jakarta.servlet.annotation.WebServlet webServlet = c
.getAnnotation(jakarta.servlet.annotation.WebServlet.class);
if (webServlet != null) {
if (webServlet.name() != null && !webServlet.name().isEmpty()) {
// use name property set in @WebServlet
return webServlet.name();
} else {
// default: use class name
return c.getSimpleName();
}
}
return null;
} catch (Exception e) {
throw new DeploymentException(
"Error trying to resolve servlet name from jakarta.servlet.annotation.WebServlet annotation", e);
}
}
private List<String> getServletNamesFromWebXML(Document webXML) {
List<String> servletNames = new ArrayList<String>();
// find all <servlet> elements
NodeList servlets = webXML.getElementsByTagName("servlet");
for (int i = 0; i < servlets.getLength(); i++) {
Node currElement = servlets.item(i);
if (currElement.getNodeType() == Node.ELEMENT_NODE) {
// find all <servlet-name> elements inside the current <servlet> element
Element servletElement = (Element) currElement;
NodeList nameElements = servletElement.getElementsByTagName("servlet-name");
if (nameElements.getLength() >= 1) {
String servletName = nameElements.item(0).getTextContent();
servletNames.add(servletName);
}
}
}
return servletNames;
}
private String getContextRoot(EnterpriseArchive ear, WebArchive war) throws DeploymentException {
org.jboss.shrinkwrap.api.Node applicationXmlNode = ear.get("META-INF/application.xml");
if(applicationXmlNode != null && applicationXmlNode.getAsset() != null) {
InputStream input = null;
try {
input = ear.get("META-INF/application.xml").getAsset().openStream();
Document applicationXml = readXML(input);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression ctxRootSelector = xPath.compile("//module/web[web-uri/text()='"+ war.getName() +"']/context-root");
String ctxRoot = ctxRootSelector.evaluate(applicationXml);
if(ctxRoot != null && ctxRoot.trim().length() > 0) {
return ctxRoot;
}
} catch (Exception e) {
throw new DeploymentException("Unable to retrieve context-root from application.xml");
} finally {
closeQuietly(input);
}
}
return getContextRoot(war);
}
private String getContextRoot(WebArchive war) throws DeploymentException {
org.jboss.shrinkwrap.api.Node webExtXmlNode = war.get("WEB-INF/ibm-web-ext.xml");
if(webExtXmlNode != null && webExtXmlNode.getAsset() != null) {
InputStream input = null;
try {
input = war.get("WEB-INF/ibm-web-ext.xml").getAsset().openStream();
Document webExtXml = readXML(input);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression ctxRootSelector = xPath.compile("//context-root/@uri");
String ctxRoot = ctxRootSelector.evaluate(webExtXml);
if(ctxRoot != null && ctxRoot.trim().length() > 0) {
return ctxRoot;
}
} catch (Exception e) {
throw new DeploymentException("Unable to retrieve context-root from ibm-web-ext.xml");
} finally {
closeQuietly(input);
}
}
return createDeploymentName(war.getName());
}
private static void closeQuietly(Closeable closable) {
try {
if (closable != null)
closable.close();
} catch (IOException e) {
log.log(Level.WARNING, "Exception while closing Closeable", e);
}
}
private int getHttpPort() throws DeploymentException {
if (log.isLoggable(Level.FINER)) {
log.entering(className, "getHttpPort");
}
int httpPort = containerConfiguration.getHttpPort();
if (httpPort == 0)
httpPort = getHttpPortFromChannelFWMBean("defaultHttpEndpoint");
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "getHttpPort", httpPort);
}
return httpPort;
}
// Returns the HttpPort configured on the Channel Framework MBean with the provided endpoint name
private int getHttpPortFromChannelFWMBean(String endpointName) throws DeploymentException {
if (log.isLoggable(Level.FINER)) {
log.entering(className, "getHttpPortFromChannelFWMBean", endpointName);
}
ObjectName endpointMBean = null;
try {
endpointMBean = new ObjectName(
"WebSphere:feature=channelfw,type=endpoint,name="
+ endpointName);
} catch (MalformedObjectNameException e) {
throw new DeploymentException(
"The generated object name is wrong. The endpointName used was '"
+ endpointName + "'", e);
} catch (NullPointerException e) {
// This should never happen given that the name parameter to the
// ObjectName constructor above can never be null
throw new DeploymentException("This should never happen", e);
}
int httpPort;
try {
if (!mbsc.isRegistered(endpointMBean))
throw new DeploymentException("The Channel Framework MBean with endpointName '"
+ endpointName + "' does not exist.");
httpPort = ((Integer)mbsc.getAttribute(endpointMBean, "Port")).intValue();
log.finer("httpPort: " + httpPort);
} catch (Exception e) {
throw new DeploymentException(
"Exception while retrieving httpPort information from Channel Framework MBean. "
+ "The httpPort can also be manually configured in the arquillian container configuration.", e);
}
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "getHttpPortFromChannelFWMBean", httpPort);
}
return httpPort;
}
@Override
public void undeploy(final Archive<?> archive) throws DeploymentException
{
if (log.isLoggable(Level.FINER)) {
log.entering(className, "undeploy");
}
String archiveName = archive.getName();
String deployName = createDeploymentName(archiveName);
String deployDir = null; // will become either app or dropin dir
archiveDeployTimes.remove(deployName);
try {
// If deploy type is xml, then remove the application from the xml file, which causes undeploy
if (containerConfiguration.isDeployTypeXML()) {
// Read the server.xml file into Memory
Document document = readServerXML();
// Remove the archive from the server.xml file
removeApplication(document, deployName);
// Update server.xml on file system
writeServerXML(document);
// Wait until the application is undeployed
waitForApplicationTargetState(new String[] {deployName}, false, containerConfiguration.getAppUndeployTimeout());
}
// Now we can proceed and delete the archive for either deploy type
if (containerConfiguration.isDeployTypeXML()) {
deployDir = getAppDirectory();
} else {
deployDir = getDropInDirectory();
}
// Remove the deployed archive
File exportedArchiveLocation = new File(deployDir, archiveName);
deleteWithRetries(exportedArchiveLocation, containerConfiguration.isFailSafeUndeployment(), containerConfiguration.getFileDeleteRetries(), containerConfiguration.getStandardFileDeleteRetryInterval());
// If it was the archive deletion that caused the undeploy we wait for the
// correct state
if (!containerConfiguration.isDeployTypeXML()) {
// Wait until the application is undeployed
waitForApplicationTargetState(new String[] {deployName}, false, containerConfiguration.getAppUndeployTimeout());
}
} catch (Exception e) {
throw new DeploymentException("Exception while undeploying application.", e);
}
if (log.isLoggable(Level.FINER)) {
log.exiting(className, "undeploy");
}
}
private void deleteWithRetries(File archveToDelete, boolean isFailSafeUndeployment, int retries, int retryInterval) throws DeploymentException {
boolean complete = false;
boolean failSafeUndeployment = containerConfiguration.isFailSafeUndeployment();
Exception lastException = null;
for (int attempt = 0; !complete && attempt <= retries; attempt ++) {
if (attempt > 0) {
try {
Thread.sleep(retryInterval);
} catch (InterruptedException e) {
throw new DeploymentException("Interrupted while trying to delete " + archveToDelete, e);
}
}
try {
//Attempt to delete the archive. If failSafeUndeployment is false and the archive is already gone throw an exception.
if (Files.deleteIfExists(archveToDelete.toPath())) {
complete = true;
} else if(!failSafeUndeployment) {
throw new DeploymentException("Archive " + archveToDelete + " already deleted from deployment directory");
}
} catch (IOException e) {
//Store this for now. We will throw an exception after the loop if complete is false.
lastException = e;
}
}
if (!complete) {
if (failSafeUndeployment) {
log.log(Level.WARNING, "Unable to delete archive from deployment directory -> failsafe -> archive " + archveToDelete + " marked for delete on exit", lastException);
archveToDelete.deleteOnExit();
} else {
throw new DeploymentException("Could not delete " + archveToDelete, lastException);
}
}
}
private String getDropInDirectory() throws IOException {