forked from payara/Payara
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApplicationLifecycle.java
2368 lines (2090 loc) · 104 KB
/
ApplicationLifecycle.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
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
// Portions Copyright [2016-2018] [Payara Foundation and/or its affiliates.]
package com.sun.enterprise.v3.server;
import com.sun.enterprise.config.serverbeans.*;
import com.sun.enterprise.deploy.shared.ArchiveFactory;
import com.sun.enterprise.deploy.shared.FileArchive;
import com.sun.enterprise.util.LocalStringManagerImpl;
import fish.payara.enterprise.config.serverbeans.DeploymentGroup;
import java.beans.PropertyVetoException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.glassfish.api.*;
import org.glassfish.api.admin.ParameterMap;
import org.glassfish.api.admin.ServerEnvironment;
import org.glassfish.api.admin.config.ApplicationName;
import org.glassfish.api.container.Container;
import org.glassfish.api.container.Sniffer;
import org.glassfish.api.deployment.*;
import org.glassfish.api.deployment.archive.*;
import org.glassfish.api.event.*;
import org.glassfish.api.event.EventListener.Event;
import org.glassfish.api.virtualization.VirtualizationEnv;
import org.glassfish.common.util.admin.ParameterMapExtractor;
import org.glassfish.deployment.common.*;
import org.glassfish.deployment.monitor.DeploymentLifecycleProbeProvider;
import org.glassfish.deployment.versioning.VersioningSyntaxException;
import org.glassfish.deployment.versioning.VersioningUtils;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.PostConstruct;
import org.glassfish.hk2.api.PreDestroy;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.classmodel.reflect.Parser;
import org.glassfish.hk2.classmodel.reflect.ParsingContext;
import org.glassfish.hk2.classmodel.reflect.Types;
import org.glassfish.internal.api.*;
import org.glassfish.internal.data.*;
import org.glassfish.internal.deployment.ApplicationLifecycleInterceptor;
import org.glassfish.internal.deployment.Deployment;
import org.glassfish.internal.deployment.DeploymentTracing;
import org.glassfish.internal.deployment.ExtendedDeploymentContext;
import org.glassfish.kernel.KernelLoggerInfo;
import org.glassfish.server.ServerEnvironmentImpl;
import org.jvnet.hk2.annotations.Optional;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.config.ConfigBean;
import org.jvnet.hk2.config.ConfigBeanProxy;
import org.jvnet.hk2.config.ConfigSupport;
import org.jvnet.hk2.config.RetryableException;
import org.jvnet.hk2.config.SingleConfigCode;
import org.jvnet.hk2.config.Transaction;
import org.jvnet.hk2.config.TransactionFailure;
import org.jvnet.hk2.config.types.Property;
/**
* Application Loader is providing useful methods to load applications
*
* @author Jerome Dochez, Sanjeeb Sahoo
*/
@Service
@Singleton
public class ApplicationLifecycle implements Deployment, PostConstruct {
private static final String[] UPLOADED_GENERATED_DIRS = new String [] {"policy", "xml", "ejb", "jsp"};
@Inject
protected SnifferManagerImpl snifferManager;
@Inject
ServiceLocator habitat;
@Inject
ArchiveFactory archiveFactory;
@Inject
ContainerRegistry containerRegistry;
@Inject
public ApplicationRegistry appRegistry;
@Inject
protected Applications applications;
@Inject @Named( ServerEnvironment.DEFAULT_INSTANCE_NAME)
Server server;
@Inject
protected Domain domain;
@Inject
ServerEnvironmentImpl env;
@Inject @Optional
VirtualizationEnv virtEnv;
@Inject
Events events;
@Inject
ConfigSupport configSupport;
protected Logger logger = KernelLoggerInfo.getLogger();
final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(ApplicationLifecycle.class);
private final ThreadLocal<Deque<ExtendedDeploymentContext>> currentDeploymentContext = new ThreadLocal<Deque<ExtendedDeploymentContext>>() {
@Override
protected Deque<ExtendedDeploymentContext> initialValue() {
return new ArrayDeque<>(5);
}
};
protected <T extends Container, U extends ApplicationContainer> Deployer<T, U> getDeployer(EngineInfo<T, U> engineInfo) {
return engineInfo.getDeployer();
}
protected DeploymentLifecycleProbeProvider
deploymentLifecycleProbeProvider = null;
private ExecutorService executorService = null;
private Collection<ApplicationLifecycleInterceptor> alcInterceptors = Collections.EMPTY_LIST;
public void postConstruct() {
executorService = createExecutorService();
deploymentLifecycleProbeProvider =
new DeploymentLifecycleProbeProvider();
alcInterceptors = habitat.getAllServices(
ApplicationLifecycleInterceptor.class);
}
/**
* Returns the ArchiveHandler for the passed archive abstraction or null
* if there are none.
*
* @param archive the archive to find the handler for
* @return the archive handler or null if not found.
* @throws IOException when an error occur
*/
public ArchiveHandler getArchiveHandler(ReadableArchive archive) throws IOException {
return getArchiveHandler(archive, null);
}
/**
* Returns the ArchiveHandler for the passed archive abstraction or null
* if there are none.
*
* @param archive the archive to find the handler for
* @param type the type of the archive
* @return the archive handler or null if not found.
* @throws IOException when an error occur
*/
public ArchiveHandler getArchiveHandler(ReadableArchive archive, String type) throws IOException {
if (type != null) {
return habitat.<ArchiveDetector>getService(ArchiveDetector.class, type).getArchiveHandler();
}
List<ArchiveDetector> detectors = new ArrayList<ArchiveDetector>(habitat.<ArchiveDetector>getAllServices(ArchiveDetector.class));
Collections.sort(detectors, new Comparator<ArchiveDetector>() {
// rank 2 is considered lower than rank 1, let's sort them in inceasing order
@Override
public int compare(ArchiveDetector o1, ArchiveDetector o2) {
return o1.rank() - o2.rank();
}
});
for (ArchiveDetector ad : detectors) {
if (ad.handles(archive)) {
return ad.getArchiveHandler();
}
}
return null;
}
@Override
public ApplicationDeployment prepare(Collection<? extends Sniffer> sniffers, final ExtendedDeploymentContext context) {
events.send(new Event<>(Deployment.DEPLOYMENT_START, context), false);
currentDeploymentContext.get().push(context);
final ActionReport report = context.getActionReport();
final DeployCommandParameters commandParams = context.getCommandParameters(DeployCommandParameters.class);
final String appName = commandParams.name();
ApplicationInfo appInfo;
final ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
ProgressTracker tracker = new ProgressTracker() {
@Override
public void actOn(Logger logger) {
//loaded is used instead of started to include more modules to
//stop. In some modules, the setup and cleanup steps are not
//fully symmetric, and to ensure thorough cleanup, we need to
//call module.stop() for started modules, and modules that are
//loaded but may not be started. Issue 18263
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.stop(context);
} catch (Exception e) {
// ignore
}
}
try {
PreDestroy.class.cast(context).preDestroy();
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.unload(context);
} catch (Exception e) {
// ignore
}
}
try {
ApplicationInfo appInfo = appRegistry.get(appName);
if (appInfo != null) {
// send the event to close necessary resources
events.send(new Event<ApplicationInfo>(Deployment.APPLICATION_DISABLED, appInfo));
}
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("prepared", EngineRef.class)) {
try {
module.clean(context);
} catch (Exception e) {
// ignore
}
}
// comment this out for now as the interceptor seems to use
// a different hook to roll back failure
// notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.REPLICATION, context);
if (!commandParams.keepfailedstubs) {
try {
context.clean();
} catch (Exception e) {
// ignore
}
}
appRegistry.remove(appName);
}
};
try {
if (commandParams.origin == OpsParams.Origin.deploy
&& appRegistry.get(appName) != null) {
report.setMessage(localStrings.getLocalString("appnamenotunique", "Application name {0} is already in use. Please pick a different name.", appName));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
// if the virtualservers param is not defined, set it to all
// defined virtual servers minus __asadmin on that target
if (commandParams.virtualservers == null) {
commandParams.virtualservers = DeploymentUtils.getVirtualServers(
commandParams.target, env, domain);
}
if (commandParams.enabled == null) {
commandParams.enabled = Boolean.TRUE;
}
if (commandParams.altdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.ALT_DD, commandParams.altdd);
}
if (commandParams.runtimealtdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.RUNTIME_ALT_DD, commandParams.runtimealtdd);
}
context.addTransientAppMetaData(ExtendedDeploymentContext.TRACKER, tracker);
context.setPhase(DeploymentContextImpl.Phase.PREPARE);
ArchiveHandler handler = context.getArchiveHandler();
if (handler == null) {
handler = getArchiveHandler(context.getSource(),
commandParams.type);
context.setArchiveHandler(handler);
}
if (handler == null) {
report.setMessage(localStrings.getLocalString("unknownarchivetype", "Archive type of {0} was not recognized", context.getSourceDir()));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
DeploymentTracing tracing = context.getModuleMetaData(DeploymentTracing.class);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.ARCHIVE_HANDLER_OBTAINED);
}
if (handler.requiresAnnotationScanning(context.getSource())) {
getDeployableTypes(context);
}
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.PARSING_DONE);
}
// containers that are started are not stopped even if
// the deployment fail, the main reason
// is that some container do not support to be restarted.
if (sniffers != null && logger.isLoggable(Level.FINE)) {
for (Sniffer sniffer : sniffers) {
logger.fine("Before Sorting" + sniffer.getModuleType());
}
}
sniffers = getSniffers(handler, sniffers, context);
ClassLoaderHierarchy clh = habitat.getService(ClassLoaderHierarchy.class);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_HIERARCHY);
}
context.createDeploymentClassLoader(clh, handler);
events.send(new Event<DeploymentContext>(Deployment.AFTER_DEPLOYMENT_CLASSLOADER_CREATION, context), false);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_CREATED);
}
Thread.currentThread().setContextClassLoader(context.getClassLoader());
List<EngineInfo> sortedEngineInfos
= setupContainerInfos(handler, sniffers, context);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CONTAINERS_SETUP_DONE);
}
if (logger.isLoggable(Level.FINE)) {
for (EngineInfo info : sortedEngineInfos) {
logger.fine("After Sorting " + info.getSniffer().getModuleType());
}
}
if (sortedEngineInfos == null || sortedEngineInfos.isEmpty()) {
report.failure(logger, localStrings.getLocalString("unknowncontainertype", "There is no installed container capable of handling this application {0}", context.getSource().getName()));
tracker.actOn(logger);
return null;
}
// create a temporary application info to hold metadata
// so the metadata could be accessed at classloader
// construction time through ApplicationInfo
ApplicationInfo tempAppInfo = new ApplicationInfo(events,
context.getSource(), appName);
for (Object m : context.getModuleMetadata()) {
tempAppInfo.addMetaData(m);
}
tempAppInfo.setIsJavaEEApp(sortedEngineInfos);
// set the flag on the archive to indicate whether it's
// a JavaEE archive or not
context.getSource().setExtraData(Boolean.class, tempAppInfo.isJavaEEApp());
appRegistry.add(appName, tempAppInfo);
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.PREPARE, context);
} catch (Throwable interceptorException) {
report.failure(logger, "Exception while invoking the lifecycle interceptor", null);
report.setFailureCause(interceptorException);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, interceptorException);
tracker.actOn(logger);
return null;
}
events.send(new Event<DeploymentContext>(Deployment.DEPLOYMENT_BEFORE_CLASSLOADER_CREATION, context), false);
context.createApplicationClassLoader(clh, handler);
events.send(new Event<DeploymentContext>(Deployment.AFTER_APPLICATION_CLASSLOADER_CREATION, context), false);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_CREATED);
}
// this is a first time deployment as opposed as load following an unload event,
// we need to create the application info
// todo : we should come up with a general Composite API solution
ModuleInfo moduleInfo = null;
try {
moduleInfo = prepareModule(sortedEngineInfos, appName, context, tracker);
// Now that the prepare phase is done, any artifacts
// should be available. Go ahead and create the
// downloadable client JAR. We want to do this now, or
// at least before the load and start phases, because
// (for example) the app client deployer start phase
// needs to find all generated files when it runs.
final ClientJarWriter cjw = new ClientJarWriter(context);
cjw.run();
} catch (Throwable prepareException) {
prepareException.printStackTrace();
report.failure(logger, "Exception while preparing the app", null);
report.setFailureCause(prepareException);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, prepareException);
tracker.actOn(logger);
return null;
}
// the deployer did not take care of populating the application info, this
// is not a composite module.
appInfo = context.getModuleMetaData(ApplicationInfo.class);
if (appInfo == null) {
appInfo = new ApplicationInfo(events, context.getSource(), appName);
appInfo.addModule(moduleInfo);
for (Object m : context.getModuleMetadata()) {
moduleInfo.addMetaData(m);
appInfo.addMetaData(m);
}
} else {
for (EngineRef ref : moduleInfo.getEngineRefs()) {
appInfo.add(ref);
}
}
// remove the temp application info from the registry
// first, then register the real one
appRegistry.remove(appName);
appInfo.setIsJavaEEApp(sortedEngineInfos);
appRegistry.add(appName, appInfo);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.PREPARE, context);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.PREPARED);
}
// send the APPLICATION_PREPARED event
// set the phase and thread context classloader properly
// before sending the event
context.setPhase(DeploymentContextImpl.Phase.PREPARED);
Thread.currentThread().setContextClassLoader(context.getClassLoader());
appInfo.setAppClassLoader(context.getClassLoader());
events.send(new Event<DeploymentContext>(Deployment.APPLICATION_PREPARED, context), false);
if (loadOnCurrentInstance(context)) {
appInfo.setLibraries(commandParams.libraries());
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.LOAD, context);
appInfo.load(context, tracker);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.LOAD, context);
} catch (Throwable loadException) {
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, loadException);
report.failure(logger, "Exception while loading the app", null);
report.setFailureCause(loadException);
tracker.actOn(logger);
return null;
}
}
} catch (Exception e) {
report.failure(logger, localStrings.getLocalString("error.deploying.app", "Exception while deploying the app [{0}]", appName), null);
report.setFailureCause(e);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, e);
tracker.actOn(logger);
return null;
} finally {
Thread.currentThread().setContextClassLoader(currentCL);
if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS) {
context.postDeployClean(false /* not final clean-up yet */);
events.send(new Event<>(Deployment.DEPLOYMENT_FAILURE, context));
}
}
ApplicationDeployment depl = new ApplicationDeployment(appInfo, context);
appRegistry.addTransient(depl);
return depl;
}
@Override
public void initialize(ApplicationInfo appInfo, Collection<? extends Sniffer> sniffers, ExtendedDeploymentContext context) {
if(appInfo == null) {
return;
}
appRegistry.removeTransient(appInfo.getName());
final ActionReport report = context.getActionReport();
ProgressTracker tracker = context.getTransientAppMetaData(ExtendedDeploymentContext.TRACKER, ProgressTracker.class);
// now were falling back into the mainstream loading/starting sequence, at this
// time the containers are set up, all the modules have been prepared in their
// associated engines and the application info is created and registered
if (loadOnCurrentInstance(context)) {
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.START, context);
appInfo.initialize();
appInfo.getModuleInfos().forEach(moduleInfo -> moduleInfo.getEngineRefs()
.forEach(engineRef -> tracker.add("initialized", EngineRef.class, engineRef)));
appInfo.start(context, tracker);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.START, context);
} catch (Throwable loadException) {
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, loadException);
report.failure(logger, "Exception while loading the app", null);
report.setFailureCause(loadException);
tracker.actOn(logger);
} finally {
context.postDeployClean(false /* not final clean-up yet */);
if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
events.send(new Event<>(Deployment.DEPLOYMENT_SUCCESS, appInfo));
} else {
events.send(new Event<>(Deployment.DEPLOYMENT_FAILURE, context));
}
}
currentDeploymentContext.get().pop();
}
}
@Override
public ApplicationInfo deploy(final ExtendedDeploymentContext context) {
return deploy(null, context);
}
@Override
public ApplicationInfo deploy(Collection<? extends Sniffer> sniffers, final ExtendedDeploymentContext context) {
long operationStartTime = Calendar.getInstance().getTimeInMillis();
ApplicationDeployment rv = prepare(sniffers, context);
ApplicationInfo appInfo = rv != null? rv.appInfo : null;
if(appInfo != null) {
initialize(appInfo, sniffers, context);
long operationTime = Calendar.getInstance().getTimeInMillis() - operationStartTime;
deploymentLifecycleProbeProvider.applicationDeployedEvent(appInfo.getName(), getApplicationType(appInfo), String.valueOf(operationTime));
}
return appInfo;
}
@Override
public Types getDeployableTypes(DeploymentContext context) throws IOException {
synchronized(context) {
Types types = context.getTransientAppMetaData(Types.class.getName(), Types.class);
if (types!=null) {
return types;
} else {
try {
// scan the jar and store the result in the deployment context.
ParsingContext parsingContext = new ParsingContext.Builder().logger(context.getLogger()).executorService(executorService).build();
Parser parser = new Parser(parsingContext);
ReadableArchiveScannerAdapter scannerAdapter = new ReadableArchiveScannerAdapter(parser, context.getSource());
parser.parse(scannerAdapter, null);
for (ReadableArchive externalLibArchive :
getExternalLibraries(context)) {
ReadableArchiveScannerAdapter libAdapter = null;
try {
libAdapter = new ReadableArchiveScannerAdapter(parser, externalLibArchive);
parser.parse(libAdapter, null);
} finally {
if (libAdapter!=null) {
libAdapter.close();
}
}
}
parser.awaitTermination();
scannerAdapter.close();
context.addTransientAppMetaData(Types.class.getName(), parsingContext.getTypes());
context.addTransientAppMetaData(Parser.class.getName(), parser);
return parsingContext.getTypes();
} catch(InterruptedException e) {
throw new IOException(e);
}
}
}
}
private void notifyLifecycleInterceptorsBefore(final ExtendedDeploymentContext.Phase phase,
final ExtendedDeploymentContext dc) {
for (ApplicationLifecycleInterceptor i : alcInterceptors) {
i.before(phase, dc);
}
}
private void notifyLifecycleInterceptorsAfter(final ExtendedDeploymentContext.Phase phase,
final ExtendedDeploymentContext dc) {
for (ApplicationLifecycleInterceptor i : alcInterceptors) {
i.after(phase, dc);
}
}
private List<ReadableArchive> getExternalLibraries(
DeploymentContext context) throws IOException {
List<ReadableArchive> externalLibArchives = new ArrayList<ReadableArchive>();
String skipScanExternalLibProp = context.getAppProps().getProperty(
DeploymentProperties.SKIP_SCAN_EXTERNAL_LIB);
if (Boolean.valueOf(skipScanExternalLibProp)) {
// if we skip scanning external libraries, we should just
// return an empty list here
return Collections.EMPTY_LIST;
}
List<URI> externalLibs = DeploymentUtils.getExternalLibraries(context.getSource());
for (URI externalLib : externalLibs) {
externalLibArchives.add(archiveFactory.openArchive(new File(externalLib.getPath())));
}
return externalLibArchives;
}
/**
* Suspends this application.
*
* @param appName the registration application ID
* @return true if suspending was successful, false otherwise.
*/
public boolean suspend(String appName) {
boolean isSuccess = true;
ApplicationInfo appInfo = appRegistry.get(appName);
if (appInfo != null) {
isSuccess = appInfo.suspend(logger);
}
return isSuccess;
}
/**
* Resumes this application.
*
* @param appName the registration application ID
* @return true if resumption was successful, false otherwise.
*/
public boolean resume(String appName) {
boolean isSuccess = true;
ApplicationInfo appInfo = appRegistry.get(appName);
if (appInfo != null) {
isSuccess = appInfo.resume(logger);
}
return isSuccess;
}
public List<EngineInfo> setupContainerInfos(DeploymentContext context)
throws Exception {
return setupContainerInfos(context.getArchiveHandler(), getSniffers(context.getArchiveHandler(), null, context), context);
}
public Collection<? extends Sniffer> getSniffers(final ArchiveHandler handler, Collection<? extends Sniffer> sniffers, DeploymentContext context) {
if (handler == null) {
return Collections.EMPTY_LIST;
}
if (sniffers==null) {
if (handler instanceof CompositeHandler) {
((CompositeHandler)handler).initCompositeMetaData(context);
context.getAppProps().setProperty(ServerTags.IS_COMPOSITE, "true");
}
sniffers = snifferManager.getSniffers(context);
}
context.addTransientAppMetaData(DeploymentProperties.SNIFFERS, sniffers);
snifferManager.validateSniffers(sniffers, context);
return sniffers;
}
// set up containers and prepare the sorted ModuleInfos
public List<EngineInfo> setupContainerInfos(final ArchiveHandler handler,
Collection<? extends Sniffer> sniffers, DeploymentContext context)
throws Exception {
final ActionReport report = context.getActionReport();
DeploymentTracing tracing = context.getModuleMetaData(DeploymentTracing.class);
Map<Deployer, EngineInfo> containerInfosByDeployers = new LinkedHashMap<Deployer, EngineInfo>();
for (Sniffer sniffer : sniffers) {
if (sniffer.getContainersNames() == null || sniffer.getContainersNames().length == 0) {
report.failure(logger, "no container associated with application of type : " + sniffer.getModuleType(), null);
return null;
}
final String containerName = sniffer.getContainersNames()[0];
if (tracing!=null) {
tracing.addContainerMark(DeploymentTracing.ContainerMark.SNIFFER_DONE, containerName );
}
// start all the containers associated with sniffers.
EngineInfo engineInfo = containerRegistry.getContainer(containerName);
if (engineInfo == null) {
// need to synchronize on the registry to not end up starting the same container from
// different threads.
Collection<EngineInfo> containersInfo=null;
synchronized (containerRegistry) {
if (containerRegistry.getContainer(containerName) == null) {
if (tracing!=null) {
tracing.addContainerMark(
DeploymentTracing.ContainerMark.BEFORE_CONTAINER_SETUP, containerName );
}
containersInfo = setupContainer(sniffer, logger, context);
if (tracing!=null) {
tracing.addContainerMark(
DeploymentTracing.ContainerMark.AFTER_CONTAINER_SETUP, containerName );
}
if (containersInfo == null || containersInfo.size() == 0) {
String msg = "Cannot start container(s) associated to application of type : " + sniffer.getModuleType();
report.failure(logger, msg, null);
throw new Exception(msg);
}
}
}
// now start all containers, by now, they should be all setup...
if (containersInfo != null && !startContainers(containersInfo, logger, context)) {
final String msg = "Aborting, Failed to start container " + containerName;
report.failure(logger, msg, null);
throw new Exception(msg);
}
}
engineInfo = containerRegistry.getContainer(sniffer.getContainersNames()[0]);
if (tracing!=null) {
tracing.addContainerMark(
DeploymentTracing.ContainerMark.GOT_CONTAINER, containerName );
}
if (engineInfo ==null) {
final String msg = "Aborting, Failed to start container " + containerName;
report.failure(logger, msg, null);
throw new Exception(msg);
}
Deployer deployer = getDeployer(engineInfo);
if (deployer==null) {
if (!startContainers(Collections.singleton(engineInfo), logger, context)) {
final String msg = "Aborting, Failed to start container " + containerName;
report.failure(logger, msg, null);
throw new Exception(msg);
}
deployer = getDeployer(engineInfo);
if (deployer == null) {
report.failure(logger, "Got a null deployer out of the " + engineInfo.getContainer().getClass() + " container, is it annotated with @Service ?");
return null;
}
}
if (tracing!=null) {
tracing.addContainerMark(
DeploymentTracing.ContainerMark.GOT_DEPLOYER, containerName );
}
containerInfosByDeployers.put(deployer, engineInfo);
}
// all containers that have recognized parts of the application being deployed
// have now been successfully started. Start the deployment process.
List<ApplicationMetaDataProvider> providers = new LinkedList<ApplicationMetaDataProvider>();
providers.addAll(habitat.<ApplicationMetaDataProvider>getAllServices(ApplicationMetaDataProvider.class));
List<EngineInfo> sortedEngineInfos = new ArrayList<EngineInfo>();
Map<Class, ApplicationMetaDataProvider> typeByProvider = new HashMap<Class, ApplicationMetaDataProvider>();
for (ApplicationMetaDataProvider provider : habitat.<ApplicationMetaDataProvider>getAllServices(ApplicationMetaDataProvider.class)) {
if (provider.getMetaData()!=null) {
for (Class provided : provider.getMetaData().provides()) {
typeByProvider.put(provided, provider);
}
}
}
// check if everything is provided.
for (ApplicationMetaDataProvider provider : habitat.<ApplicationMetaDataProvider>getAllServices(ApplicationMetaDataProvider.class)) {
if (provider.getMetaData()!=null) {
for (Class dependency : provider.getMetaData().requires()) {
if (!typeByProvider.containsKey(dependency)) {
// at this point, I only log problems, because it maybe that what I am deploying now
// will not require this application metadata.
logger.log(Level.WARNING, KernelLoggerInfo.applicationMetaDataProvider,
new Object[] {provider, dependency});
}
}
}
}
Map<Class, Deployer> typeByDeployer = new HashMap<Class, Deployer>();
for (Deployer deployer : containerInfosByDeployers.keySet()) {
if (deployer.getMetaData()!=null) {
for (Class provided : deployer.getMetaData().provides()) {
typeByDeployer.put(provided, deployer);
}
}
}
for (Deployer deployer : containerInfosByDeployers.keySet()) {
if (deployer.getMetaData()!=null) {
for (Class dependency : deployer.getMetaData().requires()) {
if (!typeByDeployer.containsKey(dependency) && !typeByProvider.containsKey(dependency)) {
Service s = deployer.getClass().getAnnotation(Service.class);
String serviceName;
if (s!=null && s.name()!=null && s.name().length()>0) {
serviceName = s.name();
} else {
serviceName = deployer.getClass().getSimpleName();
}
report.failure(logger, serviceName + " deployer requires " + dependency + " but no other deployer provides it", null);
return null;
}
}
}
}
// ok everything is satisfied, just a matter of running things in order
List<Deployer> orderedDeployers = new ArrayList<Deployer>();
for (Deployer deployer : containerInfosByDeployers.keySet()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Keyed Deployer " + deployer.getClass());
}
loadDeployer(orderedDeployers, deployer, typeByDeployer, typeByProvider, context);
}
// now load metadata from deployers.
for (Deployer deployer : orderedDeployers) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Ordered Deployer " + deployer.getClass());
}
final MetaData metadata = deployer.getMetaData();
try {
if (metadata!=null) {
if (metadata.provides()==null || metadata.provides().length==0) {
deployer.loadMetaData(null, context);
} else {
for (Class<?> provide : metadata.provides()) {
if (context.getModuleMetaData(provide)==null) {
context.addModuleMetaData(deployer.loadMetaData(provide, context));
} else {
deployer.loadMetaData(null, context);
}
}
}
} else {
deployer.loadMetaData(null, context);
}
} catch(Exception e) {
report.failure(logger, "Exception while invoking " + deployer.getClass() + " prepare method", e);
throw e;
}
sortedEngineInfos.add(containerInfosByDeployers.get(deployer));
}
return sortedEngineInfos;
}
private void loadDeployer(List<Deployer> results, Deployer deployer, Map<Class, Deployer> typeByDeployer, Map<Class, ApplicationMetaDataProvider> typeByProvider, DeploymentContext dc)
throws IOException {
if (results.contains(deployer)) {
return;
}
results.add(deployer);
if (deployer.getMetaData()!=null) {
for (Class required : deployer.getMetaData().requires()) {
if (dc.getModuleMetaData(required)!=null) {
continue;
}
if (typeByDeployer.containsKey(required)) {
loadDeployer(results,typeByDeployer.get(required), typeByDeployer, typeByProvider, dc);
} else {
ApplicationMetaDataProvider provider = typeByProvider.get(required);
if (provider==null) {
logger.log(Level.SEVERE, KernelLoggerInfo.inconsistentLifecycleState, required);
} else {
LinkedList<ApplicationMetaDataProvider> providers = new LinkedList<ApplicationMetaDataProvider>();
addRecursively(providers, typeByProvider, provider);
for (ApplicationMetaDataProvider p : providers) {
dc.addModuleMetaData(p.load(dc));
}
}
}
}
}
}
private void addRecursively(LinkedList<ApplicationMetaDataProvider> results, Map<Class, ApplicationMetaDataProvider> providers, ApplicationMetaDataProvider provider) {
results.addFirst(provider);
for (Class type : provider.getMetaData().requires()) {
if (providers.containsKey(type)) {
addRecursively(results, providers, providers.get(type));
}
}
}
public ModuleInfo prepareModule(
List<EngineInfo> sortedEngineInfos, String moduleName,
DeploymentContext context,
ProgressTracker tracker) throws Exception {
ActionReport report = context.getActionReport();
List<EngineRef> addedEngines = new ArrayList<EngineRef>();
DeploymentTracing tracing = context.getModuleMetaData(DeploymentTracing.class);
if (tracing!=null) {
tracing.addModuleMark(DeploymentTracing.ModuleMark.PREPARE,
moduleName);
}
for (EngineInfo engineInfo : sortedEngineInfos) {
// get the deployer
Deployer deployer = engineInfo.getDeployer();
try {
if (tracing!=null) {
tracing.addContainerMark(DeploymentTracing.ContainerMark.PREPARE,
engineInfo.getSniffer().getModuleType() );
}
deployer.prepare(context);
if (tracing!=null) {
tracing.addContainerMark(DeploymentTracing.ContainerMark.PREPARED,
engineInfo.getSniffer().getModuleType() );
}
// construct an incomplete EngineRef which will be later
// filled in at loading time
EngineRef engineRef = new EngineRef(engineInfo, null);
addedEngines.add(engineRef);
tracker.add("prepared", EngineRef.class, engineRef);
tracker.add(Deployer.class, deployer);
} catch(Exception e) {
report.failure(logger, "Exception while invoking " + deployer.getClass() + " prepare method", e);
throw e;
}
}
if (tracing!=null) {
tracing.addModuleMark(DeploymentTracing.ModuleMark.PREPARE_EVENTS, moduleName);
}
if (events!=null) {
events.send(new Event<DeploymentContext>(Deployment.MODULE_PREPARED, context), false);
}
if (tracing!=null) {
tracing.addModuleMark(DeploymentTracing.ModuleMark.PREPARED,moduleName);
}
// I need to create the application info here from the context, or something like this.
// and return the application info from this method for automatic registration in the caller.
// set isComposite property on module props so we know whether to persist
// module level properties inside ModuleInfo
String isComposite = context.getAppProps().getProperty(