T[] toArray(T[] array) {
return storage().toArray(array);
}
diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java
index 3dabd48108..7466d9d6af 100644
--- a/core/src/main/java/hudson/FilePath.java
+++ b/core/src/main/java/hudson/FilePath.java
@@ -70,6 +70,7 @@ import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
@@ -92,11 +93,12 @@ import java.util.regex.Pattern;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.zip.GZIPOutputStream;
-import java.util.zip.GZIPInputStream;
+import com.jcraft.jzlib.GZIPInputStream;
+import com.jcraft.jzlib.GZIPOutputStream;
import com.sun.jna.Native;
import hudson.os.PosixException;
+import java.io.BufferedInputStream;
import java.util.Enumeration;
import java.util.logging.Logger;
import org.apache.tools.ant.taskdefs.Chmod;
@@ -138,18 +140,21 @@ import org.apache.tools.zip.ZipEntry;
* The following code shows the example:
*
*
- * FilePath file = ...;
- *
- * // make 'file' a fresh empty directory.
- * file.act(new FileCallable<Void>() {
- * // if 'file' is on a different node, this FileCallable will
- * // be transfered to that node and executed there.
- * public Void invoke(File f,VirtualChannel channel) {
- * // f and file represents the same thing
- * f.deleteContents();
- * f.mkdirs();
- * }
- * });
+ * void someMethod(FilePath file) {
+ * // make 'file' a fresh empty directory.
+ * file.act(new Freshen());
+ * }
+ * // if 'file' is on a different node, this FileCallable will
+ * // be transferred to that node and executed there.
+ * private static final class Freshen implements FileCallable<Void> {
+ * private static final long serialVersionUID = 1;
+ * @Override public Void invoke(File f, VirtualChannel channel) {
+ * // f and file represent the same thing
+ * f.deleteContents();
+ * f.mkdirs();
+ * return null;
+ * }
+ * }
*
*
*
@@ -496,7 +501,7 @@ public final class FilePath implements Serializable {
private static void unzip(File dir, InputStream in) throws IOException {
File tmpFile = File.createTempFile("tmpzip", null); // uses java.io.tmpdir
try {
- // XXX why does this not simply use ZipInputStream?
+ // TODO why does this not simply use ZipInputStream?
IOUtils.copy(in, tmpFile);
unzip(dir,tmpFile);
}
@@ -619,7 +624,7 @@ public final class FilePath implements Serializable {
public InputStream extract(InputStream _in) throws IOException {
HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE);
try {
- return new GZIPInputStream(in,8192);
+ return new GZIPInputStream(in, 8192, true);
} catch (IOException e) {
// various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better
in.fillSide();
@@ -850,7 +855,7 @@ public final class FilePath implements Serializable {
/**
* Code that gets executed on the machine where the {@link FilePath} is local.
* Used to act on {@link FilePath}.
- *
+ * Warning: implementations must be serializable, so prefer a static nested class to an inner class.
* @see FilePath#act(FileCallable)
*/
public interface FileCallable extends Serializable {
@@ -997,6 +1002,27 @@ public final class FilePath implements Serializable {
}
}
+ /**
+ * Takes a {@link FilePath}+{@link FileCallable} pair and returns the equivalent {@link Callable}.
+ * When executing the resulting {@link Callable}, it executes {@link FileCallable#act(FileCallable)}
+ * on this {@link FilePath}.
+ *
+ * @since 1.522
+ */
+ public Callable asCallableWith(final FileCallable task) {
+ return new Callable() {
+ @Override
+ public V call() throws IOException {
+ try {
+ return act(task);
+ } catch (InterruptedException e) {
+ throw (IOException)new InterruptedIOException().initCause(e);
+ }
+ }
+ private static final long serialVersionUID = 1L;
+ };
+ }
+
/**
* Converts this file to the URI, relative to the machine
* on which this file is available.
@@ -1212,8 +1238,11 @@ public final class FilePath implements Serializable {
}
Writer w = new FileWriter(f);
- w.write(contents);
- w.close();
+ try {
+ w.write(contents);
+ } finally {
+ w.close();
+ }
return f.getAbsolutePath();
}
@@ -1658,12 +1687,13 @@ public final class FilePath implements Serializable {
/**
* Computes the MD5 digest of the file in hex string.
+ * @see Util#getDigestOf(File)
*/
public String digest() throws IOException, InterruptedException {
return act(new FileCallable() {
private static final long serialVersionUID = 1L;
public String invoke(File f, VirtualChannel channel) throws IOException {
- return Util.getDigestOf(new FileInputStream(f));
+ return Util.getDigestOf(f);
}
});
}
@@ -2426,4 +2456,16 @@ public final class FilePath implements Serializable {
throw new AssertionError(e);
}
}
+
+ /**
+ * Gets the {@link FilePath} representation of the "~" directory
+ * (User's home directory in the Unix sense) of the given channel.
+ */
+ public static FilePath getHomeDirectory(VirtualChannel ch) throws InterruptedException, IOException {
+ return ch.call(new Callable() {
+ public FilePath call() throws IOException {
+ return new FilePath(new File(System.getProperty("user.home")));
+ }
+ });
+ }
}
diff --git a/core/src/main/java/hudson/FileSystemProvisioner.java b/core/src/main/java/hudson/FileSystemProvisioner.java
index a357ba2e82..0ab7e44a1e 100644
--- a/core/src/main/java/hudson/FileSystemProvisioner.java
+++ b/core/src/main/java/hudson/FileSystemProvisioner.java
@@ -126,7 +126,7 @@ public abstract class FileSystemProvisioner implements ExtensionPoint, Describab
*
*
* This method can prepare the underlying file system in preparation
- * for the later {@link #snapshot(AbstractBuild, FilePath, TaskListener)}.
+ * for the later {@link FileSystemProvisioner.Default#snapshot(AbstractBuild, FilePath, TaskListener)}.
*
* TODO : the method needs to be able to see the snapshot would
* be later needed. In fact, perhaps we should only call this method
diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java
index cdb19d5bae..026536dc35 100644
--- a/core/src/main/java/hudson/Functions.java
+++ b/core/src/main/java/hudson/Functions.java
@@ -28,6 +28,7 @@ package hudson;
import hudson.cli.CLICommand;
import hudson.console.ConsoleAnnotationDescriptor;
import hudson.console.ConsoleAnnotatorFactory;
+import hudson.matrix.MatrixProject;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Describable;
@@ -72,6 +73,7 @@ import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.tasks.UserAvatarResolver;
import hudson.util.Area;
+import hudson.util.FormValidation.CheckMethod;
import hudson.util.Iterators;
import hudson.util.Secret;
import hudson.views.MyViewsTabBar;
@@ -148,6 +150,8 @@ import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgume
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.DoNotUse;
/**
* Utility functions used in views.
@@ -158,6 +162,7 @@ import com.google.common.base.Predicates;
*
* @author Kohsuke Kawaguchi
*/
+@SuppressWarnings("rawtypes")
public class Functions {
private static volatile int globalIota = 0;
private int iota;
@@ -187,6 +192,13 @@ public class Functions {
public static boolean isModelWithChildren(Object o) {
return o instanceof ModelObjectWithChildren;
}
+
+ /**
+ * @since 1.524
+ */
+ public static boolean isMatrixProject(Object o) {
+ return o instanceof MatrixProject;
+ }
public static String xsDate(Calendar cal) {
return Util.XS_DATETIME_FORMATTER.format(cal.getTime());
@@ -437,6 +449,51 @@ public class Functions {
return formatter.format(r);
}
+ @Restricted(DoNotUse.class)
+ public static String[] printLogRecordHtml(LogRecord r, LogRecord prior) {
+ String[] oldParts = prior == null ? new String[4] : logRecordPreformat(prior);
+ String[] newParts = logRecordPreformat(r);
+ for (int i = 0; i < /* not 4 */3; i++) {
+ newParts[i] = "" + newParts[i] + "";
+ }
+ return newParts;
+ }
+ /**
+ * Partially formats a log record.
+ * @return date, source, level, message+thrown
+ * @see SimpleFormatter#format(LogRecord)
+ */
+ private static String[] logRecordPreformat(LogRecord r) {
+ String source;
+ if (r.getSourceClassName() == null) {
+ source = r.getLoggerName();
+ } else {
+ if (r.getSourceMethodName() == null) {
+ source = r.getSourceClassName();
+ } else {
+ source = r.getSourceClassName() + " " + r.getSourceMethodName();
+ }
+ }
+ String message = new SimpleFormatter().formatMessage(r) + "\n";
+ Throwable x = r.getThrown();
+ return new String[] {
+ String.format("%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp", new Date(r.getMillis())),
+ source,
+ r.getLevel().getLocalizedName(),
+ x == null ? message : message + printThrowable(x) + "\n"
+ };
+ }
+
+ /**
+ * Reverses a collection so that it can be easily walked in reverse order.
+ * @since 1.525
+ */
+ public static Iterable reverse(Collection collection) {
+ List list = new ArrayList(collection);
+ Collections.reverse(list);
+ return list;
+ }
+
public static Cookie getCookie(HttpServletRequest req,String name) {
Cookie[] cookies = req.getCookies();
if(cookies!=null) {
@@ -796,6 +853,22 @@ public class Functions {
return result;
}
+ /**
+ * Returns those node properties which can be configured as global node properties.
+ *
+ * @since 1.520
+ */
+ public static List getGlobalNodePropertyDescriptors() {
+ List result = new ArrayList();
+ Collection list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
+ for (NodePropertyDescriptor npd : list) {
+ if (npd.isApplicableAsGlobal()) {
+ result.add(npd);
+ }
+ }
+ return result;
+ }
+
/**
* Gets all the descriptors sorted by their inheritance tree of {@link Describable}
* so that descriptors of similar types come nearby.
@@ -1304,15 +1377,23 @@ public class Functions {
public static String toCCStatus(Item i) {
if (i instanceof Job) {
Job j = (Job) i;
- switch (j.getIconColor().noAnime()) {
+ switch (j.getIconColor()) {
case ABORTED:
+ case ABORTED_ANIME:
case RED:
+ case RED_ANIME:
case YELLOW:
+ case YELLOW_ANIME:
return "Failure";
case BLUE:
+ case BLUE_ANIME:
return "Success";
case DISABLED:
+ case DISABLED_ANIME:
case GREY:
+ case GREY_ANIME:
+ case NOTBUILT:
+ case NOTBUILT_ANIME:
return "Unknown";
}
}
@@ -1451,6 +1532,9 @@ public class Functions {
/**
* Determines the form validation check URL. See textbox.jelly
+ *
+ * @deprecated
+ * Use {@link #calcCheckUrl}
*/
public String getCheckUrl(String userDefined, Object descriptor, String field) {
if(userDefined!=null || field==null) return userDefined;
@@ -1461,6 +1545,23 @@ public class Functions {
return null;
}
+ /**
+ * Determines the parameters that client-side needs for a form validation check. See prepareDatabinding.jelly
+ *
+ * @deprecated
+ * Use {@link #calcCheckUrl}
+ */
+ public void calcCheckUrl(Map attributes, String userDefined, Object descriptor, String field) {
+ if(userDefined!=null || field==null) return;
+
+ if (descriptor instanceof Descriptor) {
+ Descriptor d = (Descriptor) descriptor;
+ CheckMethod m = d.getCheckMethod(field);
+ attributes.put("checkUrl",m.toStemUrl());
+ attributes.put("checkDependsOn",m.getDependsOn());
+ }
+ }
+
/**
* If the given href link is matching the current page, return true.
*
@@ -1692,7 +1793,7 @@ public class Functions {
/**
* Returns human readable information about file size
*
- * @param file size in bytes
+ * @param size file size in bytes
* @return file size in appropriate unit
*/
public static String humanReadableByteSize(long size){
@@ -1716,4 +1817,40 @@ public class Functions {
DecimalFormat format = new DecimalFormat("#0.00");
return format.format(number) + " " + measure;
}
+
+ /**
+ * Get a string that can be safely broken to several lines when necessary.
+ *
+ * This implementation inserts <wbr> tags into string. It allows browsers
+ * to wrap line before any sequence of punctuation characters or anywhere
+ * in the middle of prolonged sequences of word characters.
+ *
+ * @since 1.517
+ */
+ public static String breakableString(final String plain) {
+
+ return plain.replaceAll("(\\p{Punct}+\\w)", "$1")
+ .replaceAll("(\\w{10})(?=\\w{3})", "$1")
+ ;
+ }
+
+ /**
+ * Advertises the minimum set of HTTP headers that assist programmatic
+ * discovery of Jenkins.
+ */
+ public static void advertiseHeaders(HttpServletResponse rsp) {
+ Jenkins j = Jenkins.getInstance();
+
+ rsp.setHeader("X-Hudson","1.395");
+ rsp.setHeader("X-Jenkins", Jenkins.VERSION);
+ rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH);
+
+ TcpSlaveAgentListener tal = j.tcpSlaveAgentListener;
+ if (tal !=null) {
+ rsp.setIntHeader("X-Hudson-CLI-Port", tal.getPort());
+ rsp.setIntHeader("X-Jenkins-CLI-Port", tal.getPort());
+ rsp.setIntHeader("X-Jenkins-CLI2-Port", tal.getPort());
+ rsp.setHeader("X-Jenkins-CLI-Host", TcpSlaveAgentListener.CLI_HOST_NAME);
+ }
+ }
}
diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java
index 06fd1fe0fe..aeb2c15227 100644
--- a/core/src/main/java/hudson/Launcher.java
+++ b/core/src/main/java/hudson/Launcher.java
@@ -664,6 +664,11 @@ public abstract class Launcher {
public final Launcher decorateByPrefix(final String... prefix) {
final Launcher outer = this;
return new Launcher(outer) {
+ @Override
+ public boolean isUnix() {
+ return outer.isUnix();
+ }
+
@Override
public Proc launch(ProcStarter starter) throws IOException {
starter.commands.addAll(0,Arrays.asList(prefix));
@@ -711,6 +716,11 @@ public abstract class Launcher {
final EnvVars env = new EnvVars(_env);
final Launcher outer = this;
return new Launcher(outer) {
+ @Override
+ public boolean isUnix() {
+ return outer.isUnix();
+ }
+
@Override
public Proc launch(ProcStarter starter) throws IOException {
EnvVars e = new EnvVars(env);
diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java
index 3ef1a3ab06..7ce9dea6d3 100644
--- a/core/src/main/java/hudson/PluginManager.java
+++ b/core/src/main/java/hudson/PluginManager.java
@@ -59,6 +59,7 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.LogFactory;
+import org.jenkinsci.bytecode.Transformer;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.ReactorException;
@@ -151,6 +152,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
// and load plugin-contributed classes.
public final ClassLoader uberClassLoader = new UberClassLoader();
+ private final Transformer compatibilityTransformer = new Transformer();
+
/**
* Once plugin is uploaded, this flag becomes true.
* This is used to report a message that Jenkins needs to be restarted
@@ -179,6 +182,17 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
rootDir.mkdirs();
strategy = createPluginStrategy();
+
+ // load up rules for the core first
+ try {
+ compatibilityTransformer.loadRules(getClass().getClassLoader());
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failed to load compatibility rewrite rules",e);
+ }
+ }
+
+ public Transformer getCompatibilityTransformer() {
+ return compatibilityTransformer;
}
public Api getApi() {
@@ -301,6 +315,13 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
}
});
+ // Let's see for a while until we open this functionality up to plugins
+// g.followedBy().attains(PLUGINS_LISTED).add("Load compatibility rules", new Executable() {
+// public void run(Reactor reactor) throws Exception {
+// compatibilityTransformer.loadRules(uberClassLoader);
+// }
+// });
+
session.addAll(g.discoverTasks(session));
pluginListed = true; // technically speaking this is still too early, as at this point tasks are merely scheduled, not necessarily executed.
@@ -732,25 +753,23 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
}
// first copy into a temporary file name
- File t = File.createTempFile("uploaded", "jp_",rootDir);
- fileItem.write(t); // rename all new plugins to *.jpi
+ File t = File.createTempFile("uploaded", ".jpi");
+ t.deleteOnExit();
+ fileItem.write(t);
fileItem.delete();
final String baseName = identifyPluginShortName(t);
- // and move the temp file into a proper name
- new File(rootDir, baseName + ".hpi").delete(); // don't keep confusing legacy *.hpi
- new File(rootDir, baseName + ".jpi").delete(); // rename can fail if the file already exists
- t.renameTo(new File(rootDir, baseName + ".jpi"));
-
- PluginWrapper existing = getPlugin(baseName);
- if (existing!=null && existing.isBundled){
- existing.doPin();
- }
-
pluginUploaded = true;
- return new HttpRedirect(".");
+ // Now create a dummy plugin that we can dynamically load (the InstallationJob will force a restart if one is needed):
+ JSONObject cfg = new JSONObject().
+ element("name", baseName).
+ element("version", "0"). // unused but mandatory
+ element("url", t.toURI().toString()).
+ element("dependencies", new JSONArray());
+ new UpdateSite(UpdateCenter.ID_UPLOAD, null).new Plugin(UpdateCenter.ID_UPLOAD, cfg).deploy(true);
+ return new HttpRedirect("../updateCenter");
} catch (IOException e) {
throw e;
} catch (Exception e) {// grrr. fileItem.write throws this
@@ -799,7 +818,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
List> jobs = new ArrayList>();
UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
- // XXX call uc.updateAllSites() when available? perhaps not, since we should not block on network here
+ // TODO call uc.updateAllSites() when available? perhaps not, since we should not block on network here
for (Map.Entry requestedPlugin : parseRequestedPlugins(configXml).entrySet()) {
PluginWrapper pw = getPlugin(requestedPlugin.getKey());
if (pw == null) { // install new
diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java
index 3e61e16660..dc8fd6659d 100644
--- a/core/src/main/java/hudson/PluginWrapper.java
+++ b/core/src/main/java/hudson/PluginWrapper.java
@@ -487,7 +487,7 @@ public class PluginWrapper implements Comparable, ModelObject {
/**
* If the plugin has {@link #getUpdateInfo() an update},
- * returns the {@link UpdateSite.Plugin} object.
+ * returns the {@link hudson.model.UpdateSite.Plugin} object.
*
* @return
* This method may return null — for example,
@@ -501,7 +501,7 @@ public class PluginWrapper implements Comparable, ModelObject {
}
/**
- * returns the {@link UpdateSite.Plugin} object, or null.
+ * returns the {@link hudson.model.UpdateSite.Plugin} object, or null.
*/
public UpdateSite.Plugin getInfo() {
UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
@@ -567,7 +567,11 @@ public class PluginWrapper implements Comparable, ModelObject {
if (backup.exists()) {
try {
JarFile backupPlugin = new JarFile(backup);
- return backupPlugin.getManifest().getMainAttributes().getValue("Plugin-Version");
+ try {
+ return backupPlugin.getManifest().getMainAttributes().getValue("Plugin-Version");
+ } finally {
+ backupPlugin.close();
+ }
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to get backup version ", e);
return null;
diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java
index 046adbfb10..2c5f4f916c 100644
--- a/core/src/main/java/hudson/TcpSlaveAgentListener.java
+++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java
@@ -26,8 +26,10 @@ package hudson;
import hudson.slaves.OfflineCause;
import jenkins.AgentProtocol;
+import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
+import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
@@ -139,7 +141,9 @@ public final class TcpSlaveAgentListener extends Thread {
LOGGER.info("Accepted connection #"+id+" from "+s.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(s.getInputStream());
- PrintWriter out = new PrintWriter(s.getOutputStream(),true); // DEPRECATED: newer protocol shouldn't use PrintWriter but should use DataOutputStream
+ PrintWriter out = new PrintWriter(
+ new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")),
+ true); // DEPRECATED: newer protocol shouldn't use PrintWriter but should use DataOutputStream
String s = in.readUTF();
diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java
index 1365bca2be..ad91672dc6 100644
--- a/core/src/main/java/hudson/Util.java
+++ b/core/src/main/java/hudson/Util.java
@@ -34,7 +34,6 @@ import hudson.util.IOException2;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import hudson.util.jna.WinIOException;
-import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tools.ant.BuildException;
@@ -42,10 +41,9 @@ import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
-import org.jruby.ext.posix.FileStat;
-import org.jruby.ext.posix.POSIX;
+import jnr.posix.FileStat;
+import jnr.posix.POSIX;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
-import org.kohsuke.stapler.Stapler;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
@@ -61,7 +59,6 @@ import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
-import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
@@ -76,6 +73,8 @@ import java.util.regex.Pattern;
import hudson.util.jna.Kernel32Utils;
import static hudson.util.jna.GNUCLibrary.LIBC;
+import java.security.DigestInputStream;
+import org.apache.commons.codec.digest.DigestUtils;
/**
* Various utility methods that don't have more proper home.
@@ -113,9 +112,9 @@ public class Util {
}
/**
- * Pattern for capturing variables. Either $xyz or ${xyz}, while ignoring "$$"
+ * Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
*/
- private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_]+\\}|\\$)");
+ private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");
/**
* Replaces the occurrence of '$key' by properties.get('key').
@@ -284,7 +283,7 @@ public class Util {
}
try {// try libc chmod
- POSIX posix = PosixAPI.get();
+ POSIX posix = PosixAPI.jnr();
String path = f.getAbsolutePath();
FileStat stat = posix.stat(path);
posix.chmod(path, stat.mode()|0200); // u+w
@@ -554,6 +553,7 @@ public class Util {
* The stream will be closed by this method at the end of this method.
* @return
* 32-char wide string
+ * @see DigestUtils#md5Hex(InputStream)
*/
public static String getDigestOf(InputStream source) throws IOException {
try {
@@ -571,6 +571,13 @@ public class Util {
} catch (NoSuchAlgorithmException e) {
throw new IOException2("MD5 not installed",e); // impossible
}
+ /* JENKINS-18178: confuses Maven 2 runner
+ try {
+ return DigestUtils.md5Hex(source);
+ } finally {
+ source.close();
+ }
+ */
}
public static String getDigestOf(String text) {
@@ -581,6 +588,22 @@ public class Util {
}
}
+ /**
+ * Computes the MD5 digest of a file.
+ * @param file a file
+ * @return a 32-character string
+ * @throws IOException in case reading fails
+ * @since 1.525
+ */
+ public static String getDigestOf(File file) throws IOException {
+ InputStream is = new FileInputStream(file);
+ try {
+ return getDigestOf(new BufferedInputStream(is));
+ } finally {
+ is.close();
+ }
+ }
+
/**
* Converts a string into 128-bit AES key.
* @since 1.308
@@ -1089,13 +1112,16 @@ public class Util {
} catch (LinkageError e) {
// if JNA is unavailable, fall back.
// we still prefer to try JNA first as PosixAPI supports even smaller platforms.
- if (PosixAPI.supportsNative()) {
- r = PosixAPI.get().symlink(targetPath,symlinkFile.getAbsolutePath());
+ POSIX posix = PosixAPI.jnr();
+ if (posix.isNative()) {
+ // TODO should we rethrow PosixException as IOException here?
+ r = posix.symlink(targetPath,symlinkFile.getAbsolutePath());
}
}
}
if (r==null) {
// if all else fail, fall back to the most expensive approach of forking a process
+ // TODO is this really necessary? JavaPOSIX should do this automatically
r = new LocalProc(new String[]{
"ln","-s", targetPath, symlinkPath},
new String[0],listener.getLogger(), baseDir).join();
@@ -1200,6 +1226,10 @@ public class Util {
} catch (ClassNotFoundException x3) {
assert false : x3; // should be Java 7+ here
}
+ if (x2.getClass().getName().equals("java.nio.file.FileSystemException")) {
+ // Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink, rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?
+ return null;
+ }
if (x2 instanceof IOException) {
throw (IOException) x2;
}
@@ -1233,7 +1263,7 @@ public class Util {
} catch (LinkageError e) {
// if JNA is unavailable, fall back.
// we still prefer to try JNA first as PosixAPI supports even smaller platforms.
- return PosixAPI.get().readlink(filename);
+ return PosixAPI.jnr().readlink(filename);
}
}
diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java
index f73bbe02c6..f6cf979bf8 100644
--- a/core/src/main/java/hudson/WebAppMain.java
+++ b/core/src/main/java/hudson/WebAppMain.java
@@ -59,6 +59,7 @@ import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.security.Security;
+import java.util.logging.LogRecord;
/**
* Entry point when Hudson is used as a webapp.
@@ -66,7 +67,13 @@ import java.security.Security;
* @author Kohsuke Kawaguchi
*/
public final class WebAppMain implements ServletContextListener {
- private final RingBufferLogHandler handler = new RingBufferLogHandler();
+ private final RingBufferLogHandler handler = new RingBufferLogHandler() {
+ @Override public synchronized void publish(LogRecord record) {
+ if (record.getLevel().intValue() >= Level.INFO.intValue()) {
+ super.publish(record);
+ }
+ }
+ };
private static final String APP = "app";
private boolean terminated;
private Thread initThread;
@@ -206,7 +213,7 @@ public final class WebAppMain implements ServletContextListener {
context.setAttribute(APP,new HudsonIsLoading());
- initThread = new Thread("hudson initialization thread") {
+ initThread = new Thread("Jenkins initialization thread") {
@Override
public void run() {
boolean success = false;
@@ -341,8 +348,7 @@ public final class WebAppMain implements ServletContextListener {
// Logger is in the system classloader, so if we don't do this
// the whole web app will never be undepoyed.
- Logger.getLogger("hudson").removeHandler(handler);
- Logger.getLogger("jenkins").removeHandler(handler);
+ Logger.getLogger("").removeHandler(handler);
}
private static final Logger LOGGER = Logger.getLogger(WebAppMain.class.getName());
diff --git a/core/src/main/java/hudson/cli/CliProtocol.java b/core/src/main/java/hudson/cli/CliProtocol.java
index 0f1d5035cf..b3b725fe33 100644
--- a/core/src/main/java/hudson/cli/CliProtocol.java
+++ b/core/src/main/java/hudson/cli/CliProtocol.java
@@ -9,7 +9,9 @@ import jenkins.model.Jenkins;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
+import java.io.BufferedWriter;
import java.io.IOException;
+import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
@@ -39,7 +41,7 @@ public class CliProtocol extends AgentProtocol {
}
public void run() throws IOException, InterruptedException {
- PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
+ PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")),true);
out.println("Welcome");
runCli(new Connection(socket));
}
diff --git a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
index 25bc040d8b..cd727e7ba4 100644
--- a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
+++ b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
@@ -1,13 +1,10 @@
package hudson.cli;
import hudson.FilePath;
-import hudson.FilePath.FileCallable;
import jenkins.model.Jenkins;
import jenkins.model.Jenkins.MasterComputer;
-import hudson.os.PosixAPI;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
-import hudson.remoting.VirtualChannel;
import hudson.util.Secret;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
@@ -16,7 +13,6 @@ import org.acegisecurity.userdetails.UserDetails;
import org.springframework.dao.DataAccessException;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
@@ -106,21 +102,13 @@ public class ClientAuthenticationCache implements Serializable {
}
private void save() throws IOException, InterruptedException {
- store.act(new FileCallable() {
- public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
- f.getParentFile().mkdirs();
-
- OutputStream os = new FileOutputStream(f);
- try {
- props.store(os,"Credential store");
- } finally {
- os.close();
- }
-
- // try to protect this file from other users, if we can.
- PosixAPI.get().chmod(f.getAbsolutePath(),0600);
- return null;
- }
- });
+ OutputStream os = store.write();
+ try {
+ props.store(os,"Credential store");
+ } finally {
+ os.close();
+ }
+ // try to protect this file from other users, if we can.
+ store.chmod(0600);
}
}
diff --git a/core/src/main/java/hudson/cli/CommandDuringBuild.java b/core/src/main/java/hudson/cli/CommandDuringBuild.java
index 7f1320ec8a..6f9230b3ee 100644
--- a/core/src/main/java/hudson/cli/CommandDuringBuild.java
+++ b/core/src/main/java/hudson/cli/CommandDuringBuild.java
@@ -39,17 +39,27 @@ import java.io.IOException;
*/
public abstract class CommandDuringBuild extends CLICommand {
/**
- * This method makes sense only when called from within the build kicked by Hudson.
- * We use the environment variables that Hudson sets to determine the build that is being run.
+ * This method makes sense only when called from within the build kicked by Jenkins.
+ * We use the environment variables that Jenkins sets to determine the build that is being run.
*/
protected Run getCurrentlyBuilding() throws CmdLineException {
+ Run r = optCurrentlyBuilding();
+ if (r==null)
+ throw new CmdLineException("This CLI command works only when invoked from inside a build");
+ return r;
+ }
+
+ /**
+ * If the command is currently running inside a build, return it. Otherwise null.
+ */
+ protected Run optCurrentlyBuilding() throws CmdLineException {
try {
CLICommand c = CLICommand.getCurrent();
if (c==null) throw new IllegalStateException("Not executing a CLI command");
String[] envs = c.checkChannel().call(new GetCharacteristicEnvironmentVariables());
if (envs[0]==null || envs[1]==null)
- throw new CmdLineException("This CLI command works only when invoked from inside a build");
+ return null;
Job j = Jenkins.getInstance().getItemByFullName(envs[0],Job.class);
if (j==null) throw new CmdLineException("No such job: "+envs[0]);
diff --git a/core/src/main/java/hudson/cli/CreateNodeCommand.java b/core/src/main/java/hudson/cli/CreateNodeCommand.java
new file mode 100644
index 0000000000..bd94932955
--- /dev/null
+++ b/core/src/main/java/hudson/cli/CreateNodeCommand.java
@@ -0,0 +1,83 @@
+/*
+ * The MIT License
+ *
+ * Copyright 2013 Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package hudson.cli;
+
+import hudson.Extension;
+import hudson.model.Node;
+import hudson.model.Slave;
+import hudson.model.User;
+import jenkins.model.Jenkins;
+
+import org.kohsuke.args4j.Argument;
+import org.kohsuke.args4j.CmdLineException;
+
+/**
+ * @author ogondza
+ * @since XXX
+ */
+@Extension
+public class CreateNodeCommand extends CLICommand {
+
+ @Argument(metaVar="NODE", usage="Name of the node")
+ public String nodeName;
+
+ @Override
+ public String getShortDescription() {
+
+ return Messages.CreateNodeCommand_ShortDescription();
+ }
+
+ @Override
+ protected int run() throws Exception {
+
+ final Jenkins jenkins = Jenkins.getInstance();
+ jenkins.checkPermission(Jenkins.ADMINISTER);
+
+ final Node newNode = (Node) Jenkins.XSTREAM2.fromXML(stdin);
+
+ if (nodeName != null) {
+
+ // Using deprecated method but it's contract is preserved
+ newNode.setNodeName(nodeName);
+ }
+
+ if(newNode instanceof Slave) { //change userId too
+ User user = User.current();
+ ((Slave) newNode).setUserId(user==null ? "anonymous" : user.getId());
+ }
+
+ if (jenkins.getNode(newNode.getNodeName()) != null) {
+
+ throw new CmdLineException(
+ null, "Node '" + newNode.getNodeName() + "' already exists"
+ );
+ }
+
+ jenkins.addNode(newNode);
+
+ return 0;
+ }
+
+}
diff --git a/core/src/main/java/hudson/cli/GetNodeCommand.java b/core/src/main/java/hudson/cli/GetNodeCommand.java
new file mode 100644
index 0000000000..e2bf3410da
--- /dev/null
+++ b/core/src/main/java/hudson/cli/GetNodeCommand.java
@@ -0,0 +1,60 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2013, Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.cli;
+
+import hudson.Extension;
+import hudson.model.Node;
+
+import java.io.IOException;
+
+import jenkins.model.Jenkins;
+
+import org.kohsuke.args4j.Argument;
+
+/**
+ * @author ogondza
+ * @since XXX
+ */
+@Extension
+public class GetNodeCommand extends CLICommand {
+
+ @Argument(metaVar="NODE", usage="Name of the node", required=true)
+ public Node node;
+
+ @Override
+ public String getShortDescription() {
+
+ return Messages.GetNodeCommand_ShortDescription();
+ }
+
+ @Override
+ protected int run() throws IOException {
+
+ node.checkPermission(Jenkins.ADMINISTER);
+
+ Jenkins.XSTREAM2.toXMLUTF8(node, stdout);
+
+ return 0;
+ }
+}
diff --git a/core/src/main/java/hudson/cli/ListJobsCommand.java b/core/src/main/java/hudson/cli/ListJobsCommand.java
index 8e52a9f449..af858d3f04 100644
--- a/core/src/main/java/hudson/cli/ListJobsCommand.java
+++ b/core/src/main/java/hudson/cli/ListJobsCommand.java
@@ -24,10 +24,14 @@
package hudson.cli;
import java.util.Collection;
+import java.util.LinkedHashSet;
+
import java.util.Collections;
+
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.TopLevelItem;
+import hudson.model.ViewGroup;
import hudson.model.View;
import hudson.Extension;
import jenkins.model.Jenkins;
@@ -57,7 +61,7 @@ public class ListJobsCommand extends CLICommand {
View view = h.getView(name);
if (view != null) {
- jobs = view.getItems();
+ jobs = view.getAllItems();
}
// If no view was found, try with an item group.
else {
@@ -71,7 +75,7 @@ public class ListJobsCommand extends CLICommand {
// No view and no item group with the given name found.
else {
stderr.println("No view or item group with the given name found");
- jobs = Collections.emptyList();
+ return -1;
}
}
}
diff --git a/core/src/main/java/hudson/cli/UpdateNodeCommand.java b/core/src/main/java/hudson/cli/UpdateNodeCommand.java
new file mode 100644
index 0000000000..5af2b54eb8
--- /dev/null
+++ b/core/src/main/java/hudson/cli/UpdateNodeCommand.java
@@ -0,0 +1,59 @@
+/*
+ * The MIT License
+ *
+ * Copyright 2013 Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package hudson.cli;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+
+import hudson.Extension;
+import hudson.model.Node;
+
+import org.kohsuke.args4j.Argument;
+
+/**
+ * @author ogondza
+ * @since XXX
+ */
+@Extension
+public class UpdateNodeCommand extends CLICommand {
+
+ @Argument(metaVar="NODE", usage="Name of the node", required=true)
+ public Node node;
+
+ @Override
+ public String getShortDescription() {
+
+ return Messages.UpdateNodeCommand_ShortDescription();
+ }
+
+ @Override
+ protected int run() throws IOException, ServletException {
+
+ node.toComputer().updateByXml(stdin);
+
+ return 0;
+ }
+}
diff --git a/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java b/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java
new file mode 100644
index 0000000000..24e7a5aed6
--- /dev/null
+++ b/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java
@@ -0,0 +1,68 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2013, Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.cli.handlers;
+
+import hudson.model.Node;
+import jenkins.model.Jenkins;
+
+import org.kohsuke.MetaInfServices;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.OptionDef;
+import org.kohsuke.args4j.spi.OptionHandler;
+import org.kohsuke.args4j.spi.Parameters;
+import org.kohsuke.args4j.spi.Setter;
+
+/**
+ * Refers to {@link Node} by its name.
+ *
+ * @author ogondza
+ * @since XXX
+ */
+@MetaInfServices
+public class NodeOptionHandler extends OptionHandler {
+
+ public NodeOptionHandler(CmdLineParser parser, OptionDef option, Setter setter) {
+
+ super(parser, option, setter);
+ }
+
+ @Override
+ public int parseArguments(Parameters params) throws CmdLineException {
+
+ String nodeName = params.getParameter(0);
+
+ final Node node = Jenkins.getInstance().getNode(nodeName);
+ if (node == null) throw new CmdLineException(owner, "No such node '" + nodeName + "'");
+
+ setter.addValue(node);
+ return 1;
+ }
+
+ @Override
+ public String getDefaultMetaVariable() {
+
+ return "NODE";
+ }
+}
diff --git a/core/src/main/java/hudson/cli/handlers/package-info.java b/core/src/main/java/hudson/cli/handlers/package-info.java
index 982ac6b4ec..ee7dee536f 100644
--- a/core/src/main/java/hudson/cli/handlers/package-info.java
+++ b/core/src/main/java/hudson/cli/handlers/package-info.java
@@ -1,5 +1,5 @@
/**
- * {@link OptionHandler} implementations for Hudson.
+ * {@link org.kohsuke.args4j.spi.OptionHandler} implementations for Hudson.
*/
package hudson.cli.handlers;
diff --git a/core/src/main/java/hudson/console/AnnotatedLargeText.java b/core/src/main/java/hudson/console/AnnotatedLargeText.java
index 1fe28f84e8..298e034bf1 100644
--- a/core/src/main/java/hudson/console/AnnotatedLargeText.java
+++ b/core/src/main/java/hudson/console/AnnotatedLargeText.java
@@ -51,8 +51,8 @@ import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
+import com.jcraft.jzlib.GZIPInputStream;
+import com.jcraft.jzlib.GZIPOutputStream;
import static java.lang.Math.abs;
diff --git a/core/src/main/java/hudson/console/ConsoleAnnotator.java b/core/src/main/java/hudson/console/ConsoleAnnotator.java
index 22c295d291..eab2376ddd 100644
--- a/core/src/main/java/hudson/console/ConsoleAnnotator.java
+++ b/core/src/main/java/hudson/console/ConsoleAnnotator.java
@@ -35,7 +35,7 @@ import java.util.ListIterator;
* Annotates one line of console output.
*
*
- * In Hudson, console output annotation is done line by line, and
+ * In Jenkins, console output annotation is done line by line, and
* we model this as a state machine —
* the code encapsulates some state, and it uses that to annotate one line (and possibly update the state.)
*
@@ -54,7 +54,7 @@ import java.util.ListIterator;
*
*
*
- * Because of a browser can request console output incrementally, in addition to above a console annotator
+ * Because a browser can request console output incrementally, in addition to above a console annotator
* can be serialized at any point and deserialized back later to continue annotation where it left off.
*
*
diff --git a/core/src/main/java/hudson/console/ConsoleNote.java b/core/src/main/java/hudson/console/ConsoleNote.java
index 4660193f8c..c8ea004643 100644
--- a/core/src/main/java/hudson/console/ConsoleNote.java
+++ b/core/src/main/java/hudson/console/ConsoleNote.java
@@ -50,8 +50,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
+import com.jcraft.jzlib.GZIPInputStream;
+import com.jcraft.jzlib.GZIPOutputStream;
/**
* Data that hangs off from a console output.
diff --git a/core/src/main/java/hudson/fsp/WorkspaceSnapshotSCM.java b/core/src/main/java/hudson/fsp/WorkspaceSnapshotSCM.java
index e090c14d55..140220c54d 100644
--- a/core/src/main/java/hudson/fsp/WorkspaceSnapshotSCM.java
+++ b/core/src/main/java/hudson/fsp/WorkspaceSnapshotSCM.java
@@ -89,7 +89,7 @@ public class WorkspaceSnapshotSCM extends SCM {
}
/**
* Obtains the {@link WorkspaceSnapshot} object that this {@link SCM} points to,
- * or throws {@link ResolvedFailedException} upon failing.
+ * or throws {@link hudson.fsp.WorkspaceSnapshotSCM.ResolvedFailedException} upon failing.
*
* @return never null.
*/
diff --git a/core/src/main/java/hudson/init/InitReactorListener.java b/core/src/main/java/hudson/init/InitReactorListener.java
index ea3f92a25f..75ef0614c4 100644
--- a/core/src/main/java/hudson/init/InitReactorListener.java
+++ b/core/src/main/java/hudson/init/InitReactorListener.java
@@ -15,7 +15,6 @@ import org.kohsuke.MetaInfServices;
* To register, put {@link MetaInfServices} on your implementation.
*
* @author Kohsuke Kawaguchi
- * @see jenkins.model.Jenkins#buildReactorListener()
*/
public interface InitReactorListener extends ReactorListener {
}
diff --git a/core/src/main/java/hudson/init/impl/GroovyInitScript.java b/core/src/main/java/hudson/init/impl/GroovyInitScript.java
index cc365cb274..cf5da23407 100644
--- a/core/src/main/java/hudson/init/impl/GroovyInitScript.java
+++ b/core/src/main/java/hudson/init/impl/GroovyInitScript.java
@@ -31,12 +31,12 @@ import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
-import java.util.Collections;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import static hudson.init.InitMilestone.JOB_LOADED;
import hudson.init.Initializer;
+import java.util.logging.Level;
/**
* Run the initialization script, if it exists.
@@ -78,9 +78,13 @@ public class GroovyInitScript {
execute(new GroovyCodeSource(initScript));
}
- private static void execute(GroovyCodeSource initScript) throws IOException {
+ private static void execute(GroovyCodeSource initScript) {
GroovyShell shell = new GroovyShell(Jenkins.getInstance().getPluginManager().uberClassLoader);
- shell.evaluate(initScript);
+ try {
+ shell.evaluate(initScript);
+ } catch (RuntimeException x) {
+ LOGGER.log(Level.WARNING, "Failed to run script " + initScript.getName(), x);
+ }
}
private static final Logger LOGGER = Logger.getLogger(GroovyInitScript.class.getName());
diff --git a/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java
new file mode 100644
index 0000000000..60f34e3a7d
--- /dev/null
+++ b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java
@@ -0,0 +1,30 @@
+package hudson.init.impl;
+
+import hudson.init.Initializer;
+import jenkins.model.Jenkins;
+import org.kohsuke.stapler.WebApp;
+import org.kohsuke.stapler.compression.CompressionFilter;
+import org.kohsuke.stapler.compression.UncaughtExceptionHandler;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * @author Kohsuke Kawaguchi
+ */
+public class InstallUncaughtExceptionHandler {
+ @Initializer
+ public static void init(final Jenkins j) throws IOException {
+ CompressionFilter.setUncaughtExceptionHandler(j.servletContext, new UncaughtExceptionHandler() {
+ @Override
+ public void reportException(Throwable e, ServletContext context, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
+ req.setAttribute("javax.servlet.error.exception",e);
+ WebApp.get(j.servletContext).getSomeStapler()
+ .invoke(req,rsp, Jenkins.getInstance(), "/oops");
+ }
+ });
+ }
+}
diff --git a/core/src/main/java/hudson/init/package-info.java b/core/src/main/java/hudson/init/package-info.java
index b19a2a705e..065b64a85c 100644
--- a/core/src/main/java/hudson/init/package-info.java
+++ b/core/src/main/java/hudson/init/package-info.java
@@ -27,13 +27,13 @@
*
*
* Hudson's start up is based on the same idea as the modern Unix init mechanism like initng/upstart/SMF.
- * It first builds a set of {@link Task}s that are units of the initialization work, and have them declare
+ * It first builds a set of {@link org.jvnet.hudson.reactor.Task}s that are units of the initialization work, and have them declare
* dependencies among themselves. For example, jobs are only loaded after all the plugins are initialized,
* and restoring the build queue requires all the jobs to be loaded.
*
*
* Such micro-scopic dependencies are organized into a bigger directed acyclic graph, which is then executed
- * via {@link Session}. During execution of the reactor, additional tasks can be discovred and added to
+ * via Session. During execution of the reactor, additional tasks can be discovred and added to
* the DAG. We use this additional indirection to:
*
*
diff --git a/core/src/main/java/hudson/logging/LogRecorder.java b/core/src/main/java/hudson/logging/LogRecorder.java
index 1326f93c0f..f780252af4 100644
--- a/core/src/main/java/hudson/logging/LogRecorder.java
+++ b/core/src/main/java/hudson/logging/LogRecorder.java
@@ -25,12 +25,20 @@ package hudson.logging;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
+import hudson.Extension;
+import hudson.FilePath;
import hudson.Util;
import hudson.XmlFile;
import hudson.model.AbstractModelObject;
+import hudson.model.Computer;
import jenkins.model.Jenkins;
import hudson.model.Saveable;
+import hudson.model.TaskListener;
import hudson.model.listeners.SaveableListener;
+import hudson.remoting.Callable;
+import hudson.remoting.Channel;
+import hudson.remoting.VirtualChannel;
+import hudson.slaves.ComputerListener;
import hudson.util.CopyOnWriteList;
import hudson.util.RingBufferLogHandler;
import hudson.util.XStream2;
@@ -43,12 +51,20 @@ import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
+import java.text.Collator;
+import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
-import java.util.Locale;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Records a selected set of logs so that the system administrator
@@ -100,7 +116,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));
}
public Level getLevel() {
@@ -110,11 +126,13 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
public boolean includes(LogRecord r) {
if(r.getLevel().intValue() < level)
return false; // below the threshold
+ if (name.length() == 0) {
+ return true; // like root logger, includes everything
+ }
String logName = r.getLoggerName();
if(logName==null || !logName.startsWith(name))
return false; // not within this logger
-
- String rest = r.getLoggerName().substring(name.length());
+ String rest = logName.substring(name.length());
return rest.startsWith(".") || rest.length()==0;
}
@@ -132,6 +150,54 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
Logger l = getLogger();
if(!l.isLoggable(getLevel()))
l.setLevel(getLevel());
+ new SetLevel(name, getLevel()).broadcast();
+ }
+
+ public void disable() {
+ getLogger().setLevel(null);
+ new SetLevel(name, null).broadcast();
+ }
+
+ }
+
+ private static final class SetLevel implements Callable {
+ /** known loggers (kept per slave), to avoid GC */
+ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Set loggers = new HashSet();
+ private final String name;
+ private final Level level;
+ SetLevel(String name, Level level) {
+ this.name = name;
+ this.level = level;
+ }
+ @Override public Void call() throws Error {
+ Logger logger = Logger.getLogger(name);
+ loggers.add(logger);
+ logger.setLevel(level);
+ return null;
+ }
+ void broadcast() {
+ for (Computer c : Jenkins.getInstance().getComputers()) {
+ if (c.getName().length() > 0) { // i.e. not master
+ VirtualChannel ch = c.getChannel();
+ if (ch != null) {
+ try {
+ ch.call(this);
+ } catch (Exception x) {
+ Logger.getLogger(LogRecorder.class.getName()).log(Level.WARNING, "could not set up logging on " + c, x);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @Extension @Restricted(NoExternalUse.class) public static final class ComputerLogInitializer extends ComputerListener {
+ @Override public void preOnline(Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException {
+ for (LogRecorder recorder : Jenkins.getInstance().getLog().logRecorders.values()) {
+ for (Target t : recorder.targets) {
+ channel.call(new SetLevel(t.name, t.getLevel()));
+ }
+ }
}
}
@@ -147,7 +213,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
}
public String getSearchUrl() {
- return name;
+ return Util.rawEncode(name);
}
public String getName() {
@@ -215,7 +281,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
// Disable logging for all our targets,
// then reenable all other loggers in case any also log the same targets
for (Target t : targets)
- t.getLogger().setLevel(null);
+ t.disable();
for (LogRecorder log : getParent().logRecorders.values())
for (Target t : log.targets)
t.enable();
@@ -243,6 +309,44 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
return handler.getView();
}
+ /**
+ * Gets a view of log records per slave matching this recorder.
+ * @return a map (sorted by display name) from computer to (nonempty) list of log records
+ * @since 1.519
+ */
+ public Map> getSlaveLogRecords() {
+ Map> result = new TreeMap>(new Comparator() {
+ final Collator COLL = Collator.getInstance();
+ public int compare(Computer c1, Computer c2) {
+ return COLL.compare(c1.getDisplayName(), c2.getDisplayName());
+ }
+ });
+ for (Computer c : Jenkins.getInstance().getComputers()) {
+ if (c.getName().length() == 0) {
+ continue; // master
+ }
+ List recs = new ArrayList();
+ try {
+ for (LogRecord rec : c.getLogRecords()) {
+ for (Target t : targets) {
+ if (t.includes(rec)) {
+ recs.add(rec);
+ break;
+ }
+ }
+ }
+ } catch (IOException x) {
+ continue;
+ } catch (InterruptedException x) {
+ continue;
+ }
+ if (!recs.isEmpty()) {
+ result.put(c, recs);
+ }
+ }
+ return result;
+ }
+
/**
* Thread-safe reusable {@link XStream}.
*/
@@ -257,6 +361,5 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
* Log levels that can be configured for {@link Target}.
*/
public static List LEVELS =
- Arrays.asList(Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG,
- Level.FINE, Level.FINER, Level.FINEST, Level.ALL);
+ Arrays.asList(Level.ALL, Level.FINEST, Level.FINER, Level.FINE, Level.CONFIG, Level.INFO, Level.WARNING, Level.SEVERE);
}
diff --git a/core/src/main/java/hudson/logging/LogRecorderManager.java b/core/src/main/java/hudson/logging/LogRecorderManager.java
index 4cd47477b3..ab8337c701 100644
--- a/core/src/main/java/hudson/logging/LogRecorderManager.java
+++ b/core/src/main/java/hudson/logging/LogRecorderManager.java
@@ -116,8 +116,8 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu menu = new ContextMenu();
menu.add("all","All Jenkins Logs");
- for (Entry e : logRecorders.entrySet()) {
- menu.add(e.getKey(),e.getKey());
+ for (LogRecorder lr : logRecorders.values()) {
+ menu.add(lr.getSearchUrl(), lr.getDisplayName());
}
return menu;
}
diff --git a/core/src/main/java/hudson/markup/MyspacePolicy.java b/core/src/main/java/hudson/markup/MyspacePolicy.java
index f0543f9538..46d0c31e22 100644
--- a/core/src/main/java/hudson/markup/MyspacePolicy.java
+++ b/core/src/main/java/hudson/markup/MyspacePolicy.java
@@ -67,7 +67,6 @@ public class MyspacePolicy {
tag("img", "src",ONSITE_OR_OFFSITE_URL,
"hspace","vspace");
tag("iframe", "src");
- tag("link", "type","rel");
tag("ul,ol,li,dd,dl,dt,thead,tbody,tfoot");
tag("table", "noresize");
tag("td,th,tr");
diff --git a/core/src/main/java/hudson/matrix/Axis.java b/core/src/main/java/hudson/matrix/Axis.java
index c776f6ad04..faec4501e1 100644
--- a/core/src/main/java/hudson/matrix/Axis.java
+++ b/core/src/main/java/hudson/matrix/Axis.java
@@ -76,10 +76,11 @@ public class Axis extends AbstractDescribableImpl implements Comparable values;
public Axis(String name, List values) {
+ if (values == null || values.isEmpty()) {
+ values = Collections.emptyList();
+ }
this.name = name;
this.values = new ArrayList(values);
- if(values.isEmpty())
- throw new IllegalArgumentException(); // bug in the code
}
public Axis(String name, String... values) {
diff --git a/core/src/main/java/hudson/matrix/AxisList.java b/core/src/main/java/hudson/matrix/AxisList.java
index aa9c29efeb..a93a16746b 100644
--- a/core/src/main/java/hudson/matrix/AxisList.java
+++ b/core/src/main/java/hudson/matrix/AxisList.java
@@ -88,7 +88,7 @@ public class AxisList extends ArrayList {
}
/**
- * {@link Converter} implementation for XStream.
+ * {@link com.thoughtworks.xstream.converters.Converter} implementation for XStream.
*/
public static final class ConverterImpl extends RobustCollectionConverter {
public ConverterImpl(XStream xs) {
diff --git a/core/src/main/java/hudson/matrix/Combination.java b/core/src/main/java/hudson/matrix/Combination.java
index 67a02584f9..76782a9df3 100644
--- a/core/src/main/java/hudson/matrix/Combination.java
+++ b/core/src/main/java/hudson/matrix/Combination.java
@@ -111,10 +111,18 @@ public final class Combination extends TreeMap implements Compara
* true.
*/
public boolean evalGroovyExpression(AxisList axes, String expression) {
+
+ return evalGroovyExpression(axes, expression, new Binding());
+ }
+
+ /**
+ * @see #evalGroovyExpression(AxisList, String)
+ * @since 1.515
+ */
+ public boolean evalGroovyExpression(AxisList axes, String expression, Binding binding) {
if(Util.fixEmptyAndTrim(expression)==null)
return true;
- Binding binding = new Binding();
for (Map.Entry e : entrySet())
binding.setVariable(e.getKey(),e.getValue());
diff --git a/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java b/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
index 2a25fc2bf9..9541d907a5 100644
--- a/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
+++ b/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
@@ -1,5 +1,7 @@
package hudson.matrix;
+import groovy.lang.Binding;
+import groovy.lang.GroovyRuntimeException;
import hudson.AbortException;
import hudson.Extension;
import hudson.Util;
@@ -8,6 +10,7 @@ import hudson.matrix.MatrixBuild.MatrixBuildExecution;
import hudson.matrix.listeners.MatrixBuildListener;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
+import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.Queue;
import hudson.model.ResourceController;
@@ -113,27 +116,21 @@ public class DefaultMatrixExecutionStrategyImpl extends MatrixExecutionStrategy
@Override
public Result run(MatrixBuildExecution execution) throws InterruptedException, IOException {
- MatrixBuild build = execution.getBuild();
- MatrixProject p = execution.getProject();
- PrintStream logger = execution.getListener().getLogger();
Collection touchStoneConfigurations = new HashSet();
Collection delayedConfigurations = new HashSet();
- for (MatrixConfiguration c: execution.getActiveConfigurations()) {
- if (!MatrixBuildListener.buildConfiguration(build, c))
- continue; // skip rebuild
- if (touchStoneCombinationFilter != null && c.getCombination().evalGroovyExpression(p.getAxes(), getTouchStoneCombinationFilter())) {
- touchStoneConfigurations.add(c);
- } else {
- delayedConfigurations.add(c);
- }
- }
+
+ filterConfigurations(
+ execution,
+ touchStoneConfigurations,
+ delayedConfigurations
+ );
if (notifyStartBuild(execution.getAggregators())) return Result.FAILURE;
if (sorter != null) {
touchStoneConfigurations = createTreeSet(touchStoneConfigurations, sorter);
- delayedConfigurations = createTreeSet(delayedConfigurations,sorter);
+ delayedConfigurations = createTreeSet(delayedConfigurations, sorter);
}
if(!runSequentially)
@@ -148,7 +145,9 @@ public class DefaultMatrixExecutionStrategyImpl extends MatrixExecutionStrategy
notifyEndBuild(run,execution.getAggregators());
r = r.combine(getResult(run));
}
-
+
+ PrintStream logger = execution.getListener().getLogger();
+
if (touchStoneResultCondition != null && r.isWorseThan(touchStoneResultCondition)) {
logger.printf("Touchstone configurations resulted in %s, so aborting...%n", r);
return r;
@@ -170,6 +169,71 @@ public class DefaultMatrixExecutionStrategyImpl extends MatrixExecutionStrategy
return r;
}
+ private void filterConfigurations(
+ final MatrixBuildExecution execution,
+ final Collection touchStoneConfigurations,
+ final Collection delayedConfigurations
+ ) throws AbortException {
+
+ final MatrixBuild build = execution.getBuild();
+
+ final String combinationFilter = execution.getProject().getCombinationFilter();
+ final String touchStoneFilter = getTouchStoneCombinationFilter();
+
+ try {
+
+ for (MatrixConfiguration c: execution.getActiveConfigurations()) {
+
+ if (!MatrixBuildListener.buildConfiguration(build, c)) continue; // skip rebuild
+
+ final Combination combination = c.getCombination();
+
+ if (touchStoneFilter != null && satisfies(execution, combination, touchStoneFilter)) {
+ touchStoneConfigurations.add(c);
+ } else if (satisfies(execution, combination, combinationFilter)) {
+ delayedConfigurations.add(c);
+ }
+ }
+ } catch (GroovyRuntimeException ex) {
+
+ PrintStream logger = execution.getListener().getLogger();
+ logger.println(ex.getMessage());
+ ex.printStackTrace(logger);
+ throw new AbortException("Failed executing combination filter");
+ }
+ }
+
+ private boolean satisfies(
+ final MatrixBuildExecution execution,
+ final Combination combination,
+ final String filter
+ ) {
+
+ return combination.evalGroovyExpression(
+ execution.getProject().getAxes(),
+ filter,
+ getConfiguredBinding(execution)
+ );
+ }
+
+ private Binding getConfiguredBinding(final MatrixBuildExecution execution) {
+
+ final Binding binding = new Binding();
+ final ParametersAction parameters = execution.getBuild().getAction(ParametersAction.class);
+
+ if (parameters == null) return binding;
+
+ for (final ParameterValue pv: parameters) {
+
+ if (pv == null) continue;
+ final String name = pv.getName();
+ final String value = pv.createVariableResolver(null).resolve(name);;
+ binding.setVariable(name, value);
+ }
+
+ return binding;
+ }
+
private Result getResult(@Nullable MatrixRun run) {
// null indicates that the run was cancelled before it even gets going
return run!=null ? run.getResult() : Result.ABORTED;
@@ -250,7 +314,7 @@ public class DefaultMatrixExecutionStrategyImpl extends MatrixExecutionStrategy
if(qi!=null) {
// if the build seems to be stuck in the queue, display why
String why = qi.getWhy();
- if(!why.equals(whyInQueue) && System.currentTimeMillis()-startTime>5000) {
+ if(why != null && !why.equals(whyInQueue) && System.currentTimeMillis()-startTime>5000) {
listener.getLogger().print("Configuration " + ModelHyperlinkNote.encodeTo(c)+" is still in the queue: ");
qi.getCauseOfBlockage().print(listener); //this is still shown on the same line
whyInQueue = why;
diff --git a/core/src/main/java/hudson/matrix/Layouter.java b/core/src/main/java/hudson/matrix/Layouter.java
index 941a38de10..051b8f6239 100644
--- a/core/src/main/java/hudson/matrix/Layouter.java
+++ b/core/src/main/java/hudson/matrix/Layouter.java
@@ -201,8 +201,11 @@ public abstract class Layouter {
buildMap(xp,x);
buildMap(yp,y);
buildMap(zp,z);
- for (Axis a : trivial)
- m.put(a.name,a.value(0));
+ for (Axis a : trivial) {
+ if (a.size() > 0) {
+ m.put(a.name, a.value(0));
+ }
+ }
return getT(new Combination(m));
}
diff --git a/core/src/main/java/hudson/matrix/MatrixAggregator.java b/core/src/main/java/hudson/matrix/MatrixAggregator.java
index f82a5919ce..dbdfcaffa7 100644
--- a/core/src/main/java/hudson/matrix/MatrixAggregator.java
+++ b/core/src/main/java/hudson/matrix/MatrixAggregator.java
@@ -74,7 +74,7 @@ public abstract class MatrixAggregator implements ExtensionPoint {
* @return
* true if the build can continue, false if there was an error
* and the build needs to be aborted.
- * @see BuildStep#prebuild(Build,BuildListener)
+ * @see BuildStep#prebuild(AbstractBuild,BuildListener)
*/
public boolean startBuild() throws InterruptedException, IOException {
return true;
diff --git a/core/src/main/java/hudson/matrix/MatrixBuild.java b/core/src/main/java/hudson/matrix/MatrixBuild.java
index bcef17f888..5675842311 100644
--- a/core/src/main/java/hudson/matrix/MatrixBuild.java
+++ b/core/src/main/java/hudson/matrix/MatrixBuild.java
@@ -368,7 +368,8 @@ public class MatrixBuild extends AbstractBuild {
final int n = getNumber();
for (MatrixConfiguration c : activeConfigurations) {
for (Item i : q.getItems(c)) {
- if (i.getAction(ParentBuildAction.class).parent==getBuild()) {
+ ParentBuildAction a = i.getAction(ParentBuildAction.class);
+ if (a!=null && a.parent==getBuild()) {
q.cancel(i);
logger.println(Messages.MatrixBuild_Cancelled(ModelHyperlinkNote.encodeTo(c)));
}
diff --git a/core/src/main/java/hudson/matrix/MatrixConfiguration.java b/core/src/main/java/hudson/matrix/MatrixConfiguration.java
index b1c56409be..f57fff9682 100644
--- a/core/src/main/java/hudson/matrix/MatrixConfiguration.java
+++ b/core/src/main/java/hudson/matrix/MatrixConfiguration.java
@@ -239,6 +239,10 @@ public class MatrixConfiguration extends Project
}
}
+ if (lb == null) {
+ throw new IOException("cannot start a build of " + getFullName() + " since its parent has no builds at all");
+ }
+
// for every MatrixRun there should be a parent MatrixBuild
MatrixRun lastBuild = new MatrixRun(this, lb.getTimestamp());
@@ -393,17 +397,16 @@ public class MatrixConfiguration extends Project
* @param parameters
* Can be null.
* @deprecated
- * Use {@link #scheduleBuild(List extends Action>, Cause)}. Since 1.480
+ * Use {@link #scheduleBuild(List, Cause)}. Since 1.480
*/
public boolean scheduleBuild(ParametersAction parameters, Cause c) {
-
return scheduleBuild(Collections.singletonList(parameters), c);
}
/**
* Starts the build with the actions that are passed in.
*
* @param actions Can be null.
- * @param cause Reason for starting the build
+ * @param c Reason for starting the build
*/
public boolean scheduleBuild(List extends Action> actions, Cause c) {
List allActions = new ArrayList();
@@ -414,7 +417,7 @@ public class MatrixConfiguration extends Project
allActions.add(new ParentBuildAction());
allActions.add(new CauseAction(c));
- return Jenkins.getInstance().getQueue().schedule(this, getQuietPeriod(), allActions )!=null;
+ return Jenkins.getInstance().getQueue().schedule2(this, getQuietPeriod(), allActions ).isAccepted();
}
/**
diff --git a/core/src/main/java/hudson/matrix/MatrixExecutionStrategy.java b/core/src/main/java/hudson/matrix/MatrixExecutionStrategy.java
index 3dd56545c1..33948422d7 100644
--- a/core/src/main/java/hudson/matrix/MatrixExecutionStrategy.java
+++ b/core/src/main/java/hudson/matrix/MatrixExecutionStrategy.java
@@ -38,7 +38,7 @@ import java.util.List;
* some fails, etc.
*
* @author Kohsuke Kawaguchi
- * @sicne 1.456
+ * @since 1.456
*/
public abstract class MatrixExecutionStrategy extends AbstractDescribableImpl implements ExtensionPoint {
public Result run(MatrixBuildExecution execution) throws InterruptedException, IOException {
@@ -47,7 +47,7 @@ public abstract class MatrixExecutionStrategy extends AbstractDescribableImpl aggregators, BuildListener listener) throws InterruptedException, IOException {
throw new UnsupportedOperationException(getClass()+" needs to override run(MatrixBuildExecution)");
diff --git a/core/src/main/java/hudson/matrix/MatrixProject.java b/core/src/main/java/hudson/matrix/MatrixProject.java
index c3918fb784..6390db6839 100644
--- a/core/src/main/java/hudson/matrix/MatrixProject.java
+++ b/core/src/main/java/hudson/matrix/MatrixProject.java
@@ -41,6 +41,7 @@ import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Node;
import hudson.slaves.WorkspaceList;
+import hudson.util.AlternativeUiTextProvider;
import jenkins.model.Jenkins;
import hudson.model.Item;
import hudson.model.ItemGroup;
@@ -48,6 +49,8 @@ import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.Label;
+import hudson.model.ParameterDefinition;
+import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue.FlyweightTask;
import hudson.model.Result;
import hudson.model.SCMedItem;
@@ -63,9 +66,10 @@ import hudson.util.CopyOnWriteMap;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.FormValidation.Kind;
-import jenkins.model.ModelObjectWithChildren;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import net.sf.json.JSONObject;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
@@ -89,6 +93,8 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/**
* {@link Job} that allows you to run multiple different configurations
@@ -190,6 +196,11 @@ public class MatrixProject extends AbstractProject im
super(parent, name);
}
+ @Override
+ public String getPronoun() {
+ return AlternativeUiTextProvider.get(PRONOUN, this, Messages.MatrixProject_Pronoun());
+ }
+
/**
* Gets the workspace location that {@link MatrixConfiguration} uses.
*
@@ -419,7 +430,7 @@ public class MatrixProject extends AbstractProject im
r.addAll(step.getProjectActions(this));
for (BuildWrapper step : buildWrappers)
r.addAll(step.getProjectActions(this));
- for (Trigger> trigger : triggers)
+ for (Trigger> trigger : triggers())
r.addAll(trigger.getProjectActions());
return r;
@@ -603,9 +614,11 @@ public class MatrixProject extends AbstractProject im
}
// find all active configurations
- Set active = new LinkedHashSet();
+ final Set active = new LinkedHashSet();
+ final boolean isDynamicFilter = isDynamicFilter(getCombinationFilter());
+
for (Combination c : activeCombinations) {
- if(c.evalGroovyExpression(axes,combinationFilter)) {
+ if(isDynamicFilter || c.evalGroovyExpression(axes,getCombinationFilter())) {
LOGGER.fine("Adding configuration: " + c);
MatrixConfiguration config = configurations.get(c);
if(config==null) {
@@ -622,6 +635,27 @@ public class MatrixProject extends AbstractProject im
return active;
}
+ private boolean isDynamicFilter(final String filter) {
+
+ if (!isParameterized() || filter == null) return false;
+
+ final ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
+
+ for (final ParameterDefinition definition : paramDefProp.getParameterDefinitions()) {
+
+ final String name = definition.getName();
+
+ final Matcher matcher = Pattern
+ .compile("\\b" + name + "\\b")
+ .matcher(filter)
+ ;
+
+ if (matcher.find()) return true;
+ }
+
+ return false;
+ }
+
private File getConfigurationsDir() {
return new File(getRootDir(),"configurations");
}
@@ -864,9 +898,14 @@ public class MatrixProject extends AbstractProject im
}
public DescriptorImpl getDescriptor() {
- return DESCRIPTOR;
+ return (DescriptorImpl)Jenkins.getInstance().getDescriptorOrDie(getClass());
}
+ /**
+ * Descriptor is instantiated as a field purely for backward compatibility.
+ * Do not do this in your code. Put @Extension on your DescriptorImpl class instead.
+ */
+ @Restricted(NoExternalUse.class)
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
diff --git a/core/src/main/java/hudson/matrix/listeners/MatrixBuildListener.java b/core/src/main/java/hudson/matrix/listeners/MatrixBuildListener.java
index 4bb7076f23..53c37003a4 100644
--- a/core/src/main/java/hudson/matrix/listeners/MatrixBuildListener.java
+++ b/core/src/main/java/hudson/matrix/listeners/MatrixBuildListener.java
@@ -41,7 +41,7 @@ import java.util.List;
*
* Plugins can implement this extension point to filter out the subset of matrix project to build.
* Most typically, such a plugin would add a custom {@link Action} to a build when it goes to the queue
- * ({@link Queue#schedule(Task, int, List)}, then access this from {@link MatrixBuild} to drive
+ * ({@link Queue#schedule2(Task, int, List)}, then access this from {@link MatrixBuild} to drive
* the filtering logic.
*
*
diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java
index e4ff4b86c1..522cc47829 100644
--- a/core/src/main/java/hudson/model/AbstractBuild.java
+++ b/core/src/main/java/hudson/model/AbstractBuild.java
@@ -37,7 +37,6 @@ import hudson.console.ModelHyperlinkNote;
import hudson.matrix.MatrixConfiguration;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.Fingerprint.RangeSet;
-import hudson.model.PermalinkProjectAction.Permalink;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SCMListener;
import hudson.scm.ChangeLogParser;
@@ -59,7 +58,6 @@ import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.AggregatedTestResultAction;
import hudson.util.*;
import jenkins.model.Jenkins;
-import jenkins.model.PeepholePermalink;
import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
import jenkins.model.lazy.BuildReference;
import org.kohsuke.stapler.HttpResponse;
@@ -153,7 +151,7 @@ public abstract class AbstractBuild
,R extends Abs
private volatile Set culprits;
/**
- * During the build this field remembers {@link BuildWrapper.Environment}s created by
+ * During the build this field remembers {@link hudson.tasks.BuildWrapper.Environment}s created by
* {@link BuildWrapper}. This design is bit ugly but forced due to compatibility.
*/
protected transient List buildEnvironments;
@@ -217,7 +215,7 @@ public abstract class AbstractBuild,R extends Abs
// having two neighbors pointing to each other is important to make RunMap.removeValue work
P _parent = getParent();
if (_parent == null) {
- throw new IllegalStateException("no parent for " + this);
+ throw new IllegalStateException("no parent for " + number + " in " + workspace);
}
R pb = _parent._getRuns().search(number-1, Direction.DESC);
if (pb!=null) {
@@ -360,7 +358,7 @@ public abstract class AbstractBuild
,R extends Abs
}
/**
- * Normally, a workspace is assigned by {@link RunExecution}, but this lets you set the workspace in case
+ * Normally, a workspace is assigned by {@link hudson.model.Run.RunExecution}, but this lets you set the workspace in case
* {@link AbstractBuild} is created without a build.
*/
protected void setWorkspace(FilePath ws) {
@@ -477,26 +475,9 @@ public abstract class AbstractBuild
,R extends Abs
return hudsonVersion;
}
- /**
- * Backward compatibility.
- *
- * We used to have $JENKINS_HOME/jobs/JOBNAME/lastStable and lastSuccessful symlinked to the appropriate
- * builds, but now those are done in {@link PeepholePermalink}. So here, we simply create symlinks that
- * resolves to the symlink created by {@link PeepholePermalink}.
- */
- private void createSymlink(TaskListener listener, String name, Permalink target) throws InterruptedException {
- String targetDir;
- if (getProject().getBuildDir().equals(new File(getProject().getRootDir(), "builds"))) {
- targetDir = "builds/" + target.getId();
- } else {
- targetDir = getProject().getBuildDir()+"/"+target.getId();
- }
- Util.createSymlink(getProject().getRootDir(), targetDir, name, listener);
- }
-
/**
* @deprecated as of 1.467
- * Please use {@link RunExecution}
+ * Please use {@link hudson.model.Run.RunExecution}
*/
public abstract class AbstractRunner extends AbstractBuildExecution {
@@ -724,9 +705,6 @@ public abstract class AbstractBuild
,R extends Abs
public final void post(BuildListener listener) throws Exception {
try {
post2(listener);
-
- createSymlink(listener, "lastSuccessful", Permalink.LAST_SUCCESSFUL_BUILD);
- createSymlink(listener, "lastStable", Permalink.LAST_STABLE_BUILD);
} finally {
// update the culprit list
HashSet r = new HashSet();
diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java
index ecbbbafce5..518234e652 100644
--- a/core/src/main/java/hudson/model/AbstractItem.java
+++ b/core/src/main/java/hudson/model/AbstractItem.java
@@ -401,7 +401,9 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
}
public String getShortUrl() {
- return getParent().getUrlChildPrefix()+'/'+Util.rawEncode(getName())+'/';
+ String prefix = getParent().getUrlChildPrefix();
+ String subdir = Util.rawEncode(getName());
+ return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/';
}
public String getSearchUrl() {
@@ -511,7 +513,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
// ignore
}
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
}
/**
@@ -590,7 +592,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
} finally {
Items.updatingByXml.set(false);
}
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
// if everything went well, commit this new version
out.commit();
diff --git a/core/src/main/java/hudson/model/AbstractProject.java b/core/src/main/java/hudson/model/AbstractProject.java
index 239d6ffaed..6a5cc387f5 100644
--- a/core/src/main/java/hudson/model/AbstractProject.java
+++ b/core/src/main/java/hudson/model/AbstractProject.java
@@ -39,7 +39,6 @@ import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
-import hudson.matrix.MatrixConfiguration;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserIdCause;
@@ -49,14 +48,15 @@ import hudson.model.PermalinkProjectAction.Permalink;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.queue.QueueTaskFuture;
+import hudson.model.queue.ScheduleResult;
import hudson.model.queue.SubTask;
-import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTaskContributor;
+import hudson.node_monitors.DiskSpaceMonitor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
@@ -92,8 +92,10 @@ import jenkins.scm.SCMCheckoutStrategy;
import jenkins.scm.SCMCheckoutStrategyDescriptor;
import jenkins.util.TimeDuration;
import net.sf.json.JSONObject;
+import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
+import org.jenkinsci.bytecode.AdaptField;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
@@ -109,6 +111,7 @@ import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
+import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
@@ -120,6 +123,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
@@ -128,10 +132,12 @@ import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.scm.PollingResult.*;
+import javax.annotation.CheckForNull;
import static javax.servlet.http.HttpServletResponse.*;
/**
@@ -237,7 +243,10 @@ public abstract class AbstractProject,R extends A
/**
* List of all {@link Trigger}s for this project.
*/
- protected List> triggers = new Vector>();
+ @AdaptField(was=List.class)
+ protected volatile DescribableList,TriggerDescriptor> triggers = new DescribableList,TriggerDescriptor>(this);
+ private static final AtomicReferenceFieldUpdater triggersUpdater
+ = AtomicReferenceFieldUpdater.newUpdater(AbstractProject.class,DescribableList.class,"triggers");
/**
* {@link Action}s contributed from subsidiary objects associated with
@@ -261,7 +270,7 @@ public abstract class AbstractProject,R extends A
protected AbstractProject(ItemGroup parent, String name) {
super(parent,name);
- if(!Jenkins.getInstance().getNodes().isEmpty()) {
+ if(Jenkins.getInstance()!=null && !Jenkins.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
@@ -293,7 +302,13 @@ public abstract class AbstractProject
,R extends A
if (currentBuilds==null && parent!=null) {
// are we overwriting what currently exist?
// this is primarily when Jenkins is getting reloaded
- Item current = parent.getItem(name);
+ Item current;
+ try {
+ current = parent.getItem(name);
+ } catch (RuntimeException x) {
+ LOGGER.log(Level.WARNING, "failed to look up " + name + " in " + parent, x);
+ current = null;
+ }
if (current!=null && current.getClass()==getClass()) {
currentBuilds = ((AbstractProject)current).builds;
}
@@ -306,6 +321,7 @@ public abstract class AbstractProject
,R extends A
}
}
this.builds = builds;
+ triggers().setOwner(this);
for (Trigger t : triggers())
t.start(this, Items.updatingByXml.get());
if(scm==null)
@@ -324,9 +340,10 @@ public abstract class AbstractProject
,R extends A
});
}
- private synchronized List> triggers() {
+ @WithBridgeMethods(List.class)
+ protected DescribableList,TriggerDescriptor> triggers() {
if (triggers == null) {
- triggers = new Vector>();
+ triggersUpdater.compareAndSet(this,null,new DescribableList,TriggerDescriptor>(this));
}
return triggers;
}
@@ -555,6 +572,15 @@ public abstract class AbstractProject,R extends A
}
return null;
}
+
+ private R getSomeBuildWithExistingWorkspace() throws IOException, InterruptedException {
+ int cnt=0;
+ for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
+ FilePath ws = b.getWorkspace();
+ if (ws!=null && ws.exists()) return b;
+ }
+ return null;
+ }
/**
* Returns the root directory of the checked-out module.
@@ -770,7 +796,7 @@ public abstract class AbstractProject
,R extends A
Jenkins.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
}
/**
@@ -853,9 +879,8 @@ public abstract class AbstractProject
,R extends A
* Schedules a build of this project.
*
* @return
- * true if the project is actually added to the queue.
- * false if the queue contained it and therefore the add()
- * was noop
+ * true if the project is added to the queue.
+ * false if the task was rejected from the queue (such as when the system is being shut down.)
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
@@ -916,9 +941,9 @@ public abstract class AbstractProject
,R extends A
queueActions.add(new CauseAction(c));
}
- WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
- if(i!=null)
- return (QueueTaskFuture)i.getFuture();
+ ScheduleResult i = Jenkins.getInstance().getQueue().schedule2(this, quietPeriod, queueActions);
+ if(i.isAccepted())
+ return (QueueTaskFuture)i.getItem().getFuture();
return null;
}
@@ -1021,7 +1046,9 @@ public abstract class AbstractProject
,R extends A
@Override
public void removeRun(R run) {
- this.builds.remove(run);
+ if (!this.builds.remove(run)) {
+ LOGGER.log(Level.WARNING, "{0} did not contain {1} to begin with", new Object[] {this, run});
+ }
}
/**
@@ -1055,7 +1082,7 @@ public abstract class AbstractProject
,R extends A
}
@Override
- public R getLastBuild() {
+ public @CheckForNull R getLastBuild() {
return builds.newestBuild();
}
@@ -1174,6 +1201,12 @@ public abstract class AbstractProject
,R extends A
return this;
}
+ @Nonnull
+ public Authentication getDefaultAuthentication() {
+ // backward compatible behaviour.
+ return ACL.SYSTEM;
+ }
+
/**
* {@inheritDoc}
*
@@ -1364,7 +1397,13 @@ public abstract class AbstractProject
,R extends A
return true; // no SCM
FilePath workspace = build.getWorkspace();
- workspace.mkdirs();
+ try {
+ workspace.mkdirs();
+ } catch (IOException e) {
+ // Can't create workspace dir - Is slave disk full ?
+ new DiskSpaceMonitor().markNodeOfflineIfDiskspaceIsTooLow(build.getBuiltOn().toComputer());
+ throw e;
+ }
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
if (r) {
@@ -1445,7 +1484,7 @@ public abstract class AbstractProject
,R extends A
try {
SCMPollListener.fireBeforePolling(this, listener);
- PollingResult r = _poll(listener, scm, lb);
+ PollingResult r = _poll(listener, scm);
SCMPollListener.firePollingSuccess(this,listener, r);
return r;
} catch (AbortException e) {
@@ -1474,18 +1513,20 @@ public abstract class AbstractProject
,R extends A
/**
* {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .
*/
- private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {
+ private PollingResult _poll(TaskListener listener, SCM scm) throws IOException, InterruptedException {
if (scm.requiresWorkspaceForPolling()) {
- // lock the workspace of the last build
- FilePath ws=lb.getWorkspace();
+ R b = getSomeBuildWithExistingWorkspace();
+ if (b == null) b = getLastBuild();
+ // lock the workspace for the given build
+ FilePath ws=b.getWorkspace();
- WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );
+ WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( b );
if ( workspaceOfflineReason != null ) {
// workspace offline
for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {
ws = browser.getWorkspace(this);
if (ws != null) {
- return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());
+ return pollWithWorkspace(listener, scm, b, ws, browser.getWorkspaceList());
}
}
@@ -1510,8 +1551,8 @@ public abstract class AbstractProject
,R extends A
return BUILD_NOW;
}
} else {
- WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
- return pollWithWorkspace(listener, scm, lb, ws, l);
+ WorkspaceList l = b.getBuiltOn().toComputer().getWorkspaceList();
+ return pollWithWorkspace(listener, scm, b, ws, l);
}
} else {
@@ -1519,7 +1560,7 @@ public abstract class AbstractProject
,R extends A
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
- calcPollingBaseline(lb,null,listener);
+ calcPollingBaseline(getLastBuild(),null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
@@ -1534,8 +1575,10 @@ public abstract class AbstractProject
,R extends A
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
- Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));
+ Node node = lb.getBuiltOn();
+ Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(node,listener));
try {
+ listener.getLogger().println("Polling SCM changes on " + node.getSelfLabel().getName());
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
@@ -1606,15 +1649,8 @@ public abstract class AbstractProject
,R extends A
protected final synchronized >
void addToList( T item, List collection ) throws IOException {
- for( int i=0; i,R extends A
protected final synchronized >
void removeFromList(Descriptor item, List collection) throws IOException {
- for( int i=0; i< collection.size(); i++ ) {
- if(collection.get(i).getDescriptor()==item) {
+ final Iterator iCollection = collection.iterator();
+ while(iCollection.hasNext()) {
+ final T next = iCollection.next();
+ if(next.getDescriptor()==item) {
// found it
- collection.remove(i);
+ iCollection.remove();
save();
updateTransientActions();
return;
@@ -1634,8 +1672,8 @@ public abstract class AbstractProject,R extends A
}
@SuppressWarnings("unchecked")
- public synchronized Map getTriggers() {
- return (Map)Descriptor.toMap(triggers());
+ public Map> getTriggers() {
+ return triggers().toMap();
}
/**
@@ -1798,8 +1836,17 @@ public abstract class AbstractProject,R extends A
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
- Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));
- rsp.sendRedirect(".");
+ ScheduleResult r = Jenkins.getInstance().getQueue().schedule2(this, delay.getTime(), getBuildCause(req));
+ if (r.isAccepted()) {
+ rsp.sendRedirect(SC_CREATED,req.getContextPath()+'/'+r.getItem().getUrl());
+ } else
+ rsp.sendRedirect(".");
+ }
+
+ /** @deprecated use {@link #doBuild(StaplerRequest, StaplerResponse, TimeDuration)} */
+ @Deprecated
+ public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
+ doBuild(req, rsp, TimeDuration.fromString(req.getParameter("delay")));
}
/**
@@ -1820,7 +1867,7 @@ public abstract class AbstractProject
,R extends A
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*
- * @deprecated as of 1.488
+ * @deprecated as of 1.489
* Inject {@link TimeDuration}.
*/
public int getDelay(StaplerRequest req) throws ServletException {
@@ -1853,6 +1900,12 @@ public abstract class AbstractProject
,R extends A
}
+ /** @deprecated use {@link #doBuildWithParameters(StaplerRequest, StaplerResponse, TimeDuration)} */
+ @Deprecated
+ public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
+ doBuildWithParameters(req, rsp, TimeDuration.fromString(req.getParameter("delay")));
+ }
+
/**
* Schedules a new SCM polling command.
*/
@@ -1947,8 +2000,8 @@ public abstract class AbstractProject
,R extends A
for (Trigger t : triggers())
t.stop();
- triggers = buildDescribable(req, Trigger.for_(this));
- for (Trigger t : triggers)
+ triggers.replaceBy(buildDescribable(req, Trigger.for_(this)));
+ for (Trigger t : triggers())
t.start(this,true);
for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
diff --git a/core/src/main/java/hudson/model/AdministrativeMonitor.java b/core/src/main/java/hudson/model/AdministrativeMonitor.java
index 8f9082d856..93febdbd75 100644
--- a/core/src/main/java/hudson/model/AdministrativeMonitor.java
+++ b/core/src/main/java/hudson/model/AdministrativeMonitor.java
@@ -61,7 +61,7 @@ import org.kohsuke.stapler.StaplerResponse;
*
* - message.jelly
* -
- * If {@link #isActivated()} returns true, Hudson will use the message.jelly
+ * If {@link #isActivated()} returns true, Jenkins will use the message.jelly
* view of this object to render the warning text. This happens in the
* http://SERVER/jenkins/manage page. This view should typically render
* a DIV box with class='error' or class='warning' with a human-readable text
diff --git a/core/src/main/java/hudson/model/AsyncPeriodicWork.java b/core/src/main/java/hudson/model/AsyncPeriodicWork.java
index 52fdb148a1..f678e1425e 100644
--- a/core/src/main/java/hudson/model/AsyncPeriodicWork.java
+++ b/core/src/main/java/hudson/model/AsyncPeriodicWork.java
@@ -22,7 +22,7 @@ import java.util.logging.Level;
*/
public abstract class AsyncPeriodicWork extends PeriodicWork {
/**
- * Name of the work.
+ * Human readable name of the work.
*/
public final String name;
diff --git a/core/src/main/java/hudson/model/BallColor.java b/core/src/main/java/hudson/model/BallColor.java
index 7c27cc2c1a..17d468ec72 100644
--- a/core/src/main/java/hudson/model/BallColor.java
+++ b/core/src/main/java/hudson/model/BallColor.java
@@ -135,7 +135,7 @@ public enum BallColor implements StatusIcon {
* Gets the unanimated version.
*/
public BallColor noAnime() {
- if(isAnimated()) return valueOf(name().substring(0,name().length()-6));
+ if(isAnimated()) return valueOf(name().substring(0,name().length()-"_ANIME".length()));
else return this;
}
diff --git a/core/src/main/java/hudson/model/BuildAuthorizationToken.java b/core/src/main/java/hudson/model/BuildAuthorizationToken.java
index ddb9283925..8d4483ba08 100644
--- a/core/src/main/java/hudson/model/BuildAuthorizationToken.java
+++ b/core/src/main/java/hudson/model/BuildAuthorizationToken.java
@@ -31,6 +31,7 @@ import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
import jenkins.security.ApiTokenProperty;
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.HttpResponses;
@@ -84,6 +85,8 @@ public final class BuildAuthorizationToken {
return;
}
+ rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+ rsp.addHeader("Allow", "POST");
throw HttpResponses.forwardToView(project, "requirePOST.jelly");
}
diff --git a/core/src/main/java/hudson/model/Cause.java b/core/src/main/java/hudson/model/Cause.java
index 4ccab03338..187bed2ce4 100644
--- a/core/src/main/java/hudson/model/Cause.java
+++ b/core/src/main/java/hudson/model/Cause.java
@@ -148,6 +148,39 @@ public abstract class Cause {
this.upstreamCauses = upstreamCauses;
}
+ /**
+ * @since 1.515
+ */
+ @Override
+ public boolean equals(Object rhs) {
+
+ if (this == rhs) return true;
+
+ if (!(rhs instanceof UpstreamCause)) return false;
+
+ final UpstreamCause o = (UpstreamCause) rhs;
+
+ if (upstreamBuild != o.upstreamBuild) return false;
+ if (!upstreamCauses.equals(o.upstreamCauses)) return false;
+ if (upstreamUrl == null ? o.upstreamUrl != null : !upstreamUrl.equals(o.upstreamUrl)) return false;
+ if (upstreamProject == null ? o.upstreamProject != null : !upstreamProject.equals(o.upstreamProject)) return false;
+
+ return true;
+ }
+
+ /**
+ * @since 1.515
+ */
+ @Override
+ public int hashCode() {
+
+ int hashCode = 17;
+ hashCode = hashCode * 31 + upstreamCauses.hashCode();
+ hashCode = hashCode * 31 + upstreamBuild;
+ hashCode = hashCode * 31 + (upstreamUrl == null ? 0 : upstreamUrl.hashCode ());
+ return hashCode * 31 + (upstreamProject == null ? 0 : upstreamProject.hashCode ());
+ }
+
private @Nonnull Cause trim(@Nonnull Cause c, int depth, Set traversed) {
if (!(c instanceof UpstreamCause)) {
return c;
diff --git a/core/src/main/java/hudson/model/CauseAction.java b/core/src/main/java/hudson/model/CauseAction.java
index e29dfeed57..c3a967932b 100644
--- a/core/src/main/java/hudson/model/CauseAction.java
+++ b/core/src/main/java/hudson/model/CauseAction.java
@@ -35,9 +35,10 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import jenkins.model.RunAction2;
@ExportedBean
-public class CauseAction implements FoldableAction, RunAction {
+public class CauseAction implements FoldableAction, RunAction2 {
/**
* @deprecated since 2009-02-28
*/
@@ -105,18 +106,14 @@ public class CauseAction implements FoldableAction, RunAction {
return causes.get(0).getShortDescription();
}
- public void onLoad() {
- // noop
- }
-
- public void onBuildComplete() {
+ @Override public void onLoad(Run,?> r) {
// noop
}
/**
* When hooked up to build, notify {@link Cause}s.
*/
- public void onAttached(Run owner) {
+ @Override public void onAttached(Run,?> owner) {
if (owner instanceof AbstractBuild) {// this should be always true but being defensive here
AbstractBuild b = (AbstractBuild) owner;
for (Cause c : causes) {
diff --git a/core/src/main/java/hudson/model/CheckPoint.java b/core/src/main/java/hudson/model/CheckPoint.java
index 1e95667c75..7a5e330af6 100644
--- a/core/src/main/java/hudson/model/CheckPoint.java
+++ b/core/src/main/java/hudson/model/CheckPoint.java
@@ -28,6 +28,7 @@ import hudson.tasks.Recorder;
import hudson.tasks.Builder;
import hudson.tasks.junit.JUnitResultArchiver;
import hudson.scm.SCM;
+import javax.annotation.Nonnull;
/**
* Provides a mechanism for synchronizing build executions in the face of concurrent builds.
@@ -141,7 +142,18 @@ public final class CheckPoint {
* If the build (represented by the calling executor thread) is aborted while it's waiting.
*/
public void block() throws InterruptedException {
- Run.waitForCheckpoint(this);
+ Run.waitForCheckpoint(this, null, null);
+ }
+
+ /**
+ * Like {@link #block()} but allows for richer logging.
+ * @param listener an optional listener to which
+ * @param waiter a description of what component is requesting the wait, such as {@link Descriptor#getDisplayName}
+ * @throws InterruptedException if the build is aborted while waiting
+ * @since 1.528
+ */
+ public void block(@Nonnull BuildListener listener, @Nonnull String waiter) throws InterruptedException {
+ Run.waitForCheckpoint(this, listener, waiter);
}
/**
diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java
index cc0edeb367..d74796793a 100644
--- a/core/src/main/java/hudson/model/Computer.java
+++ b/core/src/main/java/hudson/model/Computer.java
@@ -51,9 +51,6 @@ import hudson.slaves.RetentionStrategy;
import hudson.slaves.WorkspaceList;
import hudson.slaves.OfflineCause;
import hudson.slaves.OfflineCause.ByCLI;
-import hudson.tasks.BuildWrapper;
-import hudson.tasks.Publisher;
-import hudson.util.DaemonThreadFactory;
import hudson.util.EditDistance;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.RemotingDiagnostics;
@@ -79,6 +76,7 @@ import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
+import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
@@ -87,6 +85,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -1061,7 +1061,19 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
private static final long serialVersionUID = 1L;
}
- public static final ExecutorService threadPoolForRemoting = Executors.newCachedThreadPool(new ExceptionCatchingThreadFactory(new DaemonThreadFactory()));
+ public static final ExecutorService threadPoolForRemoting = Executors.newCachedThreadPool(new ExceptionCatchingThreadFactory(
+ new ThreadFactory() {
+
+ private final AtomicInteger threadNumber = new AtomicInteger(1);
+
+ @Override
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(r);
+ t.setName("Jenkins-Remoting-Thread-"+threadNumber.getAndIncrement());
+ t.setDaemon(true);
+ return t;
+ }
+ }));
//
//
@@ -1157,20 +1169,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
protected void _doScript( StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
- // ability to run arbitrary script is dangerous
- checkPermission(Jenkins.RUN_SCRIPTS);
-
- String text = req.getParameter("script");
- if(text!=null) {
- try {
- req.setAttribute("output",
- RemotingDiagnostics.executeGroovy(text,getChannel()));
- } catch (InterruptedException e) {
- throw new ServletException(e);
- }
- }
-
- req.getView(this,view).forward(req, rsp);
+ Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
/**
@@ -1209,9 +1208,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
if (req.getMethod().equals("POST")) {
// submission
- Node result = (Node)Jenkins.XSTREAM2.fromXML(req.getReader());
-
- replaceBy(result);
+ updateByXml(req.getInputStream());
return;
}
@@ -1238,6 +1235,17 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
}
+ /**
+ * Updates Job by its XML definition.
+ *
+ * @since XXX
+ */
+ public void updateByXml(final InputStream source) throws IOException, ServletException {
+ checkPermission(Jenkins.ADMINISTER);
+ Node result = (Node)Jenkins.XSTREAM2.fromXML(source);
+ replaceBy(result);
+ }
+
/**
* Really deletes the slave.
*/
@@ -1283,7 +1291,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Gets the current {@link Computer} that the build is running.
* This method only works when called during a build, such as by
- * {@link Publisher}, {@link BuildWrapper}, etc.
+ * {@link hudson.tasks.Publisher}, {@link hudson.tasks.BuildWrapper}, etc.
*/
public static Computer currentComputer() {
Executor e = Executor.currentExecutor();
@@ -1362,6 +1370,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._Computer_CreatePermission_Description(), Permission.CREATE, PermissionScope.COMPUTER);
public static final Permission DISCONNECT = new Permission(PERMISSIONS,"Disconnect", Messages._Computer_DisconnectPermission_Description(), Jenkins.ADMINISTER, PermissionScope.COMPUTER);
public static final Permission CONNECT = new Permission(PERMISSIONS,"Connect", Messages._Computer_ConnectPermission_Description(), DISCONNECT, PermissionScope.COMPUTER);
+ public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._Computer_BuildPermission_Description(), Permission.WRITE, PermissionScope.COMPUTER);
private static final Logger LOGGER = Logger.getLogger(Computer.class.getName());
}
diff --git a/core/src/main/java/hudson/model/ComputerPanelBox.java b/core/src/main/java/hudson/model/ComputerPanelBox.java
index 0f6af199cb..9854650655 100644
--- a/core/src/main/java/hudson/model/ComputerPanelBox.java
+++ b/core/src/main/java/hudson/model/ComputerPanelBox.java
@@ -11,7 +11,7 @@ import java.util.List;
*
* @author Lucie Votypkova
* @since 1.434
- * @see jenkins.model.Computer#getComputerPanelBoxs()
+ * @see hudson.model.Computer#getComputerPanelBoxs()
*/
public abstract class ComputerPanelBox implements ExtensionPoint{
diff --git a/core/src/main/java/hudson/model/ComputerSet.java b/core/src/main/java/hudson/model/ComputerSet.java
index 12ad63c941..cb9922e0b8 100644
--- a/core/src/main/java/hudson/model/ComputerSet.java
+++ b/core/src/main/java/hudson/model/ComputerSet.java
@@ -214,7 +214,10 @@ public final class ComputerSet extends AbstractModelObject implements Describabl
for (NodeMonitor nodeMonitor : NodeMonitor.getAll()) {
Thread t = nodeMonitor.triggerUpdate();
- t.setName(nodeMonitor.getColumnCaption());
+ String columnCaption = nodeMonitor.getColumnCaption();
+ if (columnCaption != null) {
+ t.setName(columnCaption);
+ }
}
rsp.forwardToPreviousPage(req);
}
@@ -426,8 +429,8 @@ public final class ComputerSet extends AbstractModelObject implements Describabl
r.add(i);
}
monitors.replaceBy(r.toList());
- } catch (IOException e) {
- LOGGER.log(Level.WARNING, "Failed to instanciate NodeMonitors",e);
+ } catch (Throwable x) {
+ LOGGER.log(Level.WARNING, "Failed to instantiate NodeMonitors", x);
}
}
diff --git a/core/src/main/java/hudson/model/DependencyGraph.java b/core/src/main/java/hudson/model/DependencyGraph.java
index b19ff76471..5b1ca1d11e 100644
--- a/core/src/main/java/hudson/model/DependencyGraph.java
+++ b/core/src/main/java/hudson/model/DependencyGraph.java
@@ -28,6 +28,8 @@ import jenkins.model.DependencyDeclarer;
import com.google.common.collect.ImmutableList;
import hudson.security.ACL;
import jenkins.model.Jenkins;
+import jenkins.util.DirectedGraph;
+import jenkins.util.DirectedGraph.SCC;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
@@ -75,6 +77,9 @@ public class DependencyGraph implements Comparator {
private boolean built;
+ private Comparator> topologicalOrder;
+ private List> topologicallySorted;
+
/**
* Builds the dependency graph.
*/
@@ -91,14 +96,57 @@ public class DependencyGraph implements Comparator {
forward = finalize(forward);
backward = finalize(backward);
-
+ topologicalDagSort();
this.computationalData = null;
built = true;
} finally {
SecurityContextHolder.setContext(saveCtx);
}
}
-
+
+ /**
+ *
+ *
+ * See http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
+ */
+ private void topologicalDagSort() {
+ DirectedGraph g = new DirectedGraph() {
+ @Override
+ protected Collection nodes() {
+ final Set nodes = new HashSet();
+ nodes.addAll(forward.keySet());
+ nodes.addAll(backward.keySet());
+ return nodes;
+ }
+
+ @Override
+ protected Collection forward(AbstractProject node) {
+ return getDownstream(node);
+ }
+ };
+
+ List> sccs = g.getStronglyConnectedComponents();
+
+ final Map topoOrder = new HashMap();
+ topologicallySorted = new ArrayList>();
+ int idx=0;
+ for (SCC scc : sccs) {
+ for (AbstractProject n : scc) {
+ topoOrder.put(n,idx++);
+ topologicallySorted.add(n);
+ }
+ }
+
+ topologicalOrder = new Comparator>() {
+ @Override
+ public int compare(AbstractProject,?> o1, AbstractProject,?> o2) {
+ return topoOrder.get(o1)-topoOrder.get(o2);
+ }
+ };
+
+ topologicallySorted = Collections.unmodifiableList(topologicallySorted);
+ }
+
Collection getAllProjects() {
return Jenkins.getInstance().getAllItems(AbstractProject.class);
}
@@ -108,6 +156,7 @@ public class DependencyGraph implements Comparator {
*/
private DependencyGraph(boolean dummy) {
forward = backward = Collections.emptyMap();
+ topologicalDagSort();
built = true;
}
@@ -199,7 +248,7 @@ public class DependencyGraph implements Comparator {
if(built)
throw new IllegalStateException();
add(forward,dep.getUpstreamProject(),dep);
- add(backward,dep.getDownstreamProject(),dep);
+ add(backward, dep.getDownstreamProject(), dep);
}
/**
@@ -324,16 +373,22 @@ public class DependencyGraph implements Comparator {
public static final DependencyGraph EMPTY = new DependencyGraph(false);
/**
- * Compare to Projects based on the topological order defined by this Dependency Graph
+ * Compare two Projects based on the topological order defined by this Dependency Graph
*/
public int compare(AbstractProject o1, AbstractProject o2) {
- Set o1sdownstreams = getTransitiveDownstream(o1);
- Set o2sdownstreams = getTransitiveDownstream(o2);
- if (o1sdownstreams.contains(o2)) {
- if (o2sdownstreams.contains(o1)) return 0; else return 1;
- } else {
- if (o2sdownstreams.contains(o1)) return -1; else return 0;
- }
+ return topologicalOrder.compare(o1,o2);
+ }
+
+ /**
+ * Returns all the projects in the topological order of the dependency.
+ *
+ * Intuitively speaking, the first one in the list is the source of the dependency graph,
+ * and the last one is the sink.
+ *
+ * @since 1.521
+ */
+ public List> getTopologicallySorted() {
+ return topologicallySorted;
}
/**
diff --git a/core/src/main/java/hudson/model/Descriptor.java b/core/src/main/java/hudson/model/Descriptor.java
index 414e4124f5..e0cc80c5ea 100644
--- a/core/src/main/java/hudson/model/Descriptor.java
+++ b/core/src/main/java/hudson/model/Descriptor.java
@@ -31,6 +31,7 @@ import hudson.BulkChange;
import hudson.Util;
import hudson.model.listeners.SaveableListener;
import hudson.util.FormApply;
+import hudson.util.FormValidation.CheckMethod;
import hudson.util.ReflectionUtils;
import hudson.util.ReflectionUtils.Parameter;
import hudson.views.ListViewColumn;
@@ -44,7 +45,6 @@ import org.springframework.util.StringUtils;
import org.jvnet.tiger_types.Types;
import org.apache.commons.io.IOUtils;
-import static hudson.Functions.*;
import static hudson.util.QuotedStringTokenizer.*;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import javax.servlet.ServletException;
@@ -127,7 +127,7 @@ public abstract class Descriptor> implements Saveable {
*/
public transient final Class extends T> clazz;
- private transient final Map checkMethods = new ConcurrentHashMap();
+ private transient final Map checkMethods = new ConcurrentHashMap();
/**
* Lazily computed list of properties on {@link #clazz} and on the descriptor itself.
@@ -223,7 +223,22 @@ public abstract class Descriptor> implements Saveable {
*
* @see #getHelpFile(String)
*/
- private transient final Map helpRedirect = new HashMap();
+ private transient final Map helpRedirect = new HashMap();
+
+ private static class HelpRedirect {
+ private final Class extends Describable> owner;
+ private final String fieldNameToRedirectTo;
+
+ private HelpRedirect(Class extends Describable> owner, String fieldNameToRedirectTo) {
+ this.owner = owner;
+ this.fieldNameToRedirectTo = fieldNameToRedirectTo;
+ }
+
+ private String resolve() {
+ // the resolution has to be deferred to avoid ordering issue among descriptor registrations.
+ return Jenkins.getInstance().getDescriptor(owner).getHelpFile(fieldNameToRedirectTo);
+ }
+ }
/**
*
@@ -347,68 +362,27 @@ public abstract class Descriptor> implements Saveable {
}
/**
- * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method,
- * return the form-field validation string. Otherwise null.
- *
- * This method is used to hook up the form validation method to the corresponding HTML input element.
+ * @deprecated since 1.528
+ * Use {@link #getCheckMethod(String)}
*/
public String getCheckUrl(String fieldName) {
- String method = checkMethods.get(fieldName);
- if(method==null) {
- method = calcCheckUrl(fieldName);
- checkMethods.put(fieldName,method);
- }
-
- if (method.equals(NONE)) // == would do, but it makes IDE flag a warning
- return null;
-
- // put this under the right contextual umbrella.
- // a is always non-null because we already have Hudson as the sentinel
- return '\'' + jsStringEscape(getCurrentDescriptorByNameUrl()) + "/'+" + method;
- }
-
- private String calcCheckUrl(String fieldName) {
- String capitalizedFieldName = StringUtils.capitalize(fieldName);
-
- Method method = ReflectionUtils.getPublicMethodNamed(getClass(),"doCheck"+ capitalizedFieldName);
-
- if(method==null)
- return NONE;
-
- return '\'' + getDescriptorUrl() + "/check" + capitalizedFieldName + '\'' + buildParameterList(method, new StringBuilder()).append(".toString()");
+ return getCheckMethod(fieldName).toCheckUrl();
}
/**
- * Builds query parameter line by figuring out what should be submitted
+ * If the field "xyz" of a {@link Describable} has the corresponding "doCheckXyz" method,
+ * return the model of the check method.
+ *
+ * This method is used to hook up the form validation method to the corresponding HTML input element.
*/
- private StringBuilder buildParameterList(Method method, StringBuilder query) {
- for (Parameter p : ReflectionUtils.getParameters(method)) {
- QueryParameter qp = p.annotation(QueryParameter.class);
- if (qp!=null) {
- String name = qp.value();
- if (name.length()==0) name = p.name();
- if (name==null || name.length()==0)
- continue; // unknown parameter name. we'll report the error when the form is submitted.
-
- RelativePath rp = p.annotation(RelativePath.class);
- if (rp!=null)
- name = rp.value()+'/'+name;
-
- if (query.length()==0) query.append("+qs(this)");
-
- if (name.equals("value")) {
- // The special 'value' parameter binds to the the current field
- query.append(".addThis()");
- } else {
- query.append(".nearBy('"+name+"')");
- }
- continue;
- }
-
- Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler");
- if (m!=null) buildParameterList(m,query);
+ public CheckMethod getCheckMethod(String fieldName) {
+ CheckMethod method = checkMethods.get(fieldName);
+ if(method==null) {
+ method = new CheckMethod(this,fieldName);
+ checkMethods.put(fieldName,method);
}
- return query;
+
+ return method;
}
/**
@@ -477,7 +451,7 @@ public abstract class Descriptor> implements Saveable {
}
/**
- * Akin to {@link #getPropertyType(Object,String) but never returns null.
+ * Akin to {@link #getPropertyType(Object,String)} but never returns null.
* @throws AssertionError in case the field cannot be found
* @since 1.492
*/
@@ -657,8 +631,8 @@ public abstract class Descriptor> implements Saveable {
}
public String getHelpFile(Klass> clazz, String fieldName) {
- String v = helpRedirect.get(fieldName);
- if (v!=null) return v;
+ HelpRedirect r = helpRedirect.get(fieldName);
+ if (r!=null) return r.resolve();
for (Klass> c : clazz.getAncestors()) {
String page = "/descriptor/" + getId() + "/help";
@@ -688,8 +662,7 @@ public abstract class Descriptor> implements Saveable {
* @since 1.425
*/
protected void addHelpFileRedirect(String fieldName, Class extends Describable> owner, String fieldNameToRedirectTo) {
- helpRedirect.put(fieldName,
- Jenkins.getInstance().getDescriptor(owner).getHelpFile(fieldNameToRedirectTo));
+ helpRedirect.put(fieldName, new HelpRedirect(owner,fieldNameToRedirectTo));
}
/**
@@ -1005,11 +978,6 @@ public abstract class Descriptor> implements Saveable {
private static final Logger LOGGER = Logger.getLogger(Descriptor.class.getName());
- /**
- * Used in {@link #checkMethods} to indicate that there's no check method.
- */
- private static final String NONE = "\u0000";
-
/**
* Special type indicating that {@link Descriptor} describes itself.
* @see Descriptor#Descriptor(Class)
diff --git a/core/src/main/java/hudson/model/DisplayNameListener.java b/core/src/main/java/hudson/model/DisplayNameListener.java
index 93ddbdea05..ed5cf71495 100644
--- a/core/src/main/java/hudson/model/DisplayNameListener.java
+++ b/core/src/main/java/hudson/model/DisplayNameListener.java
@@ -49,8 +49,8 @@ public class DisplayNameListener extends ItemListener {
* displayed.
*/
public void onCopied(Item src, Item item) {
- // bug 5056825 - Display name field should be cleared when you copy a job.
- if(item instanceof AbstractItem) {
+ // bug 5056825 - Display name field should be cleared when you copy a job within the same folder.
+ if(item instanceof AbstractItem && src.getParent() == item.getParent()) {
AbstractItem dest = (AbstractItem)item;
try {
dest.setDisplayName(null);
diff --git a/core/src/main/java/hudson/model/EnvironmentContributor.java b/core/src/main/java/hudson/model/EnvironmentContributor.java
index fb3b7eea02..37084b10cb 100644
--- a/core/src/main/java/hudson/model/EnvironmentContributor.java
+++ b/core/src/main/java/hudson/model/EnvironmentContributor.java
@@ -73,6 +73,11 @@ public abstract class EnvironmentContributor implements ExtensionPoint {
* This method gets invoked concurrently for multiple {@link Run}s that are being built at the same time,
* so it must be concurrent-safe.
*
+ *
+ * When building environment variables for a build, Jenkins will also invoke
+ * {@link #buildEnvironmentFor(Job, EnvVars, TaskListener)}. This method only needs to add
+ * variables that are scoped to builds.
+ *
* @param r
* Build that's being performed. Never null.
* @param envs
@@ -81,7 +86,29 @@ public abstract class EnvironmentContributor implements ExtensionPoint {
* @param listener
* Connected to the build console. Can be used to report errors. Never null.
*/
- public abstract void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException;
+ public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {}
+
+ /**
+ * Contributes environment variables used for a job.
+ *
+ *
+ * This method can be called repeatedly for the same {@link Job}, thus
+ * the computation of this method needs to be efficient.
+ *
+ *
+ * This method gets invoked concurrently for multiple {@link Job}s,
+ * so it must be concurrent-safe.
+ *
+ * @param j
+ * Job for which some activities are launched.
+ * @param envs
+ * Partially built environment variable map. Implementation of this method is expected to
+ * add additional variables here. Never null.
+ * @param listener
+ * Connected to the build console. Can be used to report errors. Never null.
+ * @since 1.527
+ */
+ public void buildEnvironmentFor(Job j, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {}
/**
* Returns all the registered {@link EnvironmentContributor}s.
diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java
index 4fcb0968fd..bb96893510 100644
--- a/core/src/main/java/hudson/model/Executor.java
+++ b/core/src/main/java/hudson/model/Executor.java
@@ -38,7 +38,8 @@ import hudson.security.ACL;
import jenkins.model.InterruptedBuildAction;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
-import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
+import org.acegisecurity.context.SecurityContext;
+import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
@@ -82,7 +83,7 @@ public class Executor extends Thread implements ModelObject {
*/
private int number;
/**
- * {@link Queue.Executable} being executed right now, or null if the executor is idle.
+ * {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle.
*/
private volatile Queue.Executable executable;
@@ -123,7 +124,7 @@ public class Executor extends Thread implements ModelObject {
*/
public void interrupt(Result result) {
Authentication a = Jenkins.getAuthentication();
- if(a instanceof AnonymousAuthenticationToken || a==ACL.SYSTEM)
+ if (a == ACL.SYSTEM)
interrupt(result, new CauseOfInterruption[0]);
else {
// worth recording who did it
@@ -214,6 +215,7 @@ public class Executor extends Thread implements ModelObject {
task = workUnit.work;
startTime = System.currentTimeMillis();
executable = task.createExecutable();
+ workUnit.setExecutable(executable);
}
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is going to execute "+executable);
@@ -235,10 +237,16 @@ public class Executor extends Thread implements ModelObject {
((Actionable) executable).addAction(action);
}
}
- setName(threadName+" : executing "+executable.toString());
- if (LOGGER.isLoggable(FINE))
- LOGGER.log(FINE, getName()+" is now executing "+executable);
- queue.execute(executable, task);
+
+ final SecurityContext savedContext = ACL.impersonate(workUnit.context.item.authenticate());
+ try {
+ setName(threadName + " : executing " + executable.toString());
+ if (LOGGER.isLoggable(FINE))
+ LOGGER.log(FINE, getName()+" is now executing "+executable);
+ queue.execute(executable, task);
+ } finally {
+ SecurityContextHolder.setContext(savedContext);
+ }
} catch (Throwable e) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
@@ -290,7 +298,7 @@ public class Executor extends Thread implements ModelObject {
}
/**
- * Returns the current {@link Queue.Task} this executor is running.
+ * Returns the current {@link hudson.model.Queue.Task} this executor is running.
*
* @return
* null if the executor is idle.
@@ -567,7 +575,7 @@ public class Executor extends Thread implements ModelObject {
* was compiled against Hudson < 1.383
*
* @deprecated as of 1.388
- * Use {@link Executables#getEstimatedDurationFor(Executable)}
+ * Use {@link Executables#getEstimatedDurationFor(Queue.Executable)}
*/
public static long getEstimatedDurationFor(Executable e) {
return Executables.getEstimatedDurationFor(e);
diff --git a/core/src/main/java/hudson/model/FileParameterDefinition.java b/core/src/main/java/hudson/model/FileParameterDefinition.java
index 5cc3f78b3a..761a179d98 100644
--- a/core/src/main/java/hudson/model/FileParameterDefinition.java
+++ b/core/src/main/java/hudson/model/FileParameterDefinition.java
@@ -86,12 +86,21 @@ public class FileParameterDefinition extends ParameterDefinition {
// the requested file parameter wasn't uploaded
return null;
}
- FileParameterValue p = new FileParameterValue(getName(), src);
+ FileParameterValue p = new FileParameterValue(getName(), src, getFileName(src.getName()));
p.setDescription(getDescription());
p.setLocation(getName());
return p;
}
+ /**
+ * Strip off the path portion if the given path contains it.
+ */
+ private String getFileName(String possiblyPathName) {
+ possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('/')+1);
+ possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('\\')+1);
+ return possiblyPathName;
+ }
+
@Override
public ParameterValue createValue(CLICommand command, String value) throws IOException, InterruptedException {
// capture the file to the server
diff --git a/core/src/main/java/hudson/model/FileParameterValue.java b/core/src/main/java/hudson/model/FileParameterValue.java
index 4abddab70b..e5bfda9881 100644
--- a/core/src/main/java/hudson/model/FileParameterValue.java
+++ b/core/src/main/java/hudson/model/FileParameterValue.java
@@ -66,6 +66,9 @@ public class FileParameterValue extends ParameterValue {
*/
private final String originalFileName;
+ /**
+ * Overrides the location in the build to place this file. Initially set to {@link #getName()}
+ */
private String location;
@DataBoundConstructor
@@ -81,6 +84,7 @@ public class FileParameterValue extends ParameterValue {
super(name);
this.file = file;
this.originalFileName = originalFileName;
+ setLocation(name);
}
// post initialization hook
@@ -129,7 +133,7 @@ public class FileParameterValue extends ParameterValue {
return new BuildWrapper() {
@Override
public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
- if (!StringUtils.isEmpty(file.getName())) {
+ if (!StringUtils.isEmpty(location)) {
listener.getLogger().println("Copying file to "+location);
FilePath locationFilePath = build.getWorkspace().child(location);
locationFilePath.getParent().mkdirs();
diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java
index ab6989ba09..4de1899d00 100644
--- a/core/src/main/java/hudson/model/Fingerprint.java
+++ b/core/src/main/java/hudson/model/Fingerprint.java
@@ -24,11 +24,11 @@
package hudson.model;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableListMultimap;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
@@ -51,6 +51,7 @@ import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.io.IOException;
+import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
@@ -60,7 +61,9 @@ import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -180,6 +183,10 @@ public class Fingerprint implements ModelObject, Saveable {
return false;
}
+
+ @Override public String toString() {
+ return name + " #" + number;
+ }
}
/**
@@ -242,6 +249,13 @@ public class Fingerprint implements ModelObject, Saveable {
return this.end intersection = new ArrayList();
+
+ int lhs=0,rhs=0;
+ while(lhs sub = new ArrayList();
+
+ int lhs=0,rhs=0;
+ while(lhs0) buf.append(',');
@@ -512,7 +701,7 @@ public class Fingerprint implements ModelObject, Saveable {
else
buf.append(r.start).append('-').append(r.end-1);
}
- writer.setValue(buf.toString());
+ return buf.toString();
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
@@ -555,6 +744,8 @@ public class Fingerprint implements ModelObject, Saveable {
}
}
}
+
+ private static final DateConverter DATE_CONVERTER = new DateConverter();
private final Date timestamp;
@@ -573,7 +764,7 @@ public class Fingerprint implements ModelObject, Saveable {
*/
private final Hashtable usages = new Hashtable();
- private PersistedList facets = new PersistedList(this);
+ PersistedList facets = new PersistedList(this);
/**
* Lazily computed immutable {@link FingerprintFacet}s created from {@link TransientFingerprintFacetFactory}.
@@ -581,11 +772,15 @@ public class Fingerprint implements ModelObject, Saveable {
private transient volatile List transientFacets = null;
public Fingerprint(Run build, String fileName, byte[] md5sum) throws IOException {
- this.original = build==null ? null : new BuildPtr(build);
+ this(build==null ? null : new BuildPtr(build), fileName, md5sum);
+ save();
+ }
+
+ Fingerprint(BuildPtr original, String fileName, byte[] md5sum) {
+ this.original = original;
this.md5sum = md5sum;
this.fileName = fileName;
this.timestamp = new Date();
- save();
}
/**
@@ -696,14 +891,19 @@ public class Fingerprint implements ModelObject, Saveable {
}
public synchronized void add(AbstractBuild b) throws IOException {
- add(b.getParent().getFullName(),b.getNumber());
+ add(b.getParent().getFullName(), b.getNumber());
}
/**
* Records that a build of a job has used this file.
*/
public synchronized void add(String jobFullName, int n) throws IOException {
- synchronized(usages) {
+ addWithoutSaving(jobFullName, n);
+ save();
+ }
+
+ void addWithoutSaving(String jobFullName, int n) {
+ synchronized(usages) { // TODO why not synchronized (this) like some, though not all, other accesses?
RangeSet r = usages.get(jobFullName);
if(r==null) {
r = new RangeSet();
@@ -711,7 +911,6 @@ public class Fingerprint implements ModelObject, Saveable {
}
r.add(n);
}
- save();
}
/**
@@ -742,6 +941,65 @@ public class Fingerprint implements ModelObject, Saveable {
return false;
}
+ /**
+ * Trim off references to non-existent builds and jobs, thereby making the fingerprint smaller.
+ *
+ * @return true
+ * if this record was modified.
+ */
+ public synchronized boolean trim() throws IOException {
+ boolean modified = false;
+
+ for (Entry e : new Hashtable(usages).entrySet()) {// copy because we mutate
+ Job j = Jenkins.getInstance().getItemByFullName(e.getKey(),Job.class);
+ if(j==null) {// no such job any more. recycle the record
+ modified = true;
+ usages.remove(e.getKey());
+ continue;
+ }
+
+ Run firstBuild = j.getFirstBuild();
+ if(firstBuild==null) {// no builds. recycle the whole record
+ modified = true;
+ usages.remove(e.getKey());
+ continue;
+ }
+
+ RangeSet cur = e.getValue();
+
+ // builds that are around without the keepLog flag on are normally clustered together (in terms of build #)
+ // so our basic strategy is to discard everything up to the first ephemeral build, except those builds
+ // that are marked as kept
+ RangeSet kept = new RangeSet();
+ Run r = firstBuild;
+ while (r!=null && r.isKeepLog()) {
+ kept.add(r.getNumber());
+ r = r.getNextBuild();
+ }
+
+ if (r==null) {
+ // all the build records are permanently kept ones, so we'll just have to keep 'kept' out of whatever currently in 'cur'
+ modified |= cur.retainAll(kept);
+ } else {
+ // otherwise we are ready to discard [0,r.number) except those marked as 'kept'
+ RangeSet discarding = new RangeSet(new Range(-1,r.getNumber()));
+ discarding.removeAll(kept);
+ modified |= cur.removeAll(discarding);
+ }
+
+ if (cur.isEmpty()) {
+ usages.remove(e.getKey());
+ modified = true;
+ }
+ }
+
+ if (modified)
+ save();
+
+ return modified;
+ }
+
+
/**
* Gets the associated {@link FingerprintFacet}s.
*
@@ -774,21 +1032,13 @@ public class Fingerprint implements ModelObject, Saveable {
@Override
public boolean add(FingerprintFacet e) {
- try {
- facets.add(e);
- return true;
- } catch (IOException x) {
- throw new Error(x);
- }
+ facets.add(e);
+ return true;
}
@Override
public boolean remove(Object o) {
- try {
- return facets.remove((FingerprintFacet)o);
- } catch (IOException x) {
- throw new Error(x);
- }
+ return facets.remove(o);
}
@Override
@@ -838,13 +1088,64 @@ public class Fingerprint implements ModelObject, Saveable {
start = System.currentTimeMillis();
File file = getFingerprintFile(md5sum);
- getConfigFile(file).write(this);
+ save(file);
SaveableListener.fireOnChange(this, getConfigFile(file));
if(logger.isLoggable(Level.FINE))
logger.fine("Saving fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms");
}
+ void save(File file) throws IOException {
+ if (facets.isEmpty()) {
+ file.getParentFile().mkdirs();
+ // JENKINS-16301: fast path for the common case.
+ PrintWriter w = new PrintWriter(file, "UTF-8");
+ try {
+ w.println("");
+ w.println("");
+ w.print(" ");
+ w.print(DATE_CONVERTER.toString(timestamp));
+ w.println("");
+ if (original != null) {
+ w.println(" ");
+ w.print(" ");
+ w.print(original.name);
+ w.println("");
+ w.print(" ");
+ w.print(original.number);
+ w.println("");
+ w.println(" ");
+ }
+ w.print(" ");
+ w.print(Util.toHexString(md5sum));
+ w.println("");
+ w.print(" ");
+ w.print(fileName);
+ w.println("");
+ w.println(" ");
+ for (Map.Entry e : usages.entrySet()) {
+ w.println(" ");
+ w.print(" ");
+ w.print(e.getKey());
+ w.println("");
+ w.print(" ");
+ w.print(RangeSet.ConverterImpl.serialize(e.getValue()));
+ w.println("");
+ w.println(" ");
+ }
+ w.println(" ");
+ w.println(" ");
+ w.print("");
+ w.flush();
+ } finally {
+ w.close();
+ }
+ } else {
+ // Slower fallback that can persist facets.
+ getConfigFile(file).write(this);
+ }
+ }
+
/**
* Update references to a renamed job in the fingerprint
*/
@@ -932,6 +1233,10 @@ public class Fingerprint implements ModelObject, Saveable {
}
}
+ @Override public String toString() {
+ return "Fingerprint[original=" + original + ",hash=" + getHashString() + ",fileName=" + fileName + ",timestamp=" + DATE_CONVERTER.toString(timestamp) + ",usages=" + new TreeMap(usages) + ",facets=" + facets + "]";
+ }
+
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("fingerprint",Fingerprint.class);
diff --git a/core/src/main/java/hudson/model/FingerprintCleanupThread.java b/core/src/main/java/hudson/model/FingerprintCleanupThread.java
index e70037ab57..1b0dc37278 100644
--- a/core/src/main/java/hudson/model/FingerprintCleanupThread.java
+++ b/core/src/main/java/hudson/model/FingerprintCleanupThread.java
@@ -61,7 +61,7 @@ public final class FingerprintCleanupThread extends AsyncPeriodicWork {
return Jenkins.getInstance().getExtensionList(AsyncPeriodicWork.class).get(FingerprintCleanupThread.class);
}
- protected void execute(TaskListener listener) {
+ public void execute(TaskListener listener) {
int numFiles = 0;
File root = new File(Jenkins.getInstance().getRootDir(),"fingerprints");
@@ -103,11 +103,16 @@ public final class FingerprintCleanupThread extends AsyncPeriodicWork {
if(!fp.isAlive()) {
fingerprintFile.delete();
return true;
+ } else {
+ // get the fingerprint in the official map so have the changes visible to Jenkins
+ // otherwise the mutation made in FingerprintMap can override our trimming.
+ fp = Jenkins.getInstance()._getFingerprint(fp.getHashString());
+ return fp.trim();
}
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to process "+fingerprintFile, e);
+ return false;
}
- return false;
}
private static final FileFilter LENGTH2DIR_FILTER = new FileFilter() {
diff --git a/core/src/main/java/hudson/model/FreeStyleProject.java b/core/src/main/java/hudson/model/FreeStyleProject.java
index 8eacc0ae75..11ce99a30b 100644
--- a/core/src/main/java/hudson/model/FreeStyleProject.java
+++ b/core/src/main/java/hudson/model/FreeStyleProject.java
@@ -25,6 +25,8 @@ package hudson.model;
import hudson.Extension;
import jenkins.model.Jenkins;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Free-style software project.
@@ -50,9 +52,14 @@ public class FreeStyleProject extends Project i
}
public DescriptorImpl getDescriptor() {
- return DESCRIPTOR;
+ return (DescriptorImpl)Jenkins.getInstance().getDescriptorOrDie(getClass());
}
+ /**
+ * Descriptor is instantiated as a field purely for backward compatibility.
+ * Do not do this in your code. Put @Extension on your DescriptorImpl class instead.
+ */
+ @Restricted(NoExternalUse.class)
@Extension(ordinal=1000)
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
diff --git a/core/src/main/java/hudson/model/ItemGroupMixIn.java b/core/src/main/java/hudson/model/ItemGroupMixIn.java
index 28f2246854..2b23b27c16 100644
--- a/core/src/main/java/hudson/model/ItemGroupMixIn.java
+++ b/core/src/main/java/hudson/model/ItemGroupMixIn.java
@@ -189,9 +189,6 @@ public abstract class ItemGroupMixIn {
/**
* Copies an existing {@link TopLevelItem} to a new name.
- *
- * The caller is responsible for calling {@link ItemListener#fireOnCopied(Item, Item)}. This method
- * cannot do that because it doesn't know how to make the newly added item reachable from the parent.
*/
@SuppressWarnings({"unchecked"})
public synchronized T copy(T src, String name) throws IOException {
@@ -213,7 +210,7 @@ public abstract class ItemGroupMixIn {
add(result);
ItemListener.fireOnCopied(src,result);
- Hudson.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
return result;
}
@@ -239,7 +236,7 @@ public abstract class ItemGroupMixIn {
add(result);
ItemListener.fireOnCreated(result);
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
return result;
} catch (IOException e) {
@@ -270,7 +267,7 @@ public abstract class ItemGroupMixIn {
}
item.save();
add(item);
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
if (notify)
ItemListener.fireOnCreated(item);
diff --git a/core/src/main/java/hudson/model/Items.java b/core/src/main/java/hudson/model/Items.java
index 61827723b0..746a5aa4fb 100644
--- a/core/src/main/java/hudson/model/Items.java
+++ b/core/src/main/java/hudson/model/Items.java
@@ -166,7 +166,7 @@ public class Items {
while(tokens.hasMoreTokens()) {
String relativeName = tokens.nextToken().trim();
String canonicalName = getCanonicalName(context, relativeName);
- if (canonicalName.startsWith(oldFullName)) {
+ if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName+'/')) {
String newCanonicalName = newFullName + canonicalName.substring(oldFullName.length());
// relative name points to the renamed item, let's compute the new relative name
newValue.add( computeRelativeNameAfterRenaming(canonicalName, newCanonicalName, relativeName) );
diff --git a/core/src/main/java/hudson/model/JDK.java b/core/src/main/java/hudson/model/JDK.java
index 73ca0c9db1..5841620aee 100644
--- a/core/src/main/java/hudson/model/JDK.java
+++ b/core/src/main/java/hudson/model/JDK.java
@@ -105,9 +105,13 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En
* @deprecated as of 1.460. Use {@link #buildEnvVars(EnvVars)}
*/
public void buildEnvVars(Map env) {
+ String home = getHome();
+ if (home == null) {
+ return;
+ }
// see EnvVars javadoc for why this adds PATH.
- env.put("PATH+JDK",getHome()+"/bin");
- env.put("JAVA_HOME",getHome());
+ env.put("PATH+JDK",home+"/bin");
+ env.put("JAVA_HOME", home);
}
/**
@@ -149,7 +153,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En
public static class DescriptorImpl extends ToolDescriptor {
public String getDisplayName() {
- return "JDK"; // XXX I18N
+ return "JDK"; // TODO I18N
}
public @Override JDK[] getInstallations() {
diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java
index 8b5f2906f6..c444c2d2a1 100644
--- a/core/src/main/java/hudson/model/Job.java
+++ b/core/src/main/java/hudson/model/Job.java
@@ -26,7 +26,7 @@ package hudson.model;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
-import hudson.BulkChange;
+
import hudson.EnvVars;
import hudson.Extension;
import hudson.ExtensionPoint;
@@ -64,11 +64,11 @@ import hudson.widgets.Widget;
import jenkins.model.BuildDiscarder;
import jenkins.model.Jenkins;
import jenkins.model.ProjectNamingStrategy;
-import jenkins.scm.SCMCheckoutStrategy;
import jenkins.security.HexStringConfidentialKey;
import jenkins.util.io.OnMaster;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
+
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
@@ -89,6 +89,7 @@ import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
+
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
@@ -127,6 +128,13 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run getEstimatedDurationCandidates() {
+ List candidates = new ArrayList(3);
+ RunT lastSuccessful = (RunT) Permalink.LAST_SUCCESSFUL_BUILD.resolve(this);
+ int lastSuccessfulNumber = -1;
+ if (lastSuccessful != null) {
+ candidates.add(lastSuccessful);
+ lastSuccessfulNumber = lastSuccessful.getNumber();
+ }
+
+ int i = 0;
+ RunT r = (RunT) Permalink.LAST_BUILD.resolve(this);
+ List fallbackCandidates = new ArrayList(3);
+ while (r != null && candidates.size() < 3 && i < 6) {
+ if (!r.isBuilding() && r.getResult() != null && r.getNumber() != lastSuccessfulNumber) {
+ Result result = r.getResult();
+ if (result.isBetterOrEqualTo(Result.UNSTABLE)) {
+ candidates.add(r);
+ } else if (result.isCompleteBuild()) {
+ fallbackCandidates.add(r);
+ }
+ }
+ i++;
+ r = r.getPreviousBuild();
+ }
+
+ while (candidates.size() < 3) {
+ if (fallbackCandidates.isEmpty())
+ break;
+ RunT run = fallbackCandidates.remove(0);
+ candidates.add(run);
+ }
+
+ return candidates;
+ }
+
public long getEstimatedDuration() {
- List builds = getLastBuildsOverThreshold(3, Result.UNSTABLE);
+ List builds = getEstimatedDurationCandidates();
if(builds.isEmpty()) return -1;
@@ -933,7 +993,7 @@ public abstract class Job, RunT extends Run, Mod
public List getTiedJobs() {
List r = new ArrayList();
for (AbstractProject,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
- if(this.equals(p.getAssignedLabel()))
+ if(p instanceof TopLevelItem && this.equals(p.getAssignedLabel()))
r.add(p);
}
return r;
}
+ /**
+ * Returns a count of projects that are tied on this node. In a system without security this should be the same
+ * as {@code getTiedJobs().size()} but significantly faster as it involves fewer temporary objects and avoids
+ * sorting the intermediary list. In a system with security, this will likely return a higher value as it counts
+ * all jobs (mostly) irrespective of access.
+ * @return a count of projects that are tied on this node.
+ */
+ public int getTiedJobCount() {
+ // denormalize for performance
+ // we don't need to respect security as much when returning a simple count
+ SecurityContext context = ACL.impersonate(ACL.SYSTEM);
+ try {
+ int result = 0;
+ // top level gives the map without checking security of items in the map
+ // therefore best performance
+ for (TopLevelItem topLevelItem : Jenkins.getInstance().getItemMap().values()) {
+ if (topLevelItem instanceof AbstractProject) {
+ final AbstractProject project = (AbstractProject) topLevelItem;
+ if (this.equals(project.getAssignedLabel())) {
+ result++;
+ }
+ }
+ if (topLevelItem instanceof ItemGroup) {
+ Stack q = new Stack();
+ q.push((ItemGroup) topLevelItem);
+
+ while (!q.isEmpty()) {
+ ItemGroup> parent = q.pop();
+ // we run the risk of permissions checks in ItemGroup#getItems()
+ // not much we can do here though
+ for (Item i : parent.getItems()) {
+ if (i instanceof AbstractProject) {
+ final AbstractProject project = (AbstractProject) i;
+ if (this.equals(project.getAssignedLabel())) {
+ result++;
+ }
+ }
+ if (i instanceof ItemGroup) {
+ q.push((ItemGroup) i);
+ }
+ }
+ }
+ }
+ }
+ return result;
+ } finally {
+ SecurityContextHolder.setContext(context);
+ }
+ }
+
public boolean contains(Node node) {
return getNodes().contains(node);
}
diff --git a/core/src/main/java/hudson/model/ListView.java b/core/src/main/java/hudson/model/ListView.java
index 7e1a3eb56f..74616ebf80 100644
--- a/core/src/main/java/hudson/model/ListView.java
+++ b/core/src/main/java/hudson/model/ListView.java
@@ -26,6 +26,7 @@ package hudson.model;
import hudson.Extension;
import hudson.Util;
+import hudson.diagnosis.OldDataMonitor;
import hudson.model.Descriptor.FormException;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.DescribableList;
@@ -36,6 +37,7 @@ import hudson.views.ViewJobFilter;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SortedSet;
@@ -106,8 +108,14 @@ public class ListView extends View implements Saveable {
}
private Object readResolve() {
- if(includeRegex!=null)
- includePattern = Pattern.compile(includeRegex);
+ if(includeRegex!=null) {
+ try {
+ includePattern = Pattern.compile(includeRegex);
+ } catch (PatternSyntaxException x) {
+ includeRegex = null;
+ OldDataMonitor.report(this, Collections.singleton(x));
+ }
+ }
if (jobNames == null) {
jobNames = new TreeSet(CaseInsensitiveComparator.INSTANCE);
}
@@ -189,15 +197,18 @@ public class ListView extends View implements Saveable {
includeItems(parent, parent, names);
}
- private void includeItems(ItemGroup extends TopLevelItem> root, ItemGroup extends TopLevelItem> parent, SortedSet names) {
+ private void includeItems(ItemGroup extends TopLevelItem> root, ItemGroup> parent, SortedSet names) {
if (includePattern != null) {
for (Item item : parent.getItems()) {
if (recurse && item instanceof ItemGroup) {
- includeItems(root, (ItemGroup extends TopLevelItem>)item, names);
+ ItemGroup> ig = (ItemGroup>) item;
+ includeItems(root, ig, names);
}
- String itemName = item.getRelativeNameFrom(root);
- if (includePattern.matcher(itemName).matches()) {
- names.add(itemName);
+ if (item instanceof TopLevelItem) {
+ String itemName = item.getRelativeNameFrom(root);
+ if (includePattern.matcher(itemName).matches()) {
+ names.add(itemName);
+ }
}
}
}
@@ -229,6 +240,13 @@ public class ListView extends View implements Saveable {
public boolean isRecurse() {
return recurse;
}
+
+ /*
+ * For testing purposes
+ */
+ void setRecurse(boolean recurse) {
+ this.recurse = recurse;
+ }
/**
* Filter by enabled/disabled status of jobs.
@@ -311,16 +329,7 @@ public class ListView extends View implements Saveable {
}
}
- if (req.getParameter("useincluderegex") != null) {
- includeRegex = Util.nullify(req.getParameter("includeRegex"));
- if (includeRegex == null)
- includePattern = null;
- else
- includePattern = Pattern.compile(includeRegex);
- } else {
- includeRegex = null;
- includePattern = null;
- }
+ setIncludeRegex(req.getParameter("useincluderegex") != null ? req.getParameter("includeRegex") : null);
if (columns == null) {
columns = new DescribableList>(this);
@@ -335,6 +344,14 @@ public class ListView extends View implements Saveable {
String filter = Util.fixEmpty(req.getParameter("statusFilter"));
statusFilter = filter != null ? "1".equals(filter) : null;
}
+
+ public void setIncludeRegex(String includeRegex) {
+ this.includeRegex = Util.nullify(includeRegex);
+ if (this.includeRegex == null)
+ this.includePattern = null;
+ else
+ this.includePattern = Pattern.compile(includeRegex);
+ }
@Extension
public static class DescriptorImpl extends ViewDescriptor {
diff --git a/core/src/main/java/hudson/model/LoadStatistics.java b/core/src/main/java/hudson/model/LoadStatistics.java
index 40185eb042..edf8cf4593 100644
--- a/core/src/main/java/hudson/model/LoadStatistics.java
+++ b/core/src/main/java/hudson/model/LoadStatistics.java
@@ -77,7 +77,7 @@ public abstract class LoadStatistics {
public final MultiStageTimeSeries totalExecutors;
/**
- * Number of {@link Queue.BuildableItem}s that can run on any node in this node set but blocked.
+ * Number of {@link hudson.model.Queue.BuildableItem}s that can run on any node in this node set but blocked.
*/
@Exported
public final MultiStageTimeSeries queueLength;
diff --git a/core/src/main/java/hudson/model/ManagementLink.java b/core/src/main/java/hudson/model/ManagementLink.java
index ecd09e3034..a92e2a581f 100644
--- a/core/src/main/java/hudson/model/ManagementLink.java
+++ b/core/src/main/java/hudson/model/ManagementLink.java
@@ -107,7 +107,7 @@ public abstract class ManagementLink implements ExtensionPoint, Action {
}
/**
- * @return permission required for user to access this management link, in addition to {@link Jenkins.ADMINISTER}
+ * @return permission required for user to access this management link, in addition to {@link Jenkins#ADMINISTER}
*/
public Permission getRequiredPermission() {
return null;
diff --git a/core/src/main/java/hudson/model/Node.java b/core/src/main/java/hudson/model/Node.java
index fa34001043..f542b78411 100644
--- a/core/src/main/java/hudson/model/Node.java
+++ b/core/src/main/java/hudson/model/Node.java
@@ -35,6 +35,7 @@ import hudson.model.Queue.Task;
import hudson.model.labels.LabelAtom;
import hudson.model.queue.CauseOfBlockage;
import hudson.node_monitors.NodeMonitor;
+import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.security.ACL;
import hudson.security.AccessControlled;
@@ -58,10 +59,13 @@ import java.util.Set;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
import jenkins.util.io.OnMaster;
import net.sf.json.JSONObject;
+import org.acegisecurity.Authentication;
+import org.jvnet.localizer.Localizable;
import org.kohsuke.stapler.BindInterceptor;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
@@ -69,14 +73,19 @@ import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
/**
- * Base type of Hudson slaves (although in practice, you probably extend {@link Slave} to define a new slave type.)
+ * Base type of Jenkins slaves (although in practice, you probably extend {@link Slave} to define a new slave type.)
*
*
* As a special case, {@link Jenkins} extends from here.
*
+ *
+ * Nodes are persisted objects that capture user configurations, and instances get thrown away and recreated whenever
+ * the configuration changes. Running state of nodes are captured by {@link Computer}s.
+ *
* @author Kohsuke Kawaguchi
* @see NodeMonitor
* @see NodeDescriptor
+ * @see Computer
*/
@ExportedBean
public abstract class Node extends AbstractModelObject implements ReconfigurableDescribable, ExtensionPoint, AccessControlled, OnMaster {
@@ -222,7 +231,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
public TagCloud getLabelCloud() {
return new TagCloud(getAssignedLabels(),new WeightFunction() {
public float weight(LabelAtom item) {
- return item.getTiedJobs().size();
+ return item.getTiedJobCount();
}
});
}
@@ -322,8 +331,23 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
if(l!=null && !l.contains(this))
return CauseOfBlockage.fromMessage(Messages._Node_LabelMissing(getNodeName(),l)); // the task needs to be executed on label that this node doesn't have.
- if(l==null && getMode()== Mode.EXCLUSIVE)
- return CauseOfBlockage.fromMessage(Messages._Node_BecauseNodeIsReserved(getNodeName())); // this node is reserved for tasks that are tied to it
+ if(l==null && getMode()== Mode.EXCLUSIVE) {
+ // flyweight tasks need to get executed somewhere, if every node
+ if (!(item.task instanceof Queue.FlyweightTask && (
+ this instanceof Jenkins
+ || Jenkins.getInstance().getNumExecutors() < 1
+ || Jenkins.getInstance().getMode() == Mode.EXCLUSIVE)
+ )) {
+ return CauseOfBlockage.fromMessage(Messages._Node_BecauseNodeIsReserved(getNodeName())); // this node is reserved for tasks that are tied to it
+ }
+ }
+
+ Authentication identity = item.authenticate();
+ if (!getACL().hasPermission(identity,Computer.BUILD)) {
+ // doesn't have a permission
+ // TODO: does it make more sense to define a separate permission?
+ return CauseOfBlockage.fromMessage(Messages._Node_LackingBuildPermission(identity.getName(),getNodeName()));
+ }
// Check each NodeProperty to see whether they object to this node
// taking the task
@@ -379,7 +403,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
/**
* Gets the {@link NodeProperty} instances configured for this {@link Node}.
*/
- public abstract DescribableList, NodePropertyDescriptor> getNodeProperties();
+ public abstract @Nonnull DescribableList, NodePropertyDescriptor> getNodeProperties();
// used in the Jelly script to expose descriptors
public List getNodePropertyDescriptors() {
@@ -436,26 +460,41 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* @throws InterruptedException
* if the operation is aborted.
*/
- public abstract ClockDifference getClockDifference() throws IOException, InterruptedException;
+ public ClockDifference getClockDifference() throws IOException, InterruptedException {
+ VirtualChannel channel = getChannel();
+ if(channel==null)
+ throw new IOException(getNodeName()+" is offline");
+
+ return channel.call(getClockDifferenceCallable());
+ }
+
+ /**
+ * Returns a {@link Callable} that when run on the channel, estimates the clock difference.
+ *
+ * @return
+ * always non-null.
+ * @since 1.522
+ */
+ public abstract Callable getClockDifferenceCallable();
/**
* Constants that control how Hudson allocates jobs to slaves.
*/
public enum Mode {
- NORMAL(Messages.Node_Mode_NORMAL()),
- EXCLUSIVE(Messages.Node_Mode_EXCLUSIVE());
+ NORMAL(Messages._Node_Mode_NORMAL()),
+ EXCLUSIVE(Messages._Node_Mode_EXCLUSIVE());
- private final String description;
+ private final Localizable description;
public String getDescription() {
- return description;
+ return description.toString();
}
public String getName() {
return name();
}
- Mode(String description) {
+ Mode(Localizable description) {
this.description = description;
}
diff --git a/core/src/main/java/hudson/model/OverallLoadStatistics.java b/core/src/main/java/hudson/model/OverallLoadStatistics.java
index f576ad14f0..e07593b3cf 100644
--- a/core/src/main/java/hudson/model/OverallLoadStatistics.java
+++ b/core/src/main/java/hudson/model/OverallLoadStatistics.java
@@ -36,11 +36,11 @@ import org.kohsuke.stapler.export.Exported;
*
* @author Kohsuke Kawaguchi
* @see Jenkins#overallLoad
- * @see UnlabeldLoadStatistics
+ * @see jenkins.model.UnlabeledLoadStatistics
*/
public class OverallLoadStatistics extends LoadStatistics {
/**
- * Number of total {@link Queue.BuildableItem}s that represents blocked builds.
+ * Number of total {@link hudson.model.Queue.BuildableItem}s that represents blocked builds.
*
* @deprecated as of 1.467
* Use {@link #queueLength}. Left as an alias here for backward compatibility.
diff --git a/core/src/main/java/hudson/model/ParameterDefinition.java b/core/src/main/java/hudson/model/ParameterDefinition.java
index 7b71927619..32c89fb00a 100644
--- a/core/src/main/java/hudson/model/ParameterDefinition.java
+++ b/core/src/main/java/hudson/model/ParameterDefinition.java
@@ -32,6 +32,7 @@ import hudson.util.DescriptorList;
import java.io.Serializable;
import java.io.IOException;
+import java.util.logging.Logger;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
@@ -137,6 +138,19 @@ public abstract class ParameterDefinition implements
return description;
}
+ /**
+ * return parameter description, applying the configured MarkupFormatter for jenkins instance.
+ * @since 1.521
+ */
+ public String getFormattedDescription() {
+ try {
+ return Jenkins.getInstance().getMarkupFormatter().translate(description);
+ } catch (IOException e) {
+ LOGGER.warning("failed to translate description using configured markup formatter");
+ return "";
+ }
+ }
+
/**
* {@inheritDoc}
*/
@@ -241,4 +255,6 @@ public abstract class ParameterDefinition implements
return "Parameter";
}
}
+
+ private static final Logger LOGGER = Logger.getLogger(ParameterDefinition.class.getName());
}
diff --git a/core/src/main/java/hudson/model/ParametersAction.java b/core/src/main/java/hudson/model/ParametersAction.java
index 132e1014ea..c5cab54dea 100644
--- a/core/src/main/java/hudson/model/ParametersAction.java
+++ b/core/src/main/java/hudson/model/ParametersAction.java
@@ -84,7 +84,7 @@ public class ParametersAction implements Action, Iterable, Queue
}
/**
- * Performs a variable subsitution to the given text and return it.
+ * Performs a variable substitution to the given text and return it.
*/
public String substitute(AbstractBuild,?> build, String text) {
return Util.replaceMacro(text,createVariableResolver(build));
diff --git a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
index 0cc266ce43..1081078ec9 100644
--- a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
+++ b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
@@ -34,6 +34,8 @@ import java.util.AbstractList;
import javax.servlet.ServletException;
+import hudson.Util;
+import hudson.model.Queue.WaitingItem;
import jenkins.model.Jenkins;
import jenkins.util.TimeDuration;
import net.sf.json.JSONArray;
@@ -46,8 +48,11 @@ import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import hudson.Extension;
+import javax.annotation.CheckForNull;
import org.kohsuke.stapler.export.Flavor;
+import static javax.servlet.http.HttpServletResponse.SC_CREATED;
+
/**
* Keeps a list of the parameters defined for a project.
*
@@ -102,6 +107,8 @@ public class ParametersDefinitionProperty extends JobProperty) owner;
}
+ /** @deprecated use {@link #_doBuild(StaplerRequest, StaplerResponse, TimeDuration)} */
+ @Deprecated
public void _doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
_doBuild(req,rsp,TimeDuration.fromString(req.getParameter("delay")));
}
@@ -132,18 +139,25 @@ public class ParametersDefinitionProperty extends JobProperty values = new ArrayList();
for (ParameterDefinition d: parameterDefinitions) {
ParameterValue value = d.createValue(req);
diff --git a/core/src/main/java/hudson/model/Project.java b/core/src/main/java/hudson/model/Project.java
index b27fe9096e..13127ccd2e 100644
--- a/core/src/main/java/hudson/model/Project.java
+++ b/core/src/main/java/hudson/model/Project.java
@@ -47,6 +47,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* Buildable software project.
@@ -59,17 +60,23 @@ public abstract class Project,B extends Build
>
/**
* List of active {@link Builder}s configured for this project.
*/
- private DescribableList> builders;
+ private volatile DescribableList> builders;
+ private static final AtomicReferenceFieldUpdater buildersSetter
+ = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"builders");
/**
* List of active {@link Publisher}s configured for this project.
*/
- private DescribableList> publishers;
+ private volatile DescribableList> publishers;
+ private static final AtomicReferenceFieldUpdater publishersSetter
+ = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"publishers");
/**
* List of active {@link BuildWrapper}s configured for this project.
*/
- private DescribableList> buildWrappers;
+ private volatile DescribableList> buildWrappers;
+ private static final AtomicReferenceFieldUpdater buildWrappersSetter
+ = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"buildWrappers");
/**
* Creates a new project.
@@ -103,16 +110,16 @@ public abstract class Project,B extends Build
>
return getPublishersList().toMap();
}
- public synchronized DescribableList> getBuildersList() {
+ public DescribableList> getBuildersList() {
if (builders == null) {
- builders = new DescribableList>(this);
+ buildersSetter.compareAndSet(this,null,new DescribableList>(this));
}
return builders;
}
- public synchronized DescribableList> getPublishersList() {
+ public DescribableList> getPublishersList() {
if (publishers == null) {
- publishers = new DescribableList>(this);
+ publishersSetter.compareAndSet(this,null,new DescribableList>(this));
}
return publishers;
}
@@ -121,9 +128,9 @@ public abstract class Project