File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\WebAppMain.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jean-Baptiste Quenot, Tom Huybrechts
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson;
25
26 import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
27 import com.thoughtworks.xstream.core.JVM;
28 import hudson.model.Hudson;
29 import jenkins.model.Jenkins;
30 import hudson.util.HudsonIsLoading;
31 import hudson.util.IncompatibleServletVersionDetected;
32 import hudson.util.IncompatibleVMDetected;
33 import hudson.util.InsufficientPermissionDetected;
34 import hudson.util.NoHomeDir;
35 import hudson.util.RingBufferLogHandler;
36 import hudson.util.NoTempDir;
37 import hudson.util.IncompatibleAntVersionDetected;
38 import hudson.util.HudsonFailedToLoad;
39 import hudson.util.ChartUtil;
40 import hudson.util.AWTProblem;
41 import org.jvnet.localizer.LocaleProvider;
42 import org.kohsuke.stapler.jelly.JellyFacet;
43 import org.apache.tools.ant.types.FileSet;
44
45 import javax.naming.Context;
46 import javax.naming.InitialContext;
47 import javax.naming.NamingException;
48 import javax.servlet.ServletContext;
49 import javax.servlet.ServletContextEvent;
50 import javax.servlet.ServletContextListener;
51 import javax.servlet.ServletResponse;
52 import javax.xml.transform.TransformerFactory;
53 import javax.xml.transform.TransformerFactoryConfigurationError;
54 import java.io.File;
55 import java.io.IOException;
56 import java.net.URL;
57 import java.net.URLClassLoader;
58 import java.util.Locale;
59 import java.util.logging.Level;
60 import java.util.logging.Logger;
61 import java.security.Security;
62
63 /**
64 * Entry point when Hudson is used as a webapp.
65 *
66 * @author Kohsuke Kawaguchi
67 */
68 public final class WebAppMain implements ServletContextListener {
69 private final RingBufferLogHandler handler = new RingBufferLogHandler();
70 private static final String APP = "app";
71 private boolean terminated;
72 private Thread initThread;
73
74 /**
75 * Creates the sole instance of {@link jenkins.model.Jenkins} and register it to the {@link ServletContext}.
76 */
77 public void contextInitialized(ServletContextEvent event) {
78 try {
79 final ServletContext context = event.getServletContext();
80
81 // use the current request to determine the language
82 LocaleProvider.setProvider(new LocaleProvider() {
83 public Locale get() {
84 return Functions.getCurrentLocale();
85 }
86 });
87
88 // quick check to see if we (seem to) have enough permissions to run. (see #719)
89 JVM jvm;
90 try {
91 jvm = new JVM();
92 new URLClassLoader(new URL[0],getClass().getClassLoader());
93 } catch(SecurityException e) {
94 context.setAttribute(APP,new InsufficientPermissionDetected(e));
95 return;
96 }
97
98 try {// remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483
99 Security.removeProvider("SunPKCS11-Solaris");
100 } catch (SecurityException e) {
101 // ignore this error.
102 }
103
104 installLogger();
105
106 final FileAndDescription describedHomeDir = getHomeDir(event);
107 final File home = describedHomeDir.file.getAbsoluteFile();
108 home.mkdirs();
109 System.out.println("Jenkins home directory: "+home+" found at: "+describedHomeDir.description);
110
111 // check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
112 if (! home.exists()) {
113 context.setAttribute(APP,new NoHomeDir(home));
114 return;
115 }
116
117 // make sure that we are using XStream in the "enhanced" (JVM-specific) mode
118 if(jvm.bestReflectionProvider().getClass()==PureJavaReflectionProvider.class) {
119 // nope
120 context.setAttribute(APP,new IncompatibleVMDetected());
121 return;
122 }
123
124 // JNA is no longer a hard requirement. It's just nice to have. See HUDSON-4820 for more context.
125 // // make sure JNA works. this can fail if
126 // // - platform is unsupported
127 // // - JNA is already loaded in another classloader
128 // // see http://wiki.jenkins-ci.org/display/JENKINS/JNA+is+already+loaded
129 // // TODO: or shall we instead modify Hudson to work gracefully without JNA?
130 // try {
131 // /*
132 // java.lang.UnsatisfiedLinkError: Native Library /builds/apps/glassfish/domains/hudson-domain/generated/jsp/j2ee-modules/hudson-1.309/loader/com/sun/jna/sunos-sparc/libjnidispatch.so already loaded in another classloader
133 // at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1743)
134 // at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1674)
135 // at java.lang.Runtime.load0(Runtime.java:770)
136 // at java.lang.System.load(System.java:1005)
137 // at com.sun.jna.Native.loadNativeLibraryFromJar(Native.java:746)
138 // at com.sun.jna.Native.loadNativeLibrary(Native.java:680)
139 // at com.sun.jna.Native.<clinit>(Native.java:108)
140 // at hudson.util.jna.GNUCLibrary.<clinit>(GNUCLibrary.java:86)
141 // at hudson.Util.createSymlink(Util.java:970)
142 // at hudson.model.Run.run(Run.java:1174)
143 // at hudson.matrix.MatrixBuild.run(MatrixBuild.java:149)
144 // at hudson.model.ResourceController.execute(ResourceController.java:88)
145 // at hudson.model.Executor.run(Executor.java:123)
146 // */
147 // String.valueOf(Native.POINTER_SIZE); // this meaningless operation forces the classloading and initialization
148 // } catch (LinkageError e) {
149 // if (e.getMessage().contains("another classloader"))
150 // context.setAttribute(APP,new JNADoublyLoaded(e));
151 // else
152 // context.setAttribute(APP,new HudsonFailedToLoad(e));
153 // }
154
155 // make sure this is servlet 2.4 container or above
156 try {
157 ServletResponse.class.getMethod("setCharacterEncoding",String.class);
158 } catch (NoSuchMethodException e) {
159 context.setAttribute(APP,new IncompatibleServletVersionDetected(ServletResponse.class));
160 return;
161 }
162
163 // make sure that we see Ant 1.7
164 try {
165 FileSet.class.getMethod("getDirectoryScanner");
166 } catch (NoSuchMethodException e) {
167 context.setAttribute(APP,new IncompatibleAntVersionDetected(FileSet.class));
168 return;
169 }
170
171 // make sure AWT is functioning, or else JFreeChart won't even load.
172 if(ChartUtil.awtProblemCause!=null) {
173 context.setAttribute(APP,new AWTProblem(ChartUtil.awtProblemCause));
174 return;
175 }
176
177 // some containers (in particular Tomcat) doesn't abort a launch
178 // even if the temp directory doesn't exist.
179 // check that and report an error
180 try {
181 File f = File.createTempFile("test", "test");
182 f.delete();
183 } catch (IOException e) {
184 context.setAttribute(APP,new NoTempDir(e));
185 return;
186 }
187
188 // Tomcat breaks XSLT with JDK 5.0 and onward. Check if that's the case, and if so,
189 // try to correct it
190 try {
191 TransformerFactory.newInstance();
192 // if this works we are all happy
193 } catch (TransformerFactoryConfigurationError x) {
194 // no it didn't.
195 LOGGER.log(Level.WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details",x);
196 System.setProperty(TransformerFactory.class.getName(),"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
197 try {
198 TransformerFactory.newInstance();
199 LOGGER.info("XSLT is set to the JAXP RI in JRE");
200 } catch(TransformerFactoryConfigurationError y) {
201 LOGGER.log(Level.SEVERE, "Failed to correct the problem.");
202 }
203 }
204
205 installExpressionFactory(event);
206
207 context.setAttribute(APP,new HudsonIsLoading());
208
209 initThread = new Thread("hudson initialization thread") {
210 @Override
211 public void run() {
212 boolean success = false;
213 try {
214 Jenkins instance = new Hudson(home, context);
215 context.setAttribute(APP, instance);
216
217 // at this point we are open for business and serving requests normally
218 LOGGER.info("Jenkins is fully up and running");
219 success = true;
220 } catch (Error e) {
221 LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",e);
222 context.setAttribute(APP,new HudsonFailedToLoad(e));
223 throw e;
224 } catch (Exception e) {
225 LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",e);
226 context.setAttribute(APP,new HudsonFailedToLoad(e));
227 } finally {
228 Jenkins instance = Jenkins.getInstance();
229 if(!success && instance!=null)
230 instance.cleanUp();
231 }
232 }
233 };
234 initThread.start();
235 } catch (Error e) {
236 LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",e);
237 throw e;
238 } catch (RuntimeException e) {
239 LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",e);
240 throw e;
241 }
242 }
243
244 public static void installExpressionFactory(ServletContextEvent event) {
245 JellyFacet.setExpressionFactory(event, new ExpressionFactory2());
246 }
247
248 /**
249 * Installs log handler to monitor all Hudson logs.
250 */
251 @edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
252 private void installLogger() {
253 Jenkins.logRecords = handler.getView();
254 Logger.getLogger("hudson").addHandler(handler);
255 Logger.getLogger("jenkins").addHandler(handler);
256 }
257
258 /** Add some metadata to a File, allowing to trace setup issues */
259 public static class FileAndDescription {
260 public final File file;
261 public final String description;
262 public FileAndDescription(File file,String description) {
263 this.file = file;
264 this.description = description;
265 }
266 }
267
268 /**
269 * Determines the home directory for Jenkins.
270 *
271 * <p>
272 * We look for a setting that affects the smallest scope first, then bigger ones later.
273 *
274 * <p>
275 * People makes configuration mistakes, so we are trying to be nice
276 * with those by doing {@link String#trim()}.
277 *
278 * <p>
279 * @return the File alongside with some description to help the user troubleshoot issues
280 */
281 public FileAndDescription getHomeDir(ServletContextEvent event) {
282 // check JNDI for the home directory first
283 for (String name : HOME_NAMES) {
284 try {
285 InitialContext iniCtxt = new InitialContext();
286 Context env = (Context) iniCtxt.lookup("java:comp/env");
287 String value = (String) env.lookup(name);
288 if(value!=null && value.trim().length()>0)
289 return new FileAndDescription(new File(value.trim()),"JNDI/java:comp/env/"+name);
290 // look at one more place. See issue #1314
291 value = (String) iniCtxt.lookup(name);
292 if(value!=null && value.trim().length()>0)
293 return new FileAndDescription(new File(value.trim()),"JNDI/"+name);
294 } catch (NamingException e) {
295 // ignore
296 }
297 }
298
299 // next the system property
300 for (String name : HOME_NAMES) {
301 String sysProp = System.getProperty(name);
302 if(sysProp!=null)
303 return new FileAndDescription(new File(sysProp.trim()),"System.getProperty(\""+name+"\")");
304 }
305
306 // look at the env var next
307 for (String name : HOME_NAMES) {
308 String env = EnvVars.masterEnvVars.get(name);
309 if(env!=null)
310 return new FileAndDescription(new File(env.trim()).getAbsoluteFile(),"EnvVars.masterEnvVars.get(\""+name+"\")");
311 }
312
313 // otherwise pick a place by ourselves
314
315 String root = event.getServletContext().getRealPath("/WEB-INF/workspace");
316 if(root!=null) {
317 File ws = new File(root.trim());
318 if(ws.exists())
319 // Hudson <1.42 used to prefer this before ~/.hudson, so
320 // check the existence and if it's there, use it.
321 // otherwise if this is a new installation, prefer ~/.hudson
322 return new FileAndDescription(ws,"getServletContext().getRealPath(\"/WEB-INF/workspace\")");
323 }
324
325 File legacyHome = new File(new File(System.getProperty("user.home")),".hudson");
326 if (legacyHome.exists()) {
327 return new FileAndDescription(legacyHome,"$user.home/.hudson"); // before rename, this is where it was stored
328 }
329
330 File newHome = new File(new File(System.getProperty("user.home")),".jenkins");
331 return new FileAndDescription(newHome,"$user.home/.jenkins");
332 }
333
334 public void contextDestroyed(ServletContextEvent event) {
335 terminated = true;
336 Jenkins instance = Jenkins.getInstance();
337 if(instance!=null)
338 instance.cleanUp();
339 Thread t = initThread;
340 if (t!=null)
341 t.interrupt();
342
343 // Logger is in the system classloader, so if we don't do this
344 // the whole web app will never be undepoyed.
345 Logger.getLogger("hudson").removeHandler(handler);
346 Logger.getLogger("jenkins").removeHandler(handler);
347 }
348
349 private static final Logger LOGGER = Logger.getLogger(WebAppMain.class.getName());
350
351
352 private static final String[] HOME_NAMES = {"JENKINS_HOME","HUDSON_HOME"};
353 }
354