| author | Henrik Lynggaard Hansen | 2012-07-10 15:50:18 (EDT) |
|---|---|---|
| committer | Henrik Lynggaard Hansen | 2012-07-10 15:50:18 (EDT) |
| commit | 1947adf9a73253df6eb40f519ab693e12cb0b806 (patch) (side-by-side diff) | |
| tree | 774f97734499c691dfa50b48bcd195c93b807742 | |
| parent | 6b2a021db07f935226235132973fb64223c07d91 (diff) | |
| download | org.eclipse.hudson.core-1947adf9a73253df6eb40f519ab693e12cb0b806.zip org.eclipse.hudson.core-1947adf9a73253df6eb40f519ab693e12cb0b806.tar.gz org.eclipse.hudson.core-1947adf9a73253df6eb40f519ab693e12cb0b806.tar.bz2 | |
Reformat of logging and lifecyclerefs/changes/02/6702/1
Change-Id: I82123dcd437d875772b4096037b4ddd5dab0ded1
Signed-off-by: Henrik Lynggaard Hansen <henrik@hlyh.dk>
10 files changed, 244 insertions, 201 deletions
diff --git a/hudson-core/src/main/java/hudson/lifecycle/Lifecycle.java b/hudson-core/src/main/java/hudson/lifecycle/Lifecycle.java index acef635..9b04656 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/Lifecycle.java +++ b/hudson-core/src/main/java/hudson/lifecycle/Lifecycle.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* + * Contributors: + * * Kohsuke Kawaguchi - * + * * *******************************************************************************/ @@ -32,18 +32,16 @@ import org.slf4j.LoggerFactory; /** * Provides the capability for starting/stopping/restarting/uninstalling Hudson. * - * <p> - * The steps to perform these operations depend on how Hudson is launched, - * so the concrete instance of this method (which is VM-wide singleton) is discovered - * by looking up a FQCN from the system property "hudson.lifecycle". + * <p> The steps to perform these operations depend on how Hudson is launched, + * so the concrete instance of this method (which is VM-wide singleton) is + * discovered by looking up a FQCN from the system property "hudson.lifecycle". * * @author Kohsuke Kawaguchi * @since 1.254 */ public abstract class Lifecycle implements ExtensionPoint { - + private transient Logger logger = LoggerFactory.getLogger(Lifecycle.class); - private static Lifecycle INSTANCE = null; /** @@ -52,13 +50,13 @@ public abstract class Lifecycle implements ExtensionPoint { * @return never null */ public synchronized static Lifecycle get() { - if(INSTANCE==null) { + if (INSTANCE == null) { Lifecycle instance; String p = System.getProperty("hudson.lifecycle"); - if(p!=null) { + if (p != null) { try { ClassLoader cl = Hudson.getInstance().getPluginManager().uberClassLoader; - instance = (Lifecycle)cl.loadClass(p).newInstance(); + instance = (Lifecycle) cl.loadClass(p).newInstance(); } catch (InstantiationException e) { InstantiationError x = new InstantiationError(e.getMessage()); x.initCause(e); @@ -73,7 +71,7 @@ public abstract class Lifecycle implements ExtensionPoint { throw x; } } else { - if(Functions.isWindows()) { + if (Functions.isWindows()) { instance = new Lifecycle() { @Override public void verifyRestartable() throws RestartNotSupportedException { @@ -81,7 +79,7 @@ public abstract class Lifecycle implements ExtensionPoint { "Default Windows lifecycle does not support restart."); } }; - } else if (System.getenv("SMF_FMRI")!=null && System.getenv("SMF_RESTARTER")!=null) { + } else if (System.getenv("SMF_FMRI") != null && System.getenv("SMF_RESTARTER") != null) { // when we are run by Solaris SMF, these environment variables are set. instance = new SolarisSMFLifecycle(); } else { @@ -99,42 +97,45 @@ public abstract class Lifecycle implements ExtensionPoint { * If the location of <tt>hudson.war</tt> is known in this life cycle, * return it location. Otherwise return null to indicate that it is unknown. * - * <p> - * When a non-null value is returned, Hudson will offer an upgrade UI - * to a newer version. + * <p> When a non-null value is returned, Hudson will offer an upgrade UI to + * a newer version. */ public File getHudsonWar() { String war = System.getProperty("executable-war"); - if(war!=null && new File(war).exists()) + if (war != null && new File(war).exists()) { return new File(war); + } return null; } /** * Replaces hudson.war by the given file. * - * <p> - * On some system, most notably Windows, a file being in use cannot be changed, - * so rewriting <tt>hudson.war</tt> requires some special trick. Override this method - * to do so. + * <p> On some system, most notably Windows, a file being in use cannot be + * changed, so rewriting <tt>hudson.war</tt> requires some special trick. + * Override this method to do so. */ public void rewriteHudsonWar(File by) throws IOException { File dest = getHudsonWar(); // this should be impossible given the canRewriteHudsonWar method, // but let's be defensive - if(dest==null) throw new IOException("hudson.war location is not known."); + if (dest == null) { + throw new IOException("hudson.war location is not known."); + } // backing up the old hudson.war before it gets lost due to upgrading // (newly downloaded hudson.war and 'backup' (hudson.war.tmp) are the same files // unless we are trying to rewrite hudson.war by a backup itself File bak = new File(dest.getPath() + ".bak"); - if (!by.equals(bak)) + if (!by.equals(bak)) { FileUtils.copyFile(dest, bak); - + } + FileUtils.copyFile(by, dest); // we don't want to keep backup if we are downgrading - if (by.equals(bak)&&bak.exists()) + if (by.equals(bak) && bak.exists()) { bak.delete(); + } } /** @@ -143,21 +144,19 @@ public abstract class Lifecycle implements ExtensionPoint { public boolean canRewriteHudsonWar() { // if we don't know where hudson.war is, it's impossible to replace. File f = getHudsonWar(); - return f!=null && f.canWrite(); + return f != null && f.canWrite(); } /** - * If this life cycle supports a restart of Hudson, do so. - * Otherwise, throw {@link UnsupportedOperationException}, - * which is what the default implementation does. + * If this life cycle supports a restart of Hudson, do so. Otherwise, throw + * {@link UnsupportedOperationException}, which is what the default + * implementation does. * - * <p> - * The restart operation may happen synchronously (in which case - * this method will never return), or asynchronously (in which - * case this method will successfully return.) + * <p> The restart operation may happen synchronously (in which case this + * method will never return), or asynchronously (in which case this method + * will successfully return.) * - * <p> - * Throw an exception if the operation fails unexpectedly. + * <p> Throw an exception if the operation fails unexpectedly. */ public void restart() throws IOException, InterruptedException { throw new UnsupportedOperationException(); @@ -166,19 +165,20 @@ public abstract class Lifecycle implements ExtensionPoint { /** * Can the {@link #restart()} method restart Hudson? * - * @throws RestartNotSupportedException - * If the restart is not supported, throw this exception and explain the cause. + * @throws RestartNotSupportedException If the restart is not supported, + * throw this exception and explain the cause. */ public void verifyRestartable() throws RestartNotSupportedException { // the rewriteHudsonWar method isn't overridden. - if (!Util.isOverridden(Lifecycle.class,getClass(), "restart")) - throw new RestartNotSupportedException("Restart is not supported in this running mode (" + - getClass().getName() + ")."); + if (!Util.isOverridden(Lifecycle.class, getClass(), "restart")) { + throw new RestartNotSupportedException("Restart is not supported in this running mode (" + + getClass().getName() + ")."); + } } /** - * The same as {@link #verifyRestartable()} except the status is indicated by the return value, - * not by an exception. + * The same as {@link #verifyRestartable()} except the status is indicated + * by the return value, not by an exception. */ public boolean canRestart() { try { @@ -191,5 +191,4 @@ public abstract class Lifecycle implements ExtensionPoint { return false; } } - } diff --git a/hudson-core/src/main/java/hudson/lifecycle/RestartNotSupportedException.java b/hudson-core/src/main/java/hudson/lifecycle/RestartNotSupportedException.java index ec5caee..91527e8 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/RestartNotSupportedException.java +++ b/hudson-core/src/main/java/hudson/lifecycle/RestartNotSupportedException.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -16,10 +16,11 @@ package hudson.lifecycle; /** * Indicates that the {@link Lifecycle} doesn't support restart. - * + * * @author Kohsuke Kawaguchi */ public class RestartNotSupportedException extends Exception { + public RestartNotSupportedException(String reason) { super(reason); } diff --git a/hudson-core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java b/hudson-core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java index 5543fdb..217cefe 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java +++ b/hudson-core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Kohsuke Kawaguchi - * + * * *******************************************************************************/ @@ -25,14 +25,17 @@ import java.io.IOException; * @author Kohsuke Kawaguchi */ public class SolarisSMFLifecycle extends Lifecycle { + /** - * In SMF managed environment, just commit a suicide and the service will be restarted by SMF. + * In SMF managed environment, just commit a suicide and the service will be + * restarted by SMF. */ @Override public void restart() throws IOException, InterruptedException { Hudson h = Hudson.getInstance(); - if (h != null) + if (h != null) { h.cleanUp(); + } System.exit(0); } } diff --git a/hudson-core/src/main/java/hudson/lifecycle/UnixLifecycle.java b/hudson-core/src/main/java/hudson/lifecycle/UnixLifecycle.java index 2f4bda6..d95174a 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/UnixLifecycle.java +++ b/hudson-core/src/main/java/hudson/lifecycle/UnixLifecycle.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -22,11 +22,10 @@ import org.eclipse.hudson.jna.NativeUtils; import java.io.IOException; /** - * {@link Lifecycle} implementation when Hudson runs on the embedded - * servlet container on Unix. + * {@link Lifecycle} implementation when Hudson runs on the embedded servlet + * container on Unix. * - * <p> - * Restart by exec to self. + * <p> Restart by exec to self. * * @author Kohsuke Kawaguchi, Winston Prakash * @since 1.304 diff --git a/hudson-core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java b/hudson-core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java index 5bafbc8..1d07322 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java +++ b/hudson-core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Kohsuke Kawaguchi, Seiji Sogabe, CloudBees, Inc. - * + * * *******************************************************************************/ package hudson.lifecycle; @@ -50,12 +50,13 @@ import java.net.URL; public class WindowsInstallerLink extends ManagementLink { /** - * Location of the hudson.war. - * In general case, we can't determine this value, yet having this is a requirement for the installer. + * Location of the hudson.war. In general case, we can't determine this + * value, yet having this is a requirement for the installer. */ private final File hudsonWar; /** - * If the installation is completed, this value holds the installation directory. + * If the installation is completed, this value holds the installation + * directory. */ private volatile File installationDir; @@ -148,7 +149,8 @@ public class WindowsInstallerLink extends ManagementLink { } /** - * Copies a single resource into the target folder, by the given name, and handle errors gracefully. + * Copies a single resource into the target folder, by the given name, and + * handle errors gracefully. */ private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name) throws ServletException, IOException { try { @@ -175,7 +177,6 @@ public class WindowsInstallerLink extends ManagementLink { // initiate an orderly shutdown after we finished serving this request new Thread("terminator") { - @Override public void run() { try { @@ -183,7 +184,6 @@ public class WindowsInstallerLink extends ManagementLink { // let the service start after we close our sockets, to avoid conflicts Runtime.getRuntime().addShutdownHook(new Thread("service starter") { - @Override public void run() { try { @@ -243,13 +243,14 @@ public class WindowsInstallerLink extends ManagementLink { } /** - * Decide if {@link WindowsInstallerLink} should show up in UI, and if so, register it. + * Decide if {@link WindowsInstallerLink} should show up in UI, and if so, + * register it. */ @Extension public static ManagementLink registerIfApplicable() { - if(!Functions.isWindows()) + if (!Functions.isWindows()) { return null; // this is a Windows only feature - + } if (Lifecycle.get() instanceof WindowsServiceLifecycle) { return null; // already installed as Windows service } diff --git a/hudson-core/src/main/java/hudson/lifecycle/WindowsServiceLifecycle.java b/hudson-core/src/main/java/hudson/lifecycle/WindowsServiceLifecycle.java index 1dad61f..a982b67 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/WindowsServiceLifecycle.java +++ b/hudson-core/src/main/java/hudson/lifecycle/WindowsServiceLifecycle.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Kohsuke Kawaguchi, Winston Prakash - * + * * *******************************************************************************/ @@ -24,7 +24,7 @@ import hudson.util.IOUtils; import hudson.util.StreamTaskListener; import org.eclipse.hudson.jna.NativeAccessException; import org.eclipse.hudson.jna.NativeUtils; - + import org.apache.commons.io.FileUtils; import org.apache.commons.io.output.ByteArrayOutputStream; @@ -37,19 +37,20 @@ import java.util.logging.Logger; /** * {@link Lifecycle} for Hudson installed as Windows service. - * + * * @author Kohsuke Kawaguchi * @see WindowsInstallerLink */ public class WindowsServiceLifecycle extends Lifecycle { + public WindowsServiceLifecycle() { updateHudsonExeIfNeeded(); } /** - * If <tt>hudson.exe</tt> is old compared to our copy, - * schedule an overwrite (except that since it's currently running, - * we can only do it when Hudson restarts next time.) + * If <tt>hudson.exe</tt> is old compared to our copy, schedule an overwrite + * (except that since it's currently running, we can only do it when Hudson + * restarts next time.) */ private void updateHudsonExeIfNeeded() { try { @@ -57,52 +58,57 @@ public class WindowsServiceLifecycle extends Lifecycle { URL exe = getClass().getResource("/windows-service/hudson.exe"); String ourCopy = Util.getDigestOf(exe.openStream()); - File currentCopy = new File(rootDir,"hudson.exe"); - if(!currentCopy.exists()) return; + File currentCopy = new File(rootDir, "hudson.exe"); + if (!currentCopy.exists()) { + return; + } String curCopy = new FilePath(currentCopy).digest(); - if(ourCopy.equals(curCopy)) - return; // identical - - File stage = new File(rootDir,"hudson.exe.new"); + if (ourCopy.equals(curCopy)) { + return; // identical + } + File stage = new File(rootDir, "hudson.exe.new"); FileUtils.copyURLToFile(exe, stage); - + NativeUtils.getInstance().windowsMoveFile(stage, currentCopy); - + LOGGER.info("Scheduled a replacement of hudson.exe"); } catch (NativeAccessException exc) { LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe", exc); } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe",e); + LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe", e); } catch (InterruptedException e) { - LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe",e); + LOGGER.log(Level.SEVERE, "Failed to replace hudson.exe", e); } } /** - * On Windows, hudson.war is locked, so we place a new version under a special name, - * which is picked up by the service wrapper upon restart. + * On Windows, hudson.war is locked, so we place a new version under a + * special name, which is picked up by the service wrapper upon restart. */ @Override public void rewriteHudsonWar(File by) throws IOException { File dest = getHudsonWar(); // this should be impossible given the canRewriteHudsonWar method, // but let's be defensive - if(dest==null) throw new IOException("hudson.war location is not known."); + if (dest == null) { + throw new IOException("hudson.war location is not known."); + } // backing up the old hudson.war before its lost due to upgrading // unless we are trying to rewrite hudson.war by a backup itself File bak = new File(dest.getPath() + ".bak"); - if (!by.equals(bak)) + if (!by.equals(bak)) { FileUtils.copyFile(dest, bak); + } File rootDir = Hudson.getInstance().getRootDir(); - File copyFiles = new File(rootDir,"hudson.copies"); + File copyFiles = new File(rootDir, "hudson.copies"); FileWriter w = null; try { w = new FileWriter(copyFiles, true); - w.write(by.getAbsolutePath()+'>'+getHudsonWar().getAbsolutePath()+'\n'); + w.write(by.getAbsolutePath() + '>' + getHudsonWar().getAbsolutePath() + '\n'); } finally { IOUtils.closeQuietly(w); } @@ -118,9 +124,9 @@ public class WindowsServiceLifecycle extends Lifecycle { task.getLogger().println("Restarting a service"); int r = new LocalLauncher(task).launch().cmds(new File(home, "hudson.exe"), "restart") .stdout(task).pwd(home).join(); - if(r!=0) + if (r != 0) { throw new IOException(baos.toString()); + } } - private static final Logger LOGGER = Logger.getLogger(WindowsServiceLifecycle.class.getName()); } diff --git a/hudson-core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java b/hudson-core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java index b843b31..367101e 100644 --- a/hudson-core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java +++ b/hudson-core/src/main/java/hudson/lifecycle/WindowsSlaveInstaller.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Inc., Kohsuke Kawaguchi, Winston Prakash - * + * * *******************************************************************************/ @@ -49,13 +49,13 @@ import static javax.swing.JOptionPane.*; /** * @author Kohsuke Kawaguchi */ -public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, ActionListener { +public class WindowsSlaveInstaller implements Callable<Void, RuntimeException>, ActionListener { + /** - * Root directory of this slave. - * String, not File because the platform can be different. + * Root directory of this slave. String, not File because the platform can + * be different. */ private final String rootDir; - private transient Engine engine; private transient MainDialog dialog; @@ -64,13 +64,16 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A } public Void call() { - if(File.separatorChar=='/') return null; // not Windows - if(System.getProperty("hudson.showWindowsServiceInstallLink")==null) + if (File.separatorChar == '/') { + return null; // not Windows + } + if (System.getProperty("hudson.showWindowsServiceInstallLink") == null) { return null; // only show this when it makes sense, which is when we run from JNLP - + } dialog = MainDialog.get(); - if(dialog==null) return null; // can't find the main window. Maybe not running with GUI - + if (dialog == null) { + return null; // can't find the main window. Maybe not running with GUI + } // capture the engine engine = Engine.current(); @@ -91,8 +94,8 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A /** * Invokes slave.exe with a SCM management command. * - * <p> - * If it fails in a way that indicates the presence of UAC, retry in an UAC compatible manner. + * <p> If it fails in a way that indicates the presence of UAC, retry in an + * UAC compatible manner. */ static int runElevated(File slaveExe, String command, TaskListener out, File pwd) throws IOException, InterruptedException { try { @@ -119,7 +122,7 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A } finally { IOUtils.closeQuietly(fin); } - + } } @@ -131,17 +134,19 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A int r = JOptionPane.showConfirmDialog(dialog, Messages.WindowsSlaveInstaller_ConfirmInstallation(), Messages.WindowsInstallerLink_DisplayName(), OK_CANCEL_OPTION); - if(r!=JOptionPane.OK_OPTION) return; + if (r != JOptionPane.OK_OPTION) { + return; + } - if(!NativeUtils.getInstance().isDotNetInstalled(2, 0)) { - JOptionPane.showMessageDialog(dialog,Messages.WindowsSlaveInstaller_DotNetRequired(), + if (!NativeUtils.getInstance().isDotNetInstalled(2, 0)) { + JOptionPane.showMessageDialog(dialog, Messages.WindowsSlaveInstaller_DotNetRequired(), Messages.WindowsInstallerLink_DisplayName(), ERROR_MESSAGE); return; } final File dir = new File(rootDir); if (!dir.exists()) { - JOptionPane.showMessageDialog(dialog,Messages.WindowsSlaveInstaller_RootFsDoesntExist(rootDir), + JOptionPane.showMessageDialog(dialog, Messages.WindowsSlaveInstaller_RootFsDoesntExist(rootDir), Messages.WindowsInstallerLink_DisplayName(), ERROR_MESSAGE); return; } @@ -150,40 +155,44 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe); // write out the descriptor - URL jnlp = new URL(engine.getHudsonUrl(),"computer/"+Util.rawEncode(engine.slaveName)+"/slave-agent.jnlp"); + URL jnlp = new URL(engine.getHudsonUrl(), "computer/" + Util.rawEncode(engine.slaveName) + "/slave-agent.jnlp"); String xml = generateSlaveXml( generateServiceId(rootDir), - System.getProperty("java.home")+"\\bin\\java.exe", "-jnlpUrl "+jnlp.toExternalForm()); - FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"),xml,"UTF-8"); + System.getProperty("java.home") + "\\bin\\java.exe", "-jnlpUrl " + jnlp.toExternalForm()); + FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"), xml, "UTF-8"); // copy slave.jar - URL slaveJar = new URL(engine.getHudsonUrl(),"jnlpJars/remoting.jar"); - File dstSlaveJar = new File(dir,"slave.jar").getCanonicalFile(); - if(!dstSlaveJar.exists()) // perhaps slave.jar is already there? - FileUtils.copyURLToFile(slaveJar,dstSlaveJar); + URL slaveJar = new URL(engine.getHudsonUrl(), "jnlpJars/remoting.jar"); + File dstSlaveJar = new File(dir, "slave.jar").getCanonicalFile(); + if (!dstSlaveJar.exists()) // perhaps slave.jar is already there? + { + FileUtils.copyURLToFile(slaveJar, dstSlaveJar); + } // install as a service ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamTaskListener task = new StreamTaskListener(baos); - r = runElevated(slaveExe,"install",task,dir); - if(r!=0) { + r = runElevated(slaveExe, "install", task, dir); + if (r != 0) { JOptionPane.showMessageDialog( - dialog,baos.toString(),"Error", ERROR_MESSAGE); + dialog, baos.toString(), "Error", ERROR_MESSAGE); return; } r = JOptionPane.showConfirmDialog(dialog, Messages.WindowsSlaveInstaller_InstallationSuccessful(), Messages.WindowsInstallerLink_DisplayName(), OK_CANCEL_OPTION); - if(r!=JOptionPane.OK_OPTION) return; + if (r != JOptionPane.OK_OPTION) { + return; + } // let the service start after we close our connection, to avoid conflicts Runtime.getRuntime().addShutdownHook(new Thread("service starter") { public void run() { try { StreamTaskListener task = StreamTaskListener.fromStdout(); - int r = runElevated(slaveExe,"start",task,dir); - task.getLogger().println(r==0?"Successfully started":"start service failed. Exit code="+r); + int r = runElevated(slaveExe, "start", task, dir); + task.getLogger().println(r == 0 ? "Successfully started" : "start service failed. Exit code=" + r); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { @@ -195,12 +204,12 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A } catch (Exception t) {// this runs as a JNLP app, so if we let an exeption go, we'll never find out why it failed StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); - JOptionPane.showMessageDialog(dialog,sw.toString(),"Error", ERROR_MESSAGE); + JOptionPane.showMessageDialog(dialog, sw.toString(), "Error", ERROR_MESSAGE); } } public static String generateServiceId(String slaveRoot) throws IOException { - return "hudsonslave-"+slaveRoot.replace(':','_').replace('\\','_').replace('/','_'); + return "hudsonslave-" + slaveRoot.replace(':', '_').replace('\\', '_').replace('/', '_'); } public static String generateSlaveXml(String id, String java, String args) throws IOException { @@ -210,6 +219,5 @@ public class WindowsSlaveInstaller implements Callable<Void,RuntimeException>, A xml = xml.replace("@ARGS@", args); return xml; } - private static final long serialVersionUID = 1L; } diff --git a/hudson-core/src/main/java/hudson/logging/LogRecorder.java b/hudson-core/src/main/java/hudson/logging/LogRecorder.java index c0a6fdc..e0cd410 100644 --- a/hudson-core/src/main/java/hudson/logging/LogRecorder.java +++ b/hudson-core/src/main/java/hudson/logging/LogRecorder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* + * Contributors: + * * Kohsuke Kawaguchi - * + * * *******************************************************************************/ @@ -43,29 +43,28 @@ import java.util.logging.LogRecord; import java.util.logging.Logger; /** - * Records a selected set of logs so that the system administrator - * can diagnose a specific aspect of the system. + * Records a selected set of logs so that the system administrator can diagnose + * a specific aspect of the system. * * TODO: still a work in progress. * - * <h3>Access Control</h3> - * {@link LogRecorder} is only visible for administrators, and this access control happens at - * {@link Hudson#getLog()}, the sole entry point for binding {@link LogRecorder} to URL. + * <h3>Access Control</h3> {@link LogRecorder} is only visible for + * administrators, and this access control happens at {@link Hudson#getLog()}, + * the sole entry point for binding {@link LogRecorder} to URL. * * @author Kohsuke Kawaguchi * @see LogRecorderManager */ public class LogRecorder extends AbstractModelObject implements Saveable { - private volatile String name; + private volatile String name; //TODO: review and check whether we can do it private public final CopyOnWriteList<Target> targets = new CopyOnWriteList<Target>(); - private transient /*almost final*/ RingBufferLogHandler handler = new RingBufferLogHandler() { @Override public void publish(LogRecord record) { for (Target t : targets) { - if(t.includes(record)) { + if (t.includes(record)) { super.publish(record); return; } @@ -78,15 +77,16 @@ public class LogRecorder extends AbstractModelObject implements Saveable { } /** - * Logger that this recorder monitors, and its log level. - * Just a pair of (logger name,level) with convenience methods. + * Logger that this recorder monitors, and its log level. Just a pair of + * (logger name,level) with convenience methods. */ public static final class Target { + public final String name; private final int level; public Target(String name, Level level) { - this(name,level.intValue()); + this(name, level.intValue()); } public Target(String name, int level) { @@ -96,7 +96,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { @DataBoundConstructor public Target(String name, String level) { - this(name,Level.parse(level.toUpperCase(Locale.ENGLISH))); + this(name, Level.parse(level.toUpperCase(Locale.ENGLISH))); } public Level getLevel() { @@ -104,14 +104,15 @@ public class LogRecorder extends AbstractModelObject implements Saveable { } public boolean includes(LogRecord r) { - if(r.getLevel().intValue() < level) + if (r.getLevel().intValue() < level) { return false; // below the threshold + } String logName = r.getLoggerName(); - if(logName==null || !logName.startsWith(name)) + if (logName == null || !logName.startsWith(name)) { return false; // not within this logger - + } String rest = r.getLoggerName().substring(name.length()); - return rest.startsWith(".") || rest.length()==0; + return rest.startsWith(".") || rest.length() == 0; } public Logger getLogger() { @@ -119,12 +120,14 @@ public class LogRecorder extends AbstractModelObject implements Saveable { } /** - * Makes sure that the logger passes through messages at the correct level to us. + * Makes sure that the logger passes through messages at the correct + * level to us. */ public void enable() { Logger l = getLogger(); - if(!l.isLoggable(getLevel())) + if (!l.isLoggable(getLevel())) { l.setLevel(getLevel()); + } } } @@ -132,7 +135,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { this.name = name; // register it only once when constructed, and when this object dies // WeakLogHandler will remove it - new WeakLogHandler(handler,Logger.getLogger("")); + new WeakLogHandler(handler, Logger.getLogger("")); } public String getDisplayName() { @@ -154,28 +157,31 @@ public class LogRecorder extends AbstractModelObject implements Saveable { /** * Accepts submission from the configuration page. */ - public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { JSONObject src = req.getSubmittedForm(); String newName = src.getString("name"), redirect = "."; XmlFile oldFile = null; - if(!name.equals(newName)) { + if (!name.equals(newName)) { Hudson.checkGoodName(newName); oldFile = getConfigFile(); // rename getParent().logRecorders.remove(name); this.name = newName; - getParent().logRecorders.put(name,this); + getParent().logRecorders.put(name, this); redirect = "../" + Util.rawEncode(newName) + '/'; } List<Target> newTargets = req.bindJSONToList(Target.class, src.get("targets")); - for (Target t : newTargets) + for (Target t : newTargets) { t.enable(); + } targets.replaceBy(newTargets); save(); - if (oldFile!=null) oldFile.delete(); + if (oldFile != null) { + oldFile.delete(); + } rsp.sendRedirect2(redirect); } @@ -184,15 +190,18 @@ public class LogRecorder extends AbstractModelObject implements Saveable { */ public synchronized void load() throws IOException { getConfigFile().unmarshal(this); - for (Target t : targets) + for (Target t : targets) { t.enable(); + } } /** * Save the settings to a file. */ public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) { + return; + } getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } @@ -206,26 +215,29 @@ public class LogRecorder extends AbstractModelObject implements Saveable { getParent().logRecorders.remove(name); // Disable logging for all our targets, // then reenable all other loggers in case any also log the same targets - for (Target t : targets) + for (Target t : targets) { t.getLogger().setLevel(null); - for (LogRecorder log : getParent().logRecorders.values()) - for (Target t : log.targets) + } + for (LogRecorder log : getParent().logRecorders.values()) { + for (Target t : log.targets) { t.enable(); + } + } rsp.sendRedirect2(".."); } /** * RSS feed for log entries. */ - public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - LogRecorderManager.doRss(req,rsp,getDisplayName(),getLogRecords()); + public void doRss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { + LogRecorderManager.doRss(req, rsp, getDisplayName(), getLogRecords()); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { - return new XmlFile(XSTREAM, new File(Hudson.getInstance().getRootDir(),"log/"+name+".xml")); + return new XmlFile(XSTREAM, new File(Hudson.getInstance().getRootDir(), "log/" + name + ".xml")); } /** @@ -234,21 +246,19 @@ public class LogRecorder extends AbstractModelObject implements Saveable { public List<LogRecord> getLogRecords() { return handler.getView(); } - /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM = new XStream2(); static { - XSTREAM.alias("log",LogRecorder.class); - XSTREAM.alias("target",Target.class); + XSTREAM.alias("log", LogRecorder.class); + XSTREAM.alias("target", Target.class); } - /** * Log levels that can be configured for {@link Target}. */ public static List<Level> LEVELS = Arrays.asList(Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, - Level.FINE, Level.FINER, Level.FINEST, Level.ALL); + Level.FINE, Level.FINER, Level.FINEST, Level.ALL); } diff --git a/hudson-core/src/main/java/hudson/logging/LogRecorderManager.java b/hudson-core/src/main/java/hudson/logging/LogRecorderManager.java index b6b5c58..11f387a 100644 --- a/hudson-core/src/main/java/hudson/logging/LogRecorderManager.java +++ b/hudson-core/src/main/java/hudson/logging/LogRecorderManager.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Kohsuke Kawaguchi - * + * * *******************************************************************************/ @@ -52,10 +52,11 @@ import java.util.logging.Logger; * @author Kohsuke Kawaguchi */ public class LogRecorderManager extends AbstractModelObject { + /** * {@link LogRecorder}s. */ - public transient final Map<String,LogRecorder> logRecorders = new CopyOnWriteMap.Tree<String,LogRecorder>(); + public transient final Map<String, LogRecorder> logRecorders = new CopyOnWriteMap.Tree<String, LogRecorder>(); public String getDisplayName() { return Messages.LogRecorderManager_DisplayName(); @@ -79,14 +80,16 @@ public class LogRecorderManager extends AbstractModelObject { public void load() throws IOException { logRecorders.clear(); File dir = new File(Hudson.getInstance().getRootDir(), "log"); - File[] files = dir.listFiles((FileFilter)new WildcardFileFilter("*.xml")); - if(files==null) return; + File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("*.xml")); + if (files == null) { + return; + } for (File child : files) { String name = child.getName(); - name = name.substring(0,name.length()-4); // cut off ".xml" + name = name.substring(0, name.length() - 4); // cut off ".xml" LogRecorder lr = new LogRecorder(name); lr.load(); - logRecorders.put(name,lr); + logRecorders.put(name, lr); } } @@ -95,11 +98,11 @@ public class LogRecorderManager extends AbstractModelObject { */ public HttpResponse doNewLogRecorder(@QueryParameter String name) { Hudson.checkGoodName(name); - - logRecorders.put(name,new LogRecorder(name)); + + logRecorders.put(name, new LogRecorder(name)); // redirect to the config screen - return new HttpRedirect(name+"/configure"); + return new HttpRedirect(name + "/configure"); } /** @@ -108,10 +111,11 @@ public class LogRecorderManager extends AbstractModelObject { public HttpResponse doConfigLogger(@QueryParameter String name, @QueryParameter String level) { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); Level lv; - if(level.equals("inherit")) + if (level.equals("inherit")) { lv = null; - else + } else { lv = Level.parse(level.toUpperCase(Locale.ENGLISH)); + } Logger.getLogger(name).setLevel(lv); return new HttpRedirect("levels"); } @@ -119,7 +123,7 @@ public class LogRecorderManager extends AbstractModelObject { /** * RSS feed for log entries. */ - public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { doRss(req, rsp, getDisplayName(), Hudson.logRecords); } @@ -129,17 +133,18 @@ public class LogRecorderManager extends AbstractModelObject { /*package*/ static void doRss(StaplerRequest req, StaplerResponse rsp, String recorderName, List<LogRecord> logs) throws IOException, ServletException { // filter log records based on the log level String level = req.getParameter("level"); - if(level!=null) { + if (level != null) { Level threshold = Level.parse(level); List<LogRecord> filtered = new ArrayList<LogRecord>(); for (LogRecord r : logs) { - if(r.getLevel().intValue() >= threshold.intValue()) + if (r.getLevel().intValue() >= threshold.intValue()) { filtered.add(r); + } } logs = filtered; } - RSS.forwardToRss("Hudson " + recorderName + " log","", logs, new FeedAdapter<LogRecord>() { + RSS.forwardToRss("Hudson " + recorderName + " log", "", logs, new FeedAdapter<LogRecord>() { public String getEntryTitle(LogRecord entry) { return entry.getMessage(); } @@ -165,10 +170,10 @@ public class LogRecorderManager extends AbstractModelObject { public String getEntryAuthor(LogRecord entry) { return Mailer.descriptor().getAdminAddress(); } - },req,rsp); + }, req, rsp); } - @Initializer(before=PLUGINS_PREPARED) + @Initializer(before = PLUGINS_PREPARED) public static void init(Hudson h) throws IOException { h.getLog().load(); } diff --git a/hudson-core/src/main/java/hudson/logging/WeakLogHandler.java b/hudson-core/src/main/java/hudson/logging/WeakLogHandler.java index 6b8a8da..6bc5936 100644 --- a/hudson-core/src/main/java/hudson/logging/WeakLogHandler.java +++ b/hudson-core/src/main/java/hudson/logging/WeakLogHandler.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* + * Contributors: + * * Kohsuke Kawaguchi - * + * * *******************************************************************************/ @@ -27,10 +27,11 @@ import java.util.logging.LogRecord; import java.util.logging.Logger; /** - * Delegating {@link Handler} that uses {@link WeakReference}, - * which de-registers itself when an object disappears via GC. + * Delegating {@link Handler} that uses {@link WeakReference}, which + * de-registers itself when an object disappears via GC. */ public final class WeakLogHandler extends Handler { + private final WeakReference<Handler> target; private final Logger logger; @@ -42,26 +43,30 @@ public final class WeakLogHandler extends Handler { public void publish(LogRecord record) { Handler t = resolve(); - if(t!=null) + if (t != null) { t.publish(record); + } } public void flush() { Handler t = resolve(); - if(t!=null) + if (t != null) { t.flush(); + } } public void close() throws SecurityException { Handler t = resolve(); - if(t!=null) + if (t != null) { t.close(); + } } private Handler resolve() { Handler r = target.get(); - if(r==null) + if (r == null) { logger.removeHandler(this); + } return r; } @@ -69,48 +74,54 @@ public final class WeakLogHandler extends Handler { public void setFormatter(Formatter newFormatter) throws SecurityException { super.setFormatter(newFormatter); Handler t = resolve(); - if(t!=null) + if (t != null) { t.setFormatter(newFormatter); + } } @Override public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { super.setEncoding(encoding); Handler t = resolve(); - if(t!=null) + if (t != null) { t.setEncoding(encoding); + } } @Override public void setFilter(Filter newFilter) throws SecurityException { super.setFilter(newFilter); Handler t = resolve(); - if(t!=null) + if (t != null) { t.setFilter(newFilter); + } } @Override public void setErrorManager(ErrorManager em) { super.setErrorManager(em); Handler t = resolve(); - if(t!=null) + if (t != null) { t.setErrorManager(em); + } } @Override public void setLevel(Level newLevel) throws SecurityException { super.setLevel(newLevel); Handler t = resolve(); - if(t!=null) + if (t != null) { t.setLevel(newLevel); + } } @Override public boolean isLoggable(LogRecord record) { Handler t = resolve(); - if(t!=null) + if (t != null) { return t.isLoggable(record); - else + } else { return super.isLoggable(record); + } } } |

