KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > deployment > hot > DirectoryHotDeployer


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.geronimo.deployment.hot;
18
19 import org.apache.geronimo.gbean.GBeanLifecycle;
20 import org.apache.geronimo.gbean.GBeanInfo;
21 import org.apache.geronimo.gbean.GBeanInfoBuilder;
22 import org.apache.geronimo.gbean.AbstractName;
23 import org.apache.geronimo.gbean.AbstractNameQuery;
24 import org.apache.geronimo.system.serverinfo.ServerInfo;
25 import org.apache.geronimo.deployment.plugin.factories.DeploymentFactoryImpl;
26 import org.apache.geronimo.deployment.plugin.jmx.JMXDeploymentManager;
27 import org.apache.geronimo.deployment.cli.DeployUtils;
28 import org.apache.geronimo.common.DeploymentException;
29 import org.apache.geronimo.kernel.config.PersistentConfigurationList;
30 import org.apache.geronimo.kernel.config.ConfigurationManager;
31 import org.apache.geronimo.kernel.config.Configuration;
32 import org.apache.geronimo.kernel.config.DeploymentWatcher;
33 import org.apache.geronimo.kernel.Kernel;
34 import org.apache.geronimo.kernel.repository.Artifact;
35 import org.apache.geronimo.kernel.repository.MissingDependencyException;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.apache.geronimo.deployment.util.DeploymentUtil;
39 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
40 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
41 import javax.enterprise.deploy.spi.Target JavaDoc;
42 import javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException JavaDoc;
43 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
44 import javax.enterprise.deploy.spi.factories.DeploymentFactory JavaDoc;
45
46 import java.io.File JavaDoc;
47 import java.util.Set JavaDoc;
48 import java.util.Iterator JavaDoc;
49
50 /**
51  * A directory-scanning hot deployer
52  *
53  * @version $Rev: 483713 $ $Date: 2006-12-07 17:45:45 -0500 (Thu, 07 Dec 2006) $
54  */

55 public class DirectoryHotDeployer implements HotDeployer, DeploymentWatcher, GBeanLifecycle { //todo: write unit tests
56
private static final Log log = LogFactory.getLog(DirectoryHotDeployer.class);
57
58     // Try to make this stand out as the user is likely to get a ton of errors if this comes up
59
private static final String JavaDoc BAD_LAYOUT_MESSAGE = "CANNOT DEPLOY: It looks like you unpacked an application or module " +
60             "directly into the hot deployment directory. THIS DOES NOT WORK. You need to unpack into a " +
61             "subdirectory directly under the hot deploy directory. For example, if the hot deploy directory " +
62             "is 'deploy/' and your file is 'webapp.war' then you could unpack it into a directory 'deploy/webapp.war/'";
63     private DirectoryMonitor monitor;
64     private String JavaDoc path;
65     private ServerInfo serverInfo;
66     private ConfigurationManager configManager;
67     private int pollIntervalMillis;
68     private String JavaDoc deploymentURI = "deployer:geronimo:inVM";
69     private String JavaDoc deploymentUser;
70     private String JavaDoc deploymentPassword;
71     private transient Kernel kernel;
72     private transient DeploymentFactory JavaDoc factory;
73     private transient TargetModuleID JavaDoc[] startupModules = null;
74     private transient boolean serverRunning = false;
75
76     public DirectoryHotDeployer(String JavaDoc path, int pollIntervalMillis, ServerInfo serverInfo, ConfigurationManager configManager, Kernel kernel) {
77         this.path = path;
78         this.serverInfo = serverInfo;
79         this.pollIntervalMillis = pollIntervalMillis;
80         this.kernel = kernel;
81         this.configManager = configManager;
82     }
83
84     public void deployed(Artifact id) {
85         // no action when something is deployed
86
}
87
88     public void undeployed(Artifact id) {
89         // check to see whether the artifact was hot deployed, and if so, delete it
90
monitor.removeModuleId(id);
91     }
92
93     public String JavaDoc getPath() {
94         return path;
95     }
96
97     public void setPath(String JavaDoc path) {
98         this.path = path;
99     }
100
101     public ServerInfo getServerInfo() {
102         return serverInfo;
103     }
104
105     public void setServerInfo(ServerInfo serverInfo) {
106         this.serverInfo = serverInfo;
107     }
108
109     public int getPollIntervalMillis() {
110         return pollIntervalMillis;
111     }
112
113     public void setPollIntervalMillis(int pollIntervalMillis) {
114         this.pollIntervalMillis = pollIntervalMillis;
115     }
116
117     public String JavaDoc getDeploymentURI() {
118         return deploymentURI;
119     }
120
121     public void setDeploymentURI(String JavaDoc deploymentURI) {
122         if (deploymentURI != null && !deploymentURI.trim().equals("")) {
123             this.deploymentURI = deploymentURI.trim();
124         }
125     }
126
127     public String JavaDoc getDeploymentUser() {
128         return deploymentUser;
129     }
130
131     public void setDeploymentUser(String JavaDoc deploymentUser) {
132         this.deploymentUser = deploymentUser;
133     }
134
135     public String JavaDoc getDeploymentPassword() {
136         return deploymentPassword;
137     }
138
139     public void setDeploymentPassword(String JavaDoc deploymentPassword) {
140         this.deploymentPassword = deploymentPassword;
141     }
142
143     public void doStart() throws Exception JavaDoc {
144         if (factory == null) {
145             factory = new DeploymentFactoryImpl();
146         }
147         File JavaDoc dir = serverInfo.resolve(path);
148         if (!dir.exists()) {
149             if (!dir.mkdirs()) {
150                 throw new IllegalStateException JavaDoc("Hot deploy directory " + dir.getAbsolutePath() + " does not exist and cannot be created!");
151             }
152         } else if (!dir.canRead() || !dir.isDirectory()) {
153             throw new IllegalStateException JavaDoc("Hot deploy directory " + dir.getAbsolutePath() + " is not a readable directory!");
154         }
155         DeploymentManager mgr = null;
156         try {
157             mgr = getDeploymentManager();
158             Target JavaDoc[] targets = mgr.getTargets();
159             startupModules = mgr.getAvailableModules(null, targets);
160             mgr.release();
161             mgr = null;
162             monitor = new DirectoryMonitor(dir, this, pollIntervalMillis);
163             log.debug("Hot deploy scanner intialized; starting main loop.");
164             Thread JavaDoc t = new Thread JavaDoc(monitor, "Geronimo hot deploy scanner");
165             t.setDaemon(true);
166             t.start();
167         } finally {
168             if (mgr != null) mgr.release();
169         }
170     }
171
172     public void doStop() throws Exception JavaDoc {
173         monitor.close();
174     }
175
176     public void doFail() {
177         if (monitor != null) {
178             monitor.close();
179         }
180     }
181
182     public boolean isFileDeployed(File JavaDoc file, String JavaDoc configId) {
183         try {
184             DeployUtils.identifyTargetModuleIDs(startupModules, configId, true).toArray(new TargetModuleID JavaDoc[0]);
185             return true;
186         } catch (DeploymentException e) {
187             log.debug("Found new file in deploy directory on startup with ID " + configId);
188             return false;
189         }
190     }
191
192     public boolean isServerRunning() {
193         if (serverRunning) {
194             return true;
195         }
196
197         // a bit of a hack, but the PersistentConfigurationList is the only thing that knows whether the server is full started!
198
Set JavaDoc configLists = kernel.listGBeans(new AbstractNameQuery(PersistentConfigurationList.class.getName()));
199         for (Iterator JavaDoc i = configLists.iterator(); i.hasNext();) {
200             AbstractName configListName = (AbstractName) i.next();
201             try {
202                 Boolean JavaDoc result = (Boolean JavaDoc) kernel.getAttribute(configListName, "kernelFullyStarted");
203                 if (!result.booleanValue()) {
204                     return false;
205                 }
206             } catch (Exception JavaDoc e) {
207                 log.warn("Hot deployer unable to determine whether kernel is started", e);
208             }
209         }
210         serverRunning = true;
211         return true;
212     }
213
214     public long getDeploymentTime(File JavaDoc file, String JavaDoc configId) {
215         try {
216             Artifact art = configManager.getArtifactResolver().resolveInClassLoader(Artifact.create(configId));
217             Configuration config = configManager.getConfiguration(art);
218             return config.getCreated();
219         } catch (MissingDependencyException e) {
220             log.error("Unknown configuration "+configId);
221             return -1;
222         }
223     }
224
225     public void started() {
226         startupModules = null;
227         log.debug("Initialization complete; directory scanner entering normal scan mode");
228     }
229
230     public boolean validateFile(File JavaDoc file, String JavaDoc configId) {
231         //todo: some more detailed evaluation
232
if (file.isDirectory() && (file.getName().equals("WEB-INF") || file.getName().equals("META-INF"))) {
233             log.error("(" + file.getName() + ") " + BAD_LAYOUT_MESSAGE);
234             return false;
235         }
236         return true;
237     }
238
239     public String JavaDoc fileAdded(File JavaDoc file) {
240         log.info("Deploying " + file.getName());
241         DeploymentManager mgr = null;
242         TargetModuleID JavaDoc[] modules = null;
243         boolean completed = false;
244         try {
245             mgr = getDeploymentManager();
246             Target JavaDoc[] targets = mgr.getTargets();
247             ProgressObject JavaDoc po;
248             if (DeployUtils.isJarFile(file) || file.isDirectory()) {
249                 po = mgr.distribute(targets, file, null);
250             } else {
251                 po = mgr.distribute(targets, null, file);
252             }
253             waitForProgress(po);
254             if (po.getDeploymentStatus().isCompleted()) {
255                 modules = po.getResultTargetModuleIDs();
256                 po = mgr.start(modules);
257                 waitForProgress(po);
258                 if (po.getDeploymentStatus().isCompleted()) {
259                     completed = true;
260                 } else {
261                     log.warn("Unable to start some modules for " + file.getAbsolutePath());
262                 }
263                 modules = po.getResultTargetModuleIDs();
264                 for (int i = 0; i < modules.length; i++) {
265                     TargetModuleID JavaDoc result = modules[i];
266                     log.info(DeployUtils.reformat("Deployed " + result.getModuleID() + (targets.length > 1 ? " to " + result.getTarget().getName() : "") + (result.getWebURL() == null ? "" : " @ " + result.getWebURL()), 4, 72));
267                     if (result.getChildTargetModuleID() != null) {
268                         for (int j = 0; j < result.getChildTargetModuleID().length; j++) {
269                             TargetModuleID JavaDoc child = result.getChildTargetModuleID()[j];
270                             log.info(DeployUtils.reformat(" `-> " + child.getModuleID() + (child.getWebURL() == null ? "" : " @ " + child.getWebURL()), 4, 72));
271                         }
272                     }
273                 }
274             } else {
275                  //Try to delete the module , that failed to successfully hot-deploy
276
log.error("Unable to deploy: " + po.getDeploymentStatus().getMessage());
277                 String JavaDoc delfile=file.getAbsolutePath();
278                 File JavaDoc fd = new File JavaDoc(delfile);
279                 if(fd.isDirectory()){
280                     log.info("Deleting the Directory: "+delfile);
281                     if(DeploymentUtil.recursiveDelete(fd))
282                         log.debug("Successfully deleted the Directory: "+delfile);
283                     else
284                         log.error("Couldn't delete the hot deployed directory"+delfile);
285                 }else if(fd.isFile()){
286                     log.info("Deleting the File: "+delfile);
287                     if(fd.delete()){
288                     log.debug("Successfully deleted the File: "+delfile);
289                 }else
290                     log.error("Couldn't delete the hot deployed directory"+delfile);
291                 }
292                             
293                 return null;
294             }
295         } catch (DeploymentManagerCreationException JavaDoc e) {
296             log.error("Unable to open deployer", e);
297             return null;
298         } catch (DeploymentException e) {
299             log.error("Unable to determine if file is a jar", e);
300         } finally {
301             if (mgr != null) mgr.release();
302         }
303         if (completed && modules != null) {
304             if (modules.length == 1) {
305                 return modules[0].getModuleID();
306             } else {
307                 return "";
308             }
309         } else if (modules != null) { //distribute completed but not start or something like that
310
return "";
311         } else {
312             return null;
313         }
314     }
315     
316     private DeploymentManager getDeploymentManager() throws DeploymentManagerCreationException JavaDoc {
317         DeploymentManager manager = factory.getDeploymentManager(deploymentURI, deploymentUser, deploymentPassword);
318         if (manager instanceof JMXDeploymentManager) {
319             ((JMXDeploymentManager) manager).setLogConfiguration(false, true);
320         }
321         return manager;
322     }
323
324     public boolean fileRemoved(File JavaDoc file, String JavaDoc configId) {
325         log.info("Undeploying " + file.getName());
326         DeploymentManager mgr = null;
327         try {
328             mgr = getDeploymentManager();
329             Target JavaDoc[] targets = mgr.getTargets();
330             TargetModuleID JavaDoc[] ids = mgr.getAvailableModules(null, targets);
331             ids = (TargetModuleID JavaDoc[]) DeployUtils.identifyTargetModuleIDs(ids, configId, true).toArray(new TargetModuleID JavaDoc[0]);
332             ProgressObject JavaDoc po = mgr.undeploy(ids);
333             waitForProgress(po);
334             if (po.getDeploymentStatus().isCompleted()) {
335                 TargetModuleID JavaDoc[] modules = po.getResultTargetModuleIDs();
336                 for (int i = 0; i < modules.length; i++) {
337                     TargetModuleID JavaDoc result = modules[i];
338                     log.info(DeployUtils.reformat("Undeployed " + result.getModuleID() + (targets.length > 1 ? " to " + result.getTarget().getName() : ""), 4, 72));
339                 }
340             } else {
341                 log.error("Unable to undeploy " + file.getAbsolutePath() + "(" + configId + ")" + po.getDeploymentStatus().getMessage());
342                 return false;
343             }
344         } catch (DeploymentManagerCreationException JavaDoc e) {
345             log.error("Unable to open deployer", e);
346             return false;
347         } catch (Exception JavaDoc e) {
348             log.error("Unable to undeploy", e);
349             return false;
350         } finally {
351             if (mgr != null) mgr.release();
352         }
353         return true;
354     }
355
356     public String JavaDoc getModuleId(String JavaDoc config) {
357         DeploymentManager mgr = null;
358         TargetModuleID JavaDoc[] modules = null;
359         try {
360             mgr = getDeploymentManager();
361             Target JavaDoc[] targets = mgr.getTargets();
362             TargetModuleID JavaDoc[] ids = mgr.getAvailableModules(null, targets);
363             for(int j=0;j<ids.length;j++) {
364                 String JavaDoc moduleId=ids[j].getModuleID();
365                 String JavaDoc[] parts = moduleId.split("/", -1);
366                 if (parts.length != 4) {
367                     continue;
368                 }
369                 if(parts[1] != null && parts[1].equals(config))
370                     return ids[j].getModuleID();
371             }
372         } catch(Exception JavaDoc ex){
373             log.error("Unable to getModuleId",ex);
374         }
375         return config;
376     }
377
378     public String JavaDoc fileUpdated(File JavaDoc file, String JavaDoc configId) {
379         log.info("Redeploying " + file.getName());
380         DeploymentManager mgr = null;
381         TargetModuleID JavaDoc[] modules = null;
382         try {
383             mgr = getDeploymentManager();
384             Target JavaDoc[] targets = mgr.getTargets();
385             TargetModuleID JavaDoc[] ids = mgr.getAvailableModules(null, targets);
386             ids = (TargetModuleID JavaDoc[]) DeployUtils.identifyTargetModuleIDs(ids, configId, true).toArray(new TargetModuleID JavaDoc[0]);
387             ProgressObject JavaDoc po;
388             if (DeployUtils.isJarFile(file) || file.isDirectory()) {
389                 po = mgr.redeploy(ids, file, null);
390             } else {
391                 po = mgr.redeploy(ids, null, file);
392             }
393             waitForProgress(po);
394             if (po.getDeploymentStatus().isCompleted()) {
395                 modules = po.getResultTargetModuleIDs();
396                 for (int i = 0; i < modules.length; i++) {
397                     TargetModuleID JavaDoc result = modules[i];
398                     log.info(DeployUtils.reformat("Redeployed " + result.getModuleID() + (targets.length > 1 ? " to " + result.getTarget().getName() : "") + (result.getWebURL() == null ? "" : " @ " + result.getWebURL()), 4, 72));
399                     if (result.getChildTargetModuleID() != null) {
400                         for (int j = 0; j < result.getChildTargetModuleID().length; j++) {
401                             TargetModuleID JavaDoc child = result.getChildTargetModuleID()[j];
402                             log.info(DeployUtils.reformat(" `-> " + child.getModuleID() + (child.getWebURL() == null ? "" : " @ " + child.getWebURL()), 4, 72));
403                         }
404                     }
405                 }
406             } else {
407                 log.error("Unable to undeploy " + file.getAbsolutePath() + "(" + configId + ")" + po.getDeploymentStatus().getMessage());
408             }
409         } catch (DeploymentManagerCreationException JavaDoc e) {
410             log.error("Unable to open deployer", e);
411         } catch (Exception JavaDoc e) {
412             log.error("Unable to undeploy", e);
413         } finally {
414             if (mgr != null) mgr.release();
415         }
416         if (modules != null) {
417             if (modules.length == 1) {
418                 return modules[0].getModuleID();
419             } else {
420                 return "";
421             }
422         } else {
423             return null;
424         }
425     }
426
427     private void waitForProgress(ProgressObject JavaDoc po) {
428         while (po.getDeploymentStatus().isRunning()) {
429             try {
430                 Thread.sleep(100);
431             } catch (InterruptedException JavaDoc e) {
432                 log.error(e.getMessage(), e);
433             }
434         }
435     }
436
437     public static final GBeanInfo GBEAN_INFO;
438
439     static {
440         GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(DirectoryHotDeployer.class);
441
442         infoFactory.addAttribute("path", String JavaDoc.class, true, true);
443         infoFactory.addAttribute("pollIntervalMillis", int.class, true, true);
444
445         // The next 3 args can be used to configure the hot deployer for a remote (out of VM) server
446
infoFactory.addAttribute("deploymentURI", String JavaDoc.class, true, true);
447         infoFactory.addAttribute("deploymentUser", String JavaDoc.class, true, true);
448         infoFactory.addAttribute("deploymentPassword", String JavaDoc.class, true, true);
449
450         infoFactory.addReference("ConfigManager", ConfigurationManager.class, "ConfigurationManager");
451         infoFactory.addReference("ServerInfo", ServerInfo.class, "GBean");
452         infoFactory.addAttribute("kernel", Kernel.class, false, false);
453         infoFactory.addInterface(HotDeployer.class);
454
455         infoFactory.setConstructor(new String JavaDoc[]{"path", "pollIntervalMillis", "ServerInfo", "ConfigManager", "kernel"});
456
457         GBEAN_INFO = infoFactory.getBeanInfo();
458     }
459
460     public static GBeanInfo getGBeanInfo() {
461         return GBEAN_INFO;
462     }
463 }
464
Popular Tags