KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > deployment > phasing > PEDeploymentService


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * PEDeploymentService.java
26  *
27  * Created on April 25, 2003, 11:10 AM
28  * @author sandhyae
29  * <BR> <I>$Source: /cvs/glassfish/appserv-core/src/java/com/sun/enterprise/deployment/phasing/PEDeploymentService.java,v $
30  *
31  */

32
33 package com.sun.enterprise.deployment.phasing;
34
35 import java.security.AccessControlContext JavaDoc;
36 import java.security.AccessController JavaDoc;
37 import java.security.Principal JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.Properties JavaDoc;
40 import java.io.File JavaDoc;
41 import java.util.ArrayList JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.ResourceBundle JavaDoc;
45 import java.util.logging.Level JavaDoc;
46 import java.util.logging.LogManager JavaDoc;
47 import java.util.logging.Logger JavaDoc;
48
49 import javax.management.MBeanServer JavaDoc;
50 import javax.management.ObjectName JavaDoc;
51 import javax.management.MBeanException JavaDoc;
52 import javax.management.InstanceNotFoundException JavaDoc;
53
54 import com.sun.enterprise.admin.common.exception.ServerInstanceException;
55 import com.sun.enterprise.admin.common.MBeanServerFactory;
56 import com.sun.enterprise.admin.common.ObjectNames;
57 import com.sun.enterprise.admin.event.ApplicationDeployEvent;
58 import com.sun.enterprise.admin.event.BaseDeployEvent;
59 import com.sun.enterprise.admin.event.ModuleDeployEvent;
60 import com.sun.enterprise.admin.server.core.AdminService;
61 import com.sun.enterprise.admin.util.HostAndPort;
62 import com.sun.enterprise.appverification.factory.AppVerification;
63 import com.sun.enterprise.config.ConfigContext;
64 import com.sun.enterprise.config.ConfigException;
65 import com.sun.enterprise.config.serverbeans.ServerTags;
66 import com.sun.enterprise.deployment.archivist.Archivist;
67 import com.sun.enterprise.deployment.archivist.ArchivistFactory;
68 import com.sun.enterprise.deployment.backend.ClientJarMakerRegistry;
69 import com.sun.enterprise.deployment.backend.DeployableObjectType;
70 import com.sun.enterprise.deployment.backend.DeploymentCommand;
71 import com.sun.enterprise.deployment.backend.DeploymentLogger;
72 import com.sun.enterprise.deployment.backend.DeploymentRequest;
73 import com.sun.enterprise.deployment.backend.DeploymentRequestRegistry;
74 import com.sun.enterprise.deployment.backend.DeploymentStatus;
75 import com.sun.enterprise.deployment.backend.IASDeploymentException;
76 import com.sun.enterprise.deployment.deploy.shared.InputJarArchive;
77 import com.sun.enterprise.deployment.Descriptor;
78 import com.sun.enterprise.deployment.interfaces.DeploymentImplConstants;
79 import com.sun.enterprise.deployment.util.DeploymentProperties;
80 import com.sun.enterprise.instance.InstanceEnvironment;
81 import com.sun.enterprise.management.deploy.DeploymentCallback;
82 import com.sun.enterprise.server.ApplicationServer;
83 import com.sun.enterprise.util.i18n.StringManager;
84 import com.sun.logging.LogDomains;
85 import javax.security.auth.Subject JavaDoc;
86
87 /**
88  * Manages the phases and maps deployment operations to deployment phases
89  * @author deployment dev team
90  */

91 public class PEDeploymentService extends DeploymentService {
92     
93     /** Deployment Logger object for this class */
94     public static final Logger JavaDoc sLogger = DeploymentLogger.get();
95     
96     /** Deployment auditing logger */
97     private static final Logger JavaDoc auditLogger = LogDomains.getLogger(LogDomains.DPLAUDIT_LOGGER);
98     
99     /** Auditing resource bundle for message look-up */
100     private static final ResourceBundle JavaDoc auditBundle = auditLogger.getResourceBundle();
101     
102     /** resource bundle */
103     private static StringManager localStrings =
104           StringManager.getManager( PEDeploymentService.class );
105     
106     /** context object that is used to share context with the phases */
107     protected DeploymentContext deploymentContext = null;
108     
109     /** phase list for deploy to domain operation */
110     private List JavaDoc deployToDomainPhaseList = null;
111     
112     /** phase list for undeploy from domain operation */
113     private List JavaDoc undeployFromDomainPhaseList = null;
114     
115     /** phase list for deploy operation */
116     private List JavaDoc deployPhaseList = null;
117     
118     /** phase list for undeploy operation */
119     private List JavaDoc undeployPhaseList = null;
120     
121     /** phase list for associate operation */
122     private List JavaDoc associatePhaseList = null;
123     
124     /** phase list for disassociate operation */
125     private List JavaDoc disassociatePhaseList = null;
126     
127     private List JavaDoc stopPhaseList = null;
128     
129     private List JavaDoc startPhaseList = null;
130
131     private static final String JavaDoc DISASSOCIATE_ACTION = localStrings.getString(
132                 "enterprise.deployment.phasing.action.disassociate");
133     private static final String JavaDoc REDEPLOY_ACTION = localStrings.getString(
134                 "enterprise.deployment.phasing.action.redeploy");
135     private static final String JavaDoc STOP_ACTION = localStrings.getString(
136                 "enterprise.deployment.phasing.action.stop");
137     private static final String JavaDoc UNDEPLOY_ACTION = localStrings.getString(
138                 "enterprise.deployment.phasing.action.undeploy");
139
140     /**
141      * Creates a new instance of PEDeploymentService
142      * @param configContext config context object
143      */

144     public PEDeploymentService(ConfigContext configContext)
145     {
146         deploymentContext = new DeploymentContext();
147         deploymentContext.setConfigContext(configContext);
148         initializePhases();
149     }
150
151     /**
152      *
153      */

154     protected List JavaDoc getDeployPhaseListForTarget(DeploymentRequest req) {
155
156         if (deployPhaseList != null) {
157             return deployPhaseList;
158         }
159
160         //XXX FIXME. Need to verify the type of the target.
161
J2EECPhase j2eec = new J2EECPhase(deploymentContext);
162         AssociationPhase associate = new AssociationPhase(deploymentContext);
163         ResourceAdapterStartPhase raStart =
164             new ResourceAdapterStartPhase(deploymentContext);
165         ApplicationStartPhase appStart =
166             new ApplicationStartPhase(deploymentContext);
167         PreResCreationPhase preResCreation =
168             new PreResCreationPhase(deploymentContext);
169         PostResCreationPhase postResCreation =
170             new PostResCreationPhase(deploymentContext);
171
172         //(re)deploy phaseList
173
deployPhaseList = new ArrayList JavaDoc();
174         deployPhaseList.add(j2eec);
175         deployPhaseList.add(associate);
176         deployPhaseList.add(preResCreation);
177         deployPhaseList.add(raStart);
178         deployPhaseList.add(postResCreation);
179         deployPhaseList.add(appStart);
180         return deployPhaseList;
181     }
182     
183     /**
184      * Initializes phaseList corresponding to deploy operations. Each phase is
185      * initialized with a deploymentContext object. Deployment operations that
186      * are intialized are deploy/undeploy/associate/disassociate.
187      */

188     private void initializePhases()
189     {
190         J2EECPhase j2eec = new J2EECPhase(deploymentContext);
191         AssociationPhase associate = new AssociationPhase(deploymentContext);
192         DisassociationPhase disassociate = new DisassociationPhase(deploymentContext);
193         UndeployFromDomainPhase undeploy = new UndeployFromDomainPhase(deploymentContext);
194         ResourceAdapterStartPhase raStart =
195             new ResourceAdapterStartPhase(deploymentContext);
196         ApplicationStartPhase appStart =
197             new ApplicationStartPhase(deploymentContext);
198         PreResCreationPhase preResCreation =
199             new PreResCreationPhase(deploymentContext);
200         PostResCreationPhase postResCreation =
201             new PostResCreationPhase(deploymentContext);
202
203         ResourceAdapterStopPhase raStop =
204             new ResourceAdapterStopPhase(deploymentContext);
205         ApplicationStopPhase appStop =
206             new ApplicationStopPhase(deploymentContext);
207         PreResDeletionPhase preResDeletion =
208             new PreResDeletionPhase(deploymentContext);
209         PostResDeletionPhase postResDeletion =
210             new PostResDeletionPhase(deploymentContext);
211
212         //(re)deploy to domain phaseList
213
deployToDomainPhaseList = new ArrayList JavaDoc();
214         //for special case (re)deploy to domain
215
deployToDomainPhaseList.add(preResDeletion);
216         deployToDomainPhaseList.add(postResDeletion);
217         deployToDomainPhaseList.add(j2eec);
218         deployToDomainPhaseList.add(preResCreation);
219         deployToDomainPhaseList.add(postResCreation);
220         
221         //associate phaseList
222
associatePhaseList = new ArrayList JavaDoc();
223         associatePhaseList.add(associate);
224         
225         //disassociate phaseList
226
disassociatePhaseList = new ArrayList JavaDoc();
227         disassociatePhaseList.add(disassociate);
228         
229         //undeploy phaseList
230
undeployPhaseList = new ArrayList JavaDoc();
231         undeployPhaseList.add(appStop);
232         undeployPhaseList.add(preResDeletion);
233         undeployPhaseList.add(raStop);
234         undeployPhaseList.add(postResDeletion);
235         undeployPhaseList.add(disassociate);
236         undeployPhaseList.add(undeploy);
237         
238         //undeploy from domain phaseList
239
undeployFromDomainPhaseList = new ArrayList JavaDoc();
240         undeployFromDomainPhaseList.add(preResDeletion);
241         undeployFromDomainPhaseList.add(postResDeletion);
242         undeployFromDomainPhaseList.add(undeploy);
243
244         startPhaseList = new ArrayList JavaDoc();
245         startPhaseList.add(preResCreation);
246         startPhaseList.add(raStart);
247         startPhaseList.add(postResCreation);
248         startPhaseList.add(appStart);
249         
250         stopPhaseList = new ArrayList JavaDoc();
251         stopPhaseList.add(appStop);
252         stopPhaseList.add(preResDeletion);
253         stopPhaseList.add(raStop);
254         stopPhaseList.add(postResDeletion);
255     }
256     
257
258     private DeploymentStatus deploy(DeploymentRequest req, AuditInfo auditInfo) throws IASDeploymentException {
259         // deploy to instance
260
DeploymentStatus result = null;
261         if (req.getTarget() != null &&
262             !req.getTarget().getName().equals("domain")) {
263             result = executePhases(req, getDeployPhaseListForTarget(req));
264         // deploy to domain
265
} else {
266             result = executePhases(req, deployToDomainPhaseList);
267         }
268         if (auditInfo != null) {
269             auditInfo.reportEnd(result.getStatus());
270         }
271         return result;
272     }
273     
274     /**
275      * This method deploys application to the DAS. Prepares the app, stores it in
276      * central repository and registers with config
277      * @param req DeploymentRequest object
278      */

279     public DeploymentStatus deploy(DeploymentRequest req) throws IASDeploymentException
280     {
281         return deploy(req, createAuditInfoIfOn(req, AuditInfo.Operation.deploy));
282     }
283     
284     /**
285      * This method undeploys application from DAS. Removes the application from
286      * central repository and unregisters the application from config
287      * @param req DeploymentRequest object
288      */

289     public DeploymentStatus undeploy(DeploymentRequest req) {
290         return undeploy(req, createAuditInfoIfOn(req, AuditInfo.Operation.undeploy));
291     }
292     
293     /**
294      * This method undeploys application from DAS. Removes the application from
295      * central repository and unregisters the application from config, with
296      * auditing if turned on.
297      * @param req DeploymentRequest object
298      * @param auditInfo the AuditInfo object, if any, to be used for auditing this operation
299      */

300     private DeploymentStatus undeploy(DeploymentRequest req, AuditInfo auditInfo)
301     {
302         DeploymentStatus result = null;
303         //Re-record instrospect/instrument/verifier data if
304
//any of the application is un-deployed
305
if (AppVerification.doInstrument()) {
306             AppVerification.getInstrumentLogger().handleChangeInDeployment();
307         }
308
309         // undeploy from DAS
310
if (req.getTarget() != null) {
311             result = executePhases(req, undeployPhaseList);
312         // undeploy from domain
313
} else {
314             result = executePhases(req, undeployFromDomainPhaseList);
315         }
316         if (auditInfo != null) {
317             auditInfo.reportEnd(result.getStatus());
318         }
319         return result;
320     }
321     
322
323     /**
324      * Associates an application to a target.
325      * @param req the DeploymentRequest
326      * @param auditInfo the auditing information object that will audit this operation; null if no auditing desired
327      * @return DeploymentStatus reporting the outcome of the operation
328      */

329     private DeploymentStatus associate(DeploymentRequest req, AuditInfo auditInfo) {
330         DeploymentStatus result = executePhases(req, associatePhaseList);
331         if (auditInfo != null) {
332             auditInfo.reportEnd(result.getStatus());
333         }
334         return result;
335     }
336     
337     /**
338      * This method is used to associate an application to a target.
339      * @param req DeploymentRequest object
340      */

341     public DeploymentStatus associate(DeploymentRequest req)
342         throws IASDeploymentException {
343         return associate(req, createAuditInfoIfOn(req, AuditInfo.Operation.associate));
344     }
345
346    /**
347      * This method is used to associate an application to a target.
348      * It constructs the DeploymentRequest using the parameters first.
349      */

350     public DeploymentStatus associate(String JavaDoc targetName,
351         boolean enabled, String JavaDoc virtualServers, String JavaDoc referenceName)
352         throws IASDeploymentException {
353         try {
354             long startTime = System.currentTimeMillis();
355             //FIXME: add validation code such as checking context root
356
DeployableObjectType type =
357                 DeploymentServiceUtils.getRegisteredType(referenceName);
358         
359             final DeploymentTarget target =
360                 DeploymentServiceUtils.getAndValidateDeploymentTarget(
361                     targetName, referenceName, false);
362             
363             InstanceEnvironment env =
364                 ApplicationServer.getServerContext().getInstanceEnvironment();
365             DeploymentRequest req = new DeploymentRequest(
366                                     env,
367                                     type,
368                                     DeploymentCommand.DEPLOY);
369
370             req.setName(referenceName);
371             req.setStartOnDeploy(enabled);
372             req.setTarget(target);
373
374             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
375             if(virtualServers!=null) {
376                 optionalAttributes.put(ServerTags.VIRTUAL_SERVERS,
377                     virtualServers);
378             }
379             req.setOptionalAttributes(optionalAttributes);
380             return associate(req, createAuditInfoIfOn(req, AuditInfo.Operation.associate, startTime));
381         } catch(Exception JavaDoc e) {
382             if (e instanceof IASDeploymentException) {
383                 throw (IASDeploymentException)e;
384             }
385             else {
386                 throw new IASDeploymentException(e);
387             }
388         }
389     }
390
391     /**
392      * This method is used to associate an application to a target.
393      * It constructs the DeploymentRequest using the parameters first.
394      */

395     public DeploymentStatus associate(String JavaDoc targetName,
396         String JavaDoc referenceName, Map JavaDoc options) throws IASDeploymentException {
397         try {
398             long startTime = System.currentTimeMillis();
399             DeployableObjectType type =
400                 DeploymentServiceUtils.getRegisteredType(referenceName);
401
402             final DeploymentTarget target =
403                 DeploymentServiceUtils.getAndValidateDeploymentTarget(
404                     targetName, referenceName, false);
405
406             InstanceEnvironment env =
407                 ApplicationServer.getServerContext().getInstanceEnvironment();
408             DeploymentRequest req = new DeploymentRequest(
409                                     env,
410                                     type,
411                                     DeploymentCommand.DEPLOY);
412
413             DeploymentProperties dProps = new DeploymentProperties(options);
414             String JavaDoc virtualServers = dProps.getVirtualServers();
415             boolean enabled = dProps.getEnable();
416
417             req.setName(referenceName);
418             req.setStartOnDeploy(enabled);
419             req.setTarget(target);
420             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
421
422             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
423             if(virtualServers!=null) {
424                 optionalAttributes.put(ServerTags.VIRTUAL_SERVERS,
425                     virtualServers);
426             }
427             req.setOptionalAttributes(optionalAttributes);
428
429             return associate(req, createAuditInfoIfOn(req, AuditInfo.Operation.associate, startTime));
430
431         } catch(Exception JavaDoc e) {
432             if (e instanceof IASDeploymentException) {
433                 throw (IASDeploymentException)e;
434             }
435             else {
436                 throw new IASDeploymentException(e);
437             }
438         }
439     }
440
441     private DeploymentStatus disassociate(DeploymentRequest req, AuditInfo auditInfo)
442         throws IASDeploymentException {
443         String JavaDoc moduleID = req.getName();
444         DeployableObjectType type = req.getType();
445         boolean isRegistered =
446             DeploymentServiceUtils.isRegistered(moduleID, type);
447         if (isRegistered) {
448             DeploymentServiceUtils.validate(moduleID,type,DISASSOCIATE_ACTION);
449         }
450         DeploymentStatus result = executePhases(req, disassociatePhaseList);
451         if (auditInfo != null) {
452             auditInfo.reportEnd(result.getStatus());
453         }
454         return result;
455     }
456     
457     /**
458      * This method removes references of an application on a particular target
459      * @param req DeploymentRequest object
460      */

461     public DeploymentStatus disassociate(DeploymentRequest req)
462         throws IASDeploymentException {
463         return disassociate(req, createAuditInfoIfOn(req, AuditInfo.Operation.disassociate));
464     }
465     
466     /**
467      * This method removes references of an application on a particular target
468      * It constructs the DeploymentRequest using the parameters first.
469      */

470     public DeploymentStatus disassociate(String JavaDoc targetName,
471         String JavaDoc referenceName) throws IASDeploymentException {
472         try {
473             long startTime = System.currentTimeMillis();
474             DeployableObjectType type =
475                 DeploymentServiceUtils.getRegisteredType(referenceName);
476             
477             final DeploymentTarget target =
478                 DeploymentServiceUtils.getAndValidateDeploymentTarget(
479                 targetName, referenceName, true);
480                 
481             InstanceEnvironment env =
482                 ApplicationServer.getServerContext().getInstanceEnvironment();
483             DeploymentRequest req = new DeploymentRequest(
484                                     env,
485                                     type,
486                                     DeploymentCommand.UNDEPLOY);
487
488             req.setName(referenceName);
489             req.setTarget(target);
490         
491             return disassociate(req, createAuditInfoIfOn(req, AuditInfo.Operation.disassociate, startTime));
492         } catch(Exception JavaDoc e) {
493             if (e instanceof IASDeploymentException) {
494                 throw (IASDeploymentException)e;
495             }
496             else {
497                throw new IASDeploymentException(e);
498             }
499         }
500     }
501
502     public DeploymentStatus disassociate(String JavaDoc targetName,
503         String JavaDoc referenceName, Map JavaDoc options) throws IASDeploymentException {
504         try {
505             long startTime = System.currentTimeMillis();
506             DeployableObjectType type =
507                 DeploymentServiceUtils.getRegisteredType(referenceName);
508
509             final DeploymentTarget target =
510                 DeploymentServiceUtils.getAndValidateDeploymentTarget(
511                 targetName, referenceName, true);
512
513             InstanceEnvironment env =
514                 ApplicationServer.getServerContext().getInstanceEnvironment();
515             DeploymentRequest req = new DeploymentRequest(
516                                     env,
517                                     type,
518                                     DeploymentCommand.UNDEPLOY);
519
520             req.setName(referenceName);
521             req.setTarget(target);
522
523             DeploymentProperties dProps = new DeploymentProperties(options);
524             req.setCascade(dProps.getCascade());
525             req.setForced(dProps.getForce());
526             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
527
528             return disassociate(req, createAuditInfoIfOn(req, AuditInfo.Operation.disassociate, startTime));
529         } catch(Exception JavaDoc e) {
530             if (e instanceof IASDeploymentException) {
531                 throw (IASDeploymentException)e;
532             }
533             else {
534                 throw new IASDeploymentException(e);
535             }
536         }
537     }
538
539     private DeploymentStatus start(DeploymentRequest req, AuditInfo auditInfo)
540     {
541         DeploymentStatus result = executePhases(req, startPhaseList);
542         if (auditInfo != null) {
543             auditInfo.reportEnd(result.getStatus());
544         }
545         return result;
546     }
547     
548     public DeploymentStatus start(DeploymentRequest req) {
549         return start(req, createAuditInfoIfOn(req, AuditInfo.Operation.start));
550     }
551
552     public DeploymentStatus start(String JavaDoc moduleID, String JavaDoc targetName,
553         Map JavaDoc options) throws IASDeploymentException {
554         try {
555             long startTime = System.currentTimeMillis();
556             DeployableObjectType type =
557                 DeploymentServiceUtils.getRegisteredType(moduleID);
558         
559             final DeploymentTarget target =
560                 DeploymentServiceUtils.getDeploymentTarget(targetName);
561             
562             InstanceEnvironment env =
563                 ApplicationServer.getServerContext().getInstanceEnvironment();
564             DeploymentRequest req = new DeploymentRequest(
565                                     env,
566                                     type,
567                                     DeploymentCommand.DEPLOY);
568
569             int actionCode;
570             if(type.isAPP()) {
571                 actionCode = BaseDeployEvent.APPLICATION_DEPLOYED;
572             }
573             else {
574                 actionCode = BaseDeployEvent.MODULE_DEPLOYED;
575             }
576     
577             req.setName(moduleID);
578             req.setActionCode(actionCode);
579             req.setTarget(target);
580
581             DeploymentProperties dProps = new DeploymentProperties(options);
582             req.setForced(dProps.getForce());
583             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
584
585             return start(req, createAuditInfoIfOn(req, AuditInfo.Operation.start, startTime));
586        } catch(Exception JavaDoc e) {
587             if (e instanceof IASDeploymentException) {
588                 throw (IASDeploymentException)e;
589             }
590             else {
591                 throw new IASDeploymentException(e);
592             }
593         }
594     }
595
596     private DeploymentStatus stop(DeploymentRequest req, AuditInfo auditInfo)
597         throws IASDeploymentException {
598         String JavaDoc moduleID = req.getName();
599         DeployableObjectType type = req.getType();
600         boolean isRegistered =
601             DeploymentServiceUtils.isRegistered(moduleID, type);
602         if (isRegistered) {
603             DeploymentServiceUtils.validate(moduleID,type,STOP_ACTION);
604         }
605
606         DeploymentStatus result = executePhases(req, stopPhaseList);
607         if (auditInfo != null) {
608             auditInfo.reportEnd(result.getStatus());
609         }
610         return result;
611     }
612     
613     public DeploymentStatus stop(DeploymentRequest req)
614         throws IASDeploymentException {
615         return stop(req, createAuditInfoIfOn(req, AuditInfo.Operation.stop));
616     }
617
618     public DeploymentStatus stop(String JavaDoc moduleID, String JavaDoc targetName,
619         Map JavaDoc options) throws IASDeploymentException {
620         try {
621             long startTime = System.currentTimeMillis();
622             DeployableObjectType type =
623                 DeploymentServiceUtils.getRegisteredType(moduleID);
624      
625             final DeploymentTarget target =
626                 DeploymentServiceUtils.getDeploymentTarget(targetName);
627         
628             InstanceEnvironment env =
629                 ApplicationServer.getServerContext().getInstanceEnvironment();
630             DeploymentRequest req = new DeploymentRequest(
631                                     env,
632                                     type,
633                                     DeploymentCommand.UNDEPLOY);
634                 
635             int actionCode;
636             if(type.isAPP()) {
637                 actionCode = BaseDeployEvent.APPLICATION_UNDEPLOYED;
638             }
639             else {
640                 actionCode = BaseDeployEvent.MODULE_UNDEPLOYED;
641             }
642                                     
643             req.setName(moduleID);
644             req.setActionCode(actionCode);
645             req.setTarget(target);
646
647             DeploymentProperties dProps = new DeploymentProperties(options);
648             req.setCascade(dProps.getCascade());
649             req.setForced(dProps.getForce());
650             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
651
652             return stop(req, createAuditInfoIfOn(req, AuditInfo.Operation.stop, startTime));
653         } catch(Exception JavaDoc e) {
654             if (e instanceof IASDeploymentException) {
655                 throw (IASDeploymentException)e;
656             }
657             else {
658                 throw new IASDeploymentException(e);
659             }
660         }
661     }
662
663     
664    /**
665      * This method deploys application to the domain.
666      * It constructs the DeploymentRequest using the parameters first.
667      */

668     public DeploymentStatus deploy(File JavaDoc deployFile, File JavaDoc planFile,
669         String JavaDoc archiveName, String JavaDoc moduleID, DeploymentProperties dProps,
670         DeploymentCallback callback) throws IASDeploymentException {
671         try {
672             if (deployFile == null) {
673                 throw new IASDeploymentException(
674                 localStrings.getString("deployfile_not_specified"));
675             }
676
677             /*
678              *Save the current time to use in preparing the audit info later so
679              *the audit measurement includes all the logic below.
680              */

681             long startTime = System.currentTimeMillis();
682             sLogger.log(Level.FINE, "mbean.begin_deploy", moduleID);
683             DeployableObjectType type = null;
684             if (dProps.getType() != null) {
685                 type = DeploymentServiceUtils.getDeployableObjectType(dProps.getType());
686             } else {
687                 type = DeploymentServiceUtils.getTypeFromFile(
688                             moduleID, deployFile.getAbsolutePath());
689             }
690
691             InstanceEnvironment env =
692                 ApplicationServer.getServerContext().getInstanceEnvironment();
693             DeploymentRequest req = new DeploymentRequest(
694                                     env,
695                                     type,
696                                     DeploymentCommand.DEPLOY);
697     
698             DeploymentRequestRegistry.getRegistry().addDeploymentRequest(
699                 moduleID, req);
700
701             req.setName(moduleID);
702             boolean isRegistered = false;
703             isRegistered = DeploymentServiceUtils.isRegistered(moduleID, type);
704             // FIXME validation for new REDEPLOY property
705

706             if (isRegistered) {
707                 DeploymentServiceUtils.validate(moduleID,type,REDEPLOY_ACTION);
708             }
709
710             req.setFileSource(deployFile);
711             req.setDeploymentPlan(planFile);
712             req.setForced(dProps.getForce());
713             if(type.isWEB()) {
714                 req.setDefaultContextRoot(dProps.getDefaultContextRoot(
715                     archiveName));
716                 req.setContextRoot(dProps.getContextRoot());
717             }
718             req.setVerifying(dProps.getVerify());
719             req.setPrecompileJSP(dProps.getPrecompileJSP());
720             req.setGenerateRMIStubs(dProps.getGenerateRMIStubs());
721             req.setAvailabilityEnabled(dProps.getAvailabilityEnabled());
722             req.setStartOnDeploy(dProps.getEnable());
723             req.setDescription(dProps.getDescription());
724             req.setLibraries(dProps.getLibraries());
725             req.setJavaWebStartEnabled(dProps.getJavaWebStartEnabled());
726             req.setDeploymentCallback(callback);
727             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
728
729             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
730             String JavaDoc virtualServers = dProps.getVirtualServers();
731             if(virtualServers!=null) {
732                 optionalAttributes.put(ServerTags.VIRTUAL_SERVERS,
733                     virtualServers);
734             }
735             req.setOptionalAttributes(optionalAttributes);
736
737             req.addOptionalArguments(dProps.prune());
738             DeploymentServiceUtils.setHostAndPort(req);
739             return deploy(req, createAuditInfoIfOn(req, AuditInfo.Operation.deploy, startTime));
740         } catch(Exception JavaDoc e) {
741             sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
742             if (e instanceof IASDeploymentException) {
743                 throw (IASDeploymentException)e;
744             }
745             else {
746                 throw new IASDeploymentException(e);
747             }
748         }
749     }
750
751     /**
752      * This method undeploys application from domain.
753      * It constructs the DeploymentRequest using the parameters first.
754      *
755      */

756     public DeploymentStatus undeploy(String JavaDoc mModuleID,
757         Map JavaDoc mParams) throws IASDeploymentException {
758         sLogger.log(Level.FINE, "mbean.begin_undeploy", mModuleID);
759         try {
760             /*
761              *Save the current time to use in preparing the audit info later so
762              *the audit measurement includes all the logic below.
763              */

764             long startTime = System.currentTimeMillis();
765             DeployableObjectType objectType =
766                 DeploymentServiceUtils.getRegisteredType(mModuleID);
767
768             DeploymentServiceUtils.checkAppReferencesBeforeUndeployFromDomain(
769                 mModuleID);
770
771             DeploymentServiceUtils.validate(mModuleID, objectType, UNDEPLOY_ACTION);
772
773             if (objectType.isWEB()) {
774                 DeploymentServiceUtils.checkWebModuleReferences(mModuleID);
775             }
776
777             InstanceEnvironment env =
778                 ApplicationServer.getServerContext().getInstanceEnvironment();
779             DeploymentRequest req = new DeploymentRequest(env,
780                 objectType, DeploymentCommand.UNDEPLOY);
781
782             DeploymentRequestRegistry.getRegistry().addDeploymentRequest(
783                 mModuleID, req);
784
785             DeploymentProperties dProps =
786                 new DeploymentProperties(mParams);
787             req.setName(mModuleID);
788             req.setCascade(dProps.getCascade());
789
790             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
791
792             req.addOptionalArguments(dProps.prune());
793             return undeploy(req, createAuditInfoIfOn(req, AuditInfo.Operation.undeploy, startTime));
794         }
795         catch(Exception JavaDoc e) {
796             String JavaDoc msg = localStrings.getString(
797             "enterprise.deployment.phasing.deploymentservice.undeploy.failed",
798             mModuleID, e.getLocalizedMessage());
799             sLogger.log(Level.WARNING, msg);
800             if (e instanceof IASDeploymentException) {
801                 throw (IASDeploymentException)e;
802             }
803             else {
804                 IASDeploymentException ias =
805                     new IASDeploymentException(e.getLocalizedMessage());
806                 ias.initCause(e);
807                 throw ias;
808             }
809         }
810     }
811
812     public boolean quit(String JavaDoc moduleID) {
813         DeploymentRequest request = DeploymentRequestRegistry.getRegistry().getDeploymentRequest(moduleID);
814         if (request != null) {
815             request.setAbort(true);
816             return true;
817         } else {
818             return false;
819         }
820     }
821
822     /**
823      * @return the path for the client jar file of a deployed application
824      */

825     public static String JavaDoc getClientJarPath(String JavaDoc moduleID) {
826         
827         // let's ensure first that our client jar is ready.
828
ClientJarMakerRegistry registry = ClientJarMakerRegistry.getInstance();
829         
830         if (registry.isRegistered(moduleID)) {
831             
832             // let's wait until it is finished.
833
registry.waitForCompletion(moduleID);
834         }
835         
836         return moduleID + DeploymentImplConstants.ClientJarSuffix;
837         
838     }
839     
840     /**
841      * utility method to succesively invoke DeploymentPhases instances
842      * provided as a list and rollback them in case of an exception
843      * during one of the phase execution
844      *<p>
845      *Note - after the phases are executed executePhases invokes the done
846      *method on the DeploymentRequest to release its resources, in particular
847      *the EJBClassLoaders. The DeploymentRequest cannot be reused for
848      *another deployment upon return from executePhases.
849      *
850      * @param DeploymentRequest the request to be served
851      * @param phases is the @see List of phases to execute
852      */

853     protected DeploymentStatus executePhases(DeploymentRequest req, List JavaDoc phases)
854     {
855         try {
856             Descriptor.setBoundsChecking(true);
857
858             // first we create our deployment status to return feedback to the user
859
DeploymentStatus ds = new DeploymentStatus();
860             ds.setStageDescription("Deployment");
861             req.setCurrentDeploymentStatus(ds);
862
863             DeploymentPhaseContext phaseCtx[] = new DeploymentPhaseContext[phases.size()];
864             for(int i=0 ; i < phases.size() ; i++)
865             {
866                 try{
867                     // create a new status for this phase
868
DeploymentStatus phaseDs = new DeploymentStatus(ds);
869
870                     // execute the phase
871
phaseCtx[i] = ((DeploymentPhase)phases.get(i)).executePhase(req, phaseDs);
872
873                     // if the previous phase did not excecute successfully.
874
// we need to allow previous phases to rollback.
875
if (phaseDs.getStageStatus()<DeploymentStatus.WARNING) {
876                         rollbackPhases(phases, phaseCtx, i-1);
877                         // return main deployment status
878
return ds;
879                     }
880
881                 } catch(Throwable JavaDoc dpe) {
882                     // an exception has occured in the I'th phase, we need to rollback
883
// all previously executed phases (and ignore any failures that may
884
// be raised by this rollback).
885

886                     String JavaDoc msg =
887                         localStrings.getString( "enterprise.deployment.phasing.deploymentservice.exception");
888                     sLogger.log(Level.SEVERE, msg ,dpe);
889                     rollbackPhases(phases, phaseCtx, i-1);
890
891                     // we register the original exception as it was raised
892
// by the executePhase method in our deployment status
893
ds.setStageStatus(DeploymentStatus.FAILURE);
894                     if (dpe instanceof java.io.Serializable JavaDoc) {
895                         ds.setStageException(dpe);
896                     } else {
897                         sLogger.severe(localStrings.getString("enterprise.deployment.phasing.exception_notserializable", dpe.getClass()));
898                         sLogger.severe(localStrings.getString("enterprise.deployment.phasing.exception_notforwarded", dpe.getMessage()));
899                     }
900                     ds.setStageException(dpe);
901                     ds.setStageStatusMessage(dpe.getMessage());
902                     return ds;
903                 }
904             }
905             // we do not set the state of the deployment status
906
// since it will be provided by the sub phases status.
907
return ds;
908         } finally {
909             req.done();
910         }
911     }
912     
913     /**
914      * Rollback previously excuted phases
915      */

916     private void rollbackPhases(List JavaDoc phases, DeploymentPhaseContext phaseCtx[], int index) {
917         // now we are going to rollback all the previously executed phases
918
for (int j=index; j>=0 ; j--) {
919             try {
920                 ((DeploymentPhase)phases.get(j)).rollback(phaseCtx[j]);
921             } catch(Exception JavaDoc rollbackException) {
922                 // it failed ! just log
923
String JavaDoc msg =
924                     localStrings.getString( "enterprise.deployment.phasing.deploymentservice.rollbackexception");
925                 sLogger.log(Level.INFO, msg ,rollbackException);
926                 // we swallow the exception to allow all phases to execute their
927
// rollback
928

929             }
930         }
931         
932     }
933
934     /**
935      * This method finds moduleID by explicitly loading the dd for its
936      * display name.
937      * This method is called by the DeployThread if and only if the client
938      * uses JSR88.distribute with InputStream signature.
939      * @@ todo: Ideally we do not want to load the deployment descriptor
940      * more than once. This one is a necessary evil since we need the
941      * moduleID *now* before proceeding with the rest of deployment.
942      * Bigger re-construction is needed if we want to optimize deployment
943      * further for JSR88 using InputStream.
944      * NOTE that we choose to load the dd and use the display name as
945      * the moduleID instead of the uploaded file name for backward
946      * compatibility and clarity (uploaded file name is not descriptive).
947      * @param file the deployed file
948      * @return the moduleID derived from this file using the dd's display name
949      */

950     public String JavaDoc getModuleIDFromDD (File JavaDoc file) throws Exception JavaDoc {
951         Archivist source = ArchivistFactory.getArchivistForArchive(file);
952         InputJarArchive archive = new InputJarArchive();
953         archive.open(file.getAbsolutePath());
954         Descriptor descriptor = null;
955         String JavaDoc moduleID = null;
956         String JavaDoc displayName = null;
957         try {
958             descriptor = source.readStandardDeploymentDescriptor(archive);
959         } catch (Exception JavaDoc ex) {}
960         if (descriptor != null) {
961             displayName = descriptor.getDisplayName();
962         }
963         if ((displayName != null) && (displayName.length() > 0)) {
964             moduleID = displayName;
965         } else {
966             //We give up. Use the uploaded file name instead
967
moduleID =
968                 (new DeploymentProperties()).getName(file.getAbsolutePath());
969         }
970
971         moduleID = moduleID.replace(' ','_');
972
973         // This moduleID will be later used to construct file path,
974
// replace the illegal characters in file name
975
// \ / : * ? " < > | with _
976
moduleID = moduleID.replace('\\', '_').replace('/', '_');
977         moduleID = moduleID.replace(':', '_').replace('*', '_');
978         moduleID = moduleID.replace('?', '_').replace('"', '_');
979         moduleID = moduleID.replace('<', '_').replace('>', '_');
980         moduleID = moduleID.replace('|', '_');
981
982         // This moduleID will also be used to construct an ObjectName
983
// to register the module, so replace additional special
984
// characters , = used in property parsing with -
985
moduleID = moduleID.replace(',', '_').replace('=', '_');
986
987         return moduleID;
988     }
989     
990     /**
991      *Returns an instance of AuditInfo if the audit logging level mandates; null otherwise.
992      *@param req the DeploymentRequest to be audited
993      *@param operation the type of work being performed (deployment, undeployment, etc.)
994      *@return AuditInfo or null, depending on the deployment audit logging level
995      */

996     private AuditInfo createAuditInfoIfOn(DeploymentRequest req, AuditInfo.Operation operation) {
997         return auditLogger.isLoggable(Level.INFO) ? new AuditInfo(req, operation, System.currentTimeMillis()) : null;
998     }
999
1000    /**
1001     *Returns an instance of AuditInfo if the audit logging level mandates; null otherwise.
1002     *@param req the DeploymentRequest to be audited
1003     *@param operation the type of work being performed (deployment, undeployment, etc.)
1004     *@param startTime start time of the operation being audited (typically via System.currentTimeMillis() )
1005     *@return AuditInfo or null, depending on the deployment audit logging level
1006     */

1007    private AuditInfo createAuditInfoIfOn(DeploymentRequest req, AuditInfo.Operation operation, long startTime) {
1008        return auditLogger.isLoggable(Level.INFO) ? new AuditInfo(req, operation, startTime) : null;
1009    }
1010    
1011    /**
1012     *Records information about auditing of a deployment operation and creates the
1013     *auditing messages.
1014     */

1015    private static class AuditInfo {
1016 
1017        /** keys for the audit messages */
1018        private static final String JavaDoc START_MESSAGE_KEY = "audit.start.message";
1019        private static final String JavaDoc END_MESSAGE_KEY = "audit.end.message";
1020        
1021        /**
1022         * possible outcome values when reporting completion of an operation
1023         * Note that these same values must be used in the LogStrings.properties file
1024         * message keys.
1025         */

1026        enum Outcome {end(DeploymentStatus.SUCCESS), warning(DeploymentStatus.WARNING), fail(DeploymentStatus.FAILURE);
1027            private int deploymentStatus;
1028            
1029            Outcome(int deploymentStatus) {
1030                this.deploymentStatus = deploymentStatus;
1031            }
1032            
1033            private boolean matches(int deploymentStatus) {
1034                return (deploymentStatus == this.deploymentStatus);
1035            }
1036            
1037            private String JavaDoc getAuditMessage() {
1038                return auditBundle.getString("audit.outcome." + toString());
1039            }
1040        }
1041        
1042        /**
1043         * possible operation types - these values must also be used in
1044         * LogStrings.properties message keys
1045         */

1046        enum Operation {deploy, undeploy, associate, disassociate, start, stop;
1047            private String JavaDoc getAuditMessage() {
1048                return auditBundle.getString("audit.operation." + toString());
1049                
1050            }
1051        
1052        }
1053        
1054        /** when the operation started */
1055        private long startTime;
1056        
1057        /** name of the principal under which the operation is running */
1058        private String JavaDoc principal;
1059        
1060        /** the deployment request being performed */
1061        private DeploymentRequest request;
1062        
1063        /**
1064         * operation this AuditInfo instance corresponds to
1065         */

1066        private Operation operation;
1067
1068        /**
1069         *Creates a new instance of AuditInfo, providing the current time as
1070         *the operation start time.
1071         *@param req the DeploymentRequest being performed
1072         *@param operation the Operation being performed
1073         *@param startTime when the operation started
1074         */

1075        private AuditInfo(DeploymentRequest req, Operation operation, long startTime) {
1076            request = req;
1077            this.startTime = startTime;
1078            this.operation = operation;
1079            principal = "Unknown";
1080            AccessControlContext JavaDoc acc = AccessController.getContext();
1081            Subject JavaDoc subject = Subject.getSubject(acc);
1082            if (subject == null) {
1083
1084            } else {
1085                Iterator JavaDoc iter = subject.getPrincipals().iterator();
1086                // retrieve only the first principal
1087
if (iter.hasNext()) {
1088                    Principal JavaDoc p = (Principal JavaDoc) iter.next();
1089                    principal = p.getName();
1090                }
1091            }
1092            auditLogger.log(Level.INFO, START_MESSAGE_KEY, new String JavaDoc[]{ principal, operation.getAuditMessage(), request.getName(), request.getType().toString() } );
1093        }
1094        
1095        /**
1096         * Logs the ending deployment audit information.
1097         * @param outcome String set to one of "end," "warning," or "fail"
1098         */

1099        private void reportEnd(int deploymentStatus) {
1100            auditLogger.log(Level.INFO, END_MESSAGE_KEY, computeEndParameters(findOutcome(deploymentStatus)));
1101        }
1102
1103        private Outcome findOutcome(int deploymentStatus) {
1104            Outcome result = null;
1105            for (Outcome outcome : Outcome.values() ) {
1106                if (outcome.matches(deploymentStatus) ) {
1107                    result = outcome;
1108                    break;
1109                }
1110            }
1111            if (result == null) {
1112                throw new IllegalArgumentException JavaDoc("Deployment status value of " + deploymentStatus + " could not be mapped to an audit outcome");
1113            }
1114            return result;
1115        }
1116        
1117        /**
1118         * Prepares the message parameters for the ending message.
1119         * @return String array suitable for passing to the logger.log method.
1120         */

1121        private String JavaDoc[] computeEndParameters(Outcome outcome) {
1122            String JavaDoc[] result = new String JavaDoc[]
1123                {principal,
1124                 operation.getAuditMessage(),
1125                 outcome.getAuditMessage(),
1126                 request.getName(),
1127                 request.getType().toString(),
1128                 String.valueOf(System.currentTimeMillis() - startTime)
1129                 };
1130             return result;
1131        }
1132    }
1133}
1134
Popular Tags