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;
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 b553723bf3..a6697760a8 100644
--- a/core/src/main/java/hudson/model/AbstractBuild.java
+++ b/core/src/main/java/hudson/model/AbstractBuild.java
@@ -217,7 +217,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) {
diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java
index 16cf19b221..518234e652 100644
--- a/core/src/main/java/hudson/model/AbstractItem.java
+++ b/core/src/main/java/hudson/model/AbstractItem.java
@@ -403,7 +403,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
public String getShortUrl() {
String prefix = getParent().getUrlChildPrefix();
String subdir = Util.rawEncode(getName());
- return prefix.equals(".") ? subdir : prefix+'/'+subdir+'/';
+ return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/';
}
public String getSearchUrl() {
@@ -513,7 +513,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
// ignore
}
- Jenkins.getInstance().rebuildDependencyGraph();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
}
/**
@@ -592,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 14571c3503..eb321f4676 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,6 +92,7 @@ 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.kohsuke.accmod.Restricted;
@@ -109,6 +110,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;
@@ -128,6 +130,7 @@ 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;
@@ -237,7 +240,9 @@ public abstract class AbstractProject
,R extends A
/**
* List of all {@link Trigger}s for this project.
*/
- protected List> triggers = new Vector>();
+ 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 +266,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;
@@ -306,6 +311,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 +330,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;
}
@@ -770,7 +777,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 +860,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 +922,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;
}
@@ -1174,6 +1180,12 @@ public abstract class AbstractProject
,R extends A
return this;
}
+ @Nonnull
+ public Authentication getDefaultAuthentication() {
+ // backward compatible behaviour.
+ return ACL.SYSTEM;
+ }
+
/**
* {@inheritDoc}
*
@@ -1364,7 +1376,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) {
@@ -1634,8 +1652,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,13 +1816,19 @@ public abstract class AbstractProject,R extends A
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
- WaitingItem item = Jenkins.getInstance().getQueue().schedule(this, (int) delay.getTime(), getBuildCause(req));
- if (item!=null) {
- rsp.sendRedirect(SC_CREATED,req.getContextPath()+'/'+item.getUrl());
+ 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")));
+ }
+
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
@@ -1823,7 +1847,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 {
@@ -1856,6 +1880,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.
*/
@@ -1950,8 +1980,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/Computer.java b/core/src/main/java/hudson/model/Computer.java
index 493098782f..c1756bb635 100644
--- a/core/src/main/java/hudson/model/Computer.java
+++ b/core/src/main/java/hudson/model/Computer.java
@@ -1357,6 +1357,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/ComputerSet.java b/core/src/main/java/hudson/model/ComputerSet.java
index dc1436d3f3..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);
}
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/Executor.java b/core/src/main/java/hudson/model/Executor.java
index b99b6fbb02..2aa98d0219 100644
--- a/core/src/main/java/hudson/model/Executor.java
+++ b/core/src/main/java/hudson/model/Executor.java
@@ -38,6 +38,8 @@ import hudson.security.ACL;
import jenkins.model.InterruptedBuildAction;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
+import org.acegisecurity.context.SecurityContext;
+import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
@@ -236,10 +238,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,
diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java
index c1b40239aa..4de1899d00 100644
--- a/core/src/main/java/hudson/model/Fingerprint.java
+++ b/core/src/main/java/hudson/model/Fingerprint.java
@@ -249,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(lhs 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.
*
@@ -794,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
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/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/Job.java b/core/src/main/java/hudson/model/Job.java
index 9b351e35f8..523e3de856 100644
--- a/core/src/main/java/hudson/model/Job.java
+++ b/core/src/main/java/hudson/model/Job.java
@@ -125,6 +125,13 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, 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;
diff --git a/core/src/main/java/hudson/model/Node.java b/core/src/main/java/hudson/model/Node.java
index fe0a9dbcc8..a89fef0506 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;
@@ -62,6 +63,7 @@ import javax.annotation.CheckForNull;
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;
@@ -323,8 +325,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
@@ -437,7 +454,22 @@ 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.
+ * @sine 1.522
+ */
+ public abstract Callable getClockDifferenceCallable();
/**
* Constants that control how Hudson allocates jobs to slaves.
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/ParametersDefinitionProperty.java b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
index e25116bb6f..1081078ec9 100644
--- a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
+++ b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java
@@ -34,6 +34,7 @@ import java.util.AbstractList;
import javax.servlet.ServletException;
+import hudson.Util;
import hudson.model.Queue.WaitingItem;
import jenkins.model.Jenkins;
import jenkins.util.TimeDuration;
@@ -47,6 +48,7 @@ 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;
@@ -105,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")));
}
@@ -137,18 +141,23 @@ 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,B extends Build
>
return getBuildWrappersList().toMap();
}
- public synchronized DescribableList> getBuildWrappersList() {
+ public DescribableList> getBuildWrappersList() {
if (buildWrappers == null) {
- buildWrappers = new DescribableList>(this);
+ buildWrappersSetter.compareAndSet(this,null,new DescribableList>(this));
}
return buildWrappers;
}
@@ -211,7 +218,7 @@ public abstract class Project,B extends Build
>
r.addAll(step.getProjectActions(this));
for (BuildWrapper step : getBuildWrappers().values())
r.addAll(step.getProjectActions(this));
- for (Trigger trigger : getTriggers().values())
+ for (Trigger trigger : triggers())
r.addAll(trigger.getProjectActions());
return r;
diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java
index a162856f59..cc491b2199 100644
--- a/core/src/main/java/hudson/model/Queue.java
+++ b/core/src/main/java/hudson/model/Queue.java
@@ -44,7 +44,10 @@ import hudson.cli.declarative.CLIResolver;
import hudson.model.labels.LabelAssignmentAction;
import hudson.model.queue.AbstractQueueTask;
import hudson.model.queue.Executables;
+import hudson.model.queue.QueueListener;
import hudson.model.queue.QueueTaskFuture;
+import hudson.model.queue.ScheduleResult;
+import hudson.model.queue.ScheduleResult.Created;
import hudson.model.queue.SubTask;
import hudson.model.queue.FutureImpl;
import hudson.model.queue.MappingWorksheet;
@@ -62,6 +65,7 @@ import hudson.model.queue.CauseOfBlockage.BecauseNodeIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseLabelIsOffline;
import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy;
import hudson.model.queue.WorkUnitContext;
+import hudson.security.ACL;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.util.OneShotEvent;
@@ -99,10 +103,14 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
+import jenkins.security.QueueItemAuthenticator;
+import jenkins.security.QueueItemAuthenticatorConfiguration;
import org.acegisecurity.AccessDeniedException;
+import org.acegisecurity.Authentication;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.export.Exported;
@@ -136,6 +144,8 @@ import org.kohsuke.stapler.interceptor.RequirePOST;
* cancels a job in the queue.) See the corresponding field for their exact meanings.
*
* @author Kohsuke Kawaguchi
+ * @see QueueListener
+ * @see QueueTaskDispatcher
*/
@ExportedBean
public class Queue extends ResourceController implements Saveable {
@@ -360,11 +370,11 @@ public class Queue extends ResourceController implements Saveable {
maxId = Math.max(maxId, item.id);
if (item instanceof WaitingItem) {
- waitingList.add((WaitingItem) item);
+ item.enter(this);
} else if (item instanceof BlockedItem) {
- blockedProjects.put(item.task, (BlockedItem) item);
+ item.enter(this);
} else if (item instanceof BuildableItem) {
- buildables.add((BuildableItem) item);
+ item.enter(this);
} else {
throw new IllegalStateException("Unknown item type! " + item);
}
@@ -416,10 +426,10 @@ public class Queue extends ResourceController implements Saveable {
@CLIMethod(name="clear-queue")
public synchronized void clear() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
- for (WaitingItem i : waitingList)
- i.onCancelled();
- waitingList.clear();
+ for (WaitingItem i : new ArrayList(waitingList)) // copy the list as we'll modify it in the loop
+ i.cancel(this);
blockedProjects.cancelAll();
+ pendings.cancelAll();
buildables.cancelAll();
scheduleMaintenance();
}
@@ -465,6 +475,14 @@ public class Queue extends ResourceController implements Saveable {
return schedule(p, quietPeriod)!=null;
}
+ /**
+ * @deprecated as of 1.521
+ * Use {@link #schedule2(Task, int, List)}
+ */
+ public synchronized WaitingItem schedule(Task p, int quietPeriod, List actions) {
+ return schedule2(p, quietPeriod, actions).getCreateItem();
+ }
+
/**
* Schedules an execution of a task.
*
@@ -475,14 +493,18 @@ public class Queue extends ResourceController implements Saveable {
* For the convenience of the caller, this list can contain null, and those will be silently ignored.
* @since 1.311
* @return
- * null if this task is already in the queue and therefore the add operation was no-op.
- * Otherwise indicates the {@link WaitingItem} object added, although the nature of the queue
+ * {@link ScheduleResult.Refused} if Jenkins refused to add this task into the queue (for example because the system
+ * is about to shutdown.) Otherwise the task is either merged into existing items in the queue
+ * (in which case you get {@link ScheduleResult.Existing} instance back), or a new item
+ * gets created in the queue (in which case you get {@link Created}.
+ *
+ * Note the nature of the queue
* is that such {@link Item} only captures the state of the item at a particular moment,
* and by the time you inspect the object, some of its information can be already stale.
*
- * That said, one can still look at {@link WaitingItem#future}, {@link WaitingItem#id}, etc.
+ * That said, one can still look at {@link Item#future}, {@link Item#id}, etc.
*/
- public synchronized WaitingItem schedule(Task p, int quietPeriod, List actions) {
+ public synchronized @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, List actions) {
// remove nulls
actions = new ArrayList(actions);
for (Iterator itr = actions.iterator(); itr.hasNext();) {
@@ -492,7 +514,7 @@ public class Queue extends ResourceController implements Saveable {
for(QueueDecisionHandler h : QueueDecisionHandler.all())
if (!h.shouldSchedule(p, actions))
- return null; // veto
+ return ScheduleResult.refused(); // veto
return scheduleInternal(p, quietPeriod, actions);
}
@@ -509,7 +531,7 @@ public class Queue extends ResourceController implements Saveable {
*
* That said, one can still look at {@link WaitingItem#future}, {@link WaitingItem#id}, etc.
*/
- private synchronized WaitingItem scheduleInternal(Task p, int quietPeriod, List actions) {
+ private synchronized @Nonnull ScheduleResult scheduleInternal(Task p, int quietPeriod, List actions) {
Calendar due = new GregorianCalendar();
due.add(Calendar.SECOND, quietPeriod);
@@ -532,9 +554,9 @@ public class Queue extends ResourceController implements Saveable {
// put the item in the queue
WaitingItem added = new WaitingItem(due,p,actions);
- waitingList.add(added);
+ added.enter(this);
scheduleMaintenance(); // let an executor know that a new item is in the queue.
- return added;
+ return ScheduleResult.created(added);
}
LOGGER.log(Level.FINE, "{0} is already in the queue", p);
@@ -561,16 +583,22 @@ public class Queue extends ResourceController implements Saveable {
}
// waitingList is sorted, so when we change a timestamp we need to maintain order
- waitingList.remove(wi);
+ wi.leave(this);
wi.timestamp = due;
- waitingList.add(wi);
+ wi.enter(this);
queueUpdated=true;
}
if (queueUpdated) scheduleMaintenance();
- return null;
+
+ // REVISIT: when there are multiple existing items in the queue that matches the incoming one,
+ // whether the new one should affect all existing ones or not is debateable. I for myself
+ // thought this would only affect one, so the code was bit of surprise, but I'm keeping the current
+ // behaviour.
+ return ScheduleResult.existing(duplicatesInQueue.get(0));
}
-
+
+
/**
* @deprecated as of 1.311
* Use {@link #schedule(Task, int)}
@@ -595,7 +623,14 @@ public class Queue extends ResourceController implements Saveable {
* Convenience wrapper method around {@link #schedule(Task, int, List)}
*/
public synchronized WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
- return schedule(p, quietPeriod, Arrays.asList(actions));
+ return schedule2(p, quietPeriod, actions).getCreateItem();
+ }
+
+ /**
+ * Convenience wrapper method around {@link #schedule2(Task, int, List)}
+ */
+ public synchronized @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, Action... actions) {
+ return schedule2(p, quietPeriod, Arrays.asList(actions));
}
/**
@@ -606,12 +641,9 @@ public class Queue extends ResourceController implements Saveable {
*/
public synchronized boolean cancel(Task p) {
LOGGER.log(Level.FINE, "Cancelling {0}", p);
- for (Iterator itr = waitingList.iterator(); itr.hasNext();) {
- Item item = itr.next();
+ for (WaitingItem item : waitingList) {
if (item.task.equals(p)) {
- itr.remove();
- item.onCancelled();
- return true;
+ return item.cancel(this);
}
}
// use bitwise-OR to make sure that both branches get evaluated all the time
@@ -620,14 +652,11 @@ public class Queue extends ResourceController implements Saveable {
public synchronized boolean cancel(Item item) {
LOGGER.log(Level.FINE, "Cancelling {0} item#{1}", new Object[] {item.task, item.id});
- // use bitwise-OR to make sure that all the branches get evaluated all the time
- boolean r = (item instanceof WaitingItem && waitingList.remove(item)) | blockedProjects.remove(item) | buildables.remove(item);
+ boolean r = item.leave(this);
LeftItem li = new LeftItem(item);
- leftItems.put(li.id,li);
+ li.enter(this);
- if(r)
- item.onCancelled();
return r;
}
@@ -887,7 +916,7 @@ public class Queue extends ResourceController implements Saveable {
pendings.remove(wu.context.item);
LeftItem li = new LeftItem(wu.context);
- leftItems.put(li.id,li);
+ li.enter(this);
return wu;
}
@@ -934,7 +963,7 @@ public class Queue extends ResourceController implements Saveable {
if (offer.workUnit.isMainWork()) {
pendings.remove(offer.workUnit.context.item);
LeftItem li = new LeftItem(offer.workUnit.context);
- leftItems.put(li.id,li);
+ li.enter(this);
}
return offer.workUnit;
@@ -1023,13 +1052,10 @@ public class Queue extends ResourceController implements Saveable {
LOGGER.log(Level.FINE, "Queue maintenance started {0}", this);
{// blocked -> buildable
- Iterator itr = blockedProjects.values().iterator();
- while (itr.hasNext()) {
- BlockedItem p = itr.next();
+ for (BlockedItem p : new ArrayList(blockedProjects.values())) {// copy as we'll mutate the list
if (!isBuildBlocked(p) && allowNewBuildableTask(p.task)) {
// ready to be executed
- LOGGER.log(Level.FINE, "{0} no longer blocked", p.task);
- itr.remove();
+ p.leave(this);
makeBuildable(new BuildableItem(p));
}
}
@@ -1042,17 +1068,15 @@ public class Queue extends ResourceController implements Saveable {
if (!top.timestamp.before(new GregorianCalendar()))
break; // finished moving all ready items from queue
- waitingList.remove(top);
+ top.leave(this);
Task p = top.task;
if (!isBuildBlocked(top) && allowNewBuildableTask(p)) {
// ready to be executed immediately
- LOGGER.log(Level.FINE, "{0} ready to build", p);
makeBuildable(new BuildableItem(top));
} else {
// this can't be built now because another build is in progress
// set this project aside.
- LOGGER.log(Level.FINE, "{0} is blocked", p);
- blockedProjects.put(p,new BlockedItem(top));
+ new BlockedItem(top).enter(this);
}
}
@@ -1061,21 +1085,18 @@ public class Queue extends ResourceController implements Saveable {
s.sortBuildableItems(buildables);
// allocate buildable jobs to executors
- Iterator itr = buildables.iterator();
- while (itr.hasNext()) {
- BuildableItem p = itr.next();
-
+ for (BuildableItem p : new ArrayList(buildables)) {// copy as we'll mutate the list in the loop
// one last check to make sure this build is not blocked.
if (isBuildBlocked(p)) {
- itr.remove();
- blockedProjects.put(p.task,new BlockedItem(p));
+ p.leave(this);
+ new BlockedItem(p).enter(this);
LOGGER.log(Level.FINE, "Catching that {0} is blocked in the last minute", p);
continue;
}
List candidates = new ArrayList(parked.size());
for (JobOffer j : parked.values())
- if(j.canTake(p))
+ if (j.canTake(p))
candidates.add(j);
MappingWorksheet ws = new MappingWorksheet(p, candidates);
@@ -1084,7 +1105,7 @@ public class Queue extends ResourceController implements Saveable {
// if we couldn't find the executor that fits,
// just leave it in the buildables list and
// check if we can execute other projects
- LOGGER.log(Level.FINER, "Failed to map {0} to executors. candidates={1} parked={2}", new Object[] {p, candidates, parked.values()});
+ LOGGER.log(Level.FINER, "Failed to map {0} to executors. candidates={1} parked={2}", new Object[]{p, candidates, parked.values()});
continue;
}
@@ -1092,7 +1113,7 @@ public class Queue extends ResourceController implements Saveable {
WorkUnitContext wuc = new WorkUnitContext(p);
m.execute(wuc);
- itr.remove();
+ p.leave(this);
if (!wuc.getWorkUnits().isEmpty())
makePending(p);
else
@@ -1126,8 +1147,8 @@ public class Queue extends ResourceController implements Saveable {
// if the execution get here, it means we couldn't schedule it anywhere.
// so do the scheduling like other normal jobs.
}
-
- buildables.put(p.task,p);
+
+ p.enter(this);
}
private boolean makePending(BuildableItem p) {
@@ -1282,6 +1303,25 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.377
*/
Collection extends SubTask> getSubTasks();
+
+ /**
+ * This method allows the task to provide the default fallback authentication object to be used
+ * when {@link QueueItemAuthenticator} fails to authenticate the build.
+ *
+ *
+ * When the task execution touches other objects inside Jenkins, the access control is performed
+ * based on whether this {@link Authentication} is allowed to use them.
+ *
+ *
+ * This method was added to an interface after it was created, so plugins built against
+ * older versions of Jenkins may not have this method implemented. Called {@link Tasks#_getDefaultAuthenticationOf(Task)}
+ * to avoid {@link AbstractMethodError}.
+ *
+ * @since 1.520
+ * @see QueueItemAuthenticator
+ * @see Tasks#getDefaultAuthenticationOf(Task)
+ */
+ @Nonnull Authentication getDefaultAuthentication();
}
/**
@@ -1513,12 +1553,26 @@ public class Queue extends ResourceController implements Saveable {
}
/**
- * Participates in the cancellation logic to set the {@link #future} accordingly.
+ * Returns the identity that this task carries when it runs, for the purpose of access control.
+ *
+ * When the task execution touches other objects inside Jenkins, the access control is performed
+ * based on whether this {@link Authentication} is allowed to use them. Implementers, if you are unsure,
+ * return the identity of the user who queued the task, or {@link ACL#SYSTEM} to bypass the access control
+ * and run as the super user.
+ *
+ * @since 1.520
*/
- /*package*/ void onCancelled() {
- future.setAsCancelled();
+ @Nonnull
+ public Authentication authenticate() {
+ for (QueueItemAuthenticator auth : QueueItemAuthenticatorConfiguration.get().getAuthenticators()) {
+ Authentication a = auth.authenticate(this);
+ if (a!=null)
+ return a;
+ }
+ return Tasks.getDefaultAuthenticationOf(task);
}
+
public Api getApi() {
return new Api(this);
}
@@ -1532,6 +1586,27 @@ public class Queue extends ResourceController implements Saveable {
public String toString() {
return getClass().getName() + ':' + task + ':' + getWhy();
}
+
+ /**
+ * Enters the appropriate queue for this type of item.
+ */
+ /*package*/ abstract void enter(Queue q);
+
+ /**
+ * Leaves the appropriate queue for this type of item.
+ */
+ /*package*/ abstract boolean leave(Queue q);
+
+ /**
+ * Cancels this item, which updates {@link #future} to notify the listener, and
+ * also leaves the queue.
+ */
+ /*package*/ boolean cancel(Queue q) {
+ boolean r = leave(q);
+ if (r) future.setAsCancelled();
+ return r;
+ }
+
}
/**
@@ -1612,6 +1687,38 @@ public class Queue extends ResourceController implements Saveable {
else
return CauseOfBlockage.fromMessage(Messages._Queue_Unknown());
}
+
+ @Override
+ /*package*/ void enter(Queue q) {
+ if (q.waitingList.add(this)) {
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onEnterWaiting(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+ }
+
+ @Override
+ /*package*/ boolean leave(Queue q) {
+ boolean r = q.waitingList.remove(this);
+ if (r) {
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onLeaveWaiting(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+ return r;
+ }
+
+
}
/**
@@ -1663,6 +1770,35 @@ public class Queue extends ResourceController implements Saveable {
return task.getCauseOfBlockage();
}
+
+ /*package*/ void enter(Queue q) {
+ LOGGER.log(Level.FINE, "{0} is blocked", this);
+ blockedProjects.add(this);
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onEnterBlocked(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+
+ /*package*/ boolean leave(Queue q) {
+ boolean r = blockedProjects.remove(this);
+ if (r) {
+ LOGGER.log(Level.FINE, "{0} no longer blocked", this);
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onLeaveBlocked(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+ return r;
+ }
}
/**
@@ -1702,7 +1838,7 @@ public class Queue extends ResourceController implements Saveable {
else return new BecauseNodeIsBusy(nodes.iterator().next());
}
} else {
- CauseOfBlockage c = null;
+ CauseOfBlockage c;
for (Node node : allNodes) {
if (node.toComputer().isPartiallyIdle()) {
c = canTake(node);
@@ -1744,6 +1880,36 @@ public class Queue extends ResourceController implements Saveable {
public boolean isPending() {
return isPending;
}
+
+ @Override
+ /*package*/ void enter(Queue q) {
+ q.buildables.add(this);
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onEnterBuildable(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+
+ @Override
+ /*package*/ boolean leave(Queue q) {
+ boolean r = q.buildables.remove(this);
+ if (r) {
+ LOGGER.log(Level.FINE, "{0} no longer blocked", this);
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onLeaveBuildable(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+ return r;
+ }
}
/**
@@ -1792,6 +1958,25 @@ public class Queue extends ResourceController implements Saveable {
public boolean isCancelled() {
return outcome==null;
}
+
+ @Override
+ void enter(Queue q) {
+ q.leftItems.put(id,this);
+ for (QueueListener ql : QueueListener.all()) {
+ try {
+ ql.onLeft(this);
+ } catch (Throwable e) {
+ // don't let this kill the queue
+ LOGGER.log(Level.WARNING, "QueueListener failed while processing "+this,e);
+ }
+ }
+ }
+
+ @Override
+ boolean leave(Queue q) {
+ // there's no leave operation
+ return false;
+ }
}
private static final Logger LOGGER = Logger.getLogger(Queue.class.getName());
@@ -1899,7 +2084,7 @@ public class Queue extends ResourceController implements Saveable {
/**
* {@link ArrayList} of {@link Item} with more convenience methods.
*/
- private static class ItemList extends ArrayList {
+ private class ItemList extends ArrayList {
public T get(Task task) {
for (T item: this) {
if (item.task == task) {
@@ -1948,24 +2133,16 @@ public class Queue extends ResourceController implements Saveable {
* Works like {@link #remove(Task)} but also marks the {@link Item} as cancelled.
*/
public T cancel(Task p) {
- T x = remove(p);
- if(x!=null) x.onCancelled();
+ T x = get(p);
+ if(x!=null) x.cancel(Queue.this);
return x;
}
- /**
- * Works like {@link #remove(Object)} but also marks the {@link Item} as cancelled.
- */
- public boolean cancel(Item t) {
- boolean r = remove(t);
- if(r) t.onCancelled();
- return r;
- }
-
public void cancelAll() {
- for (T t : this)
- t.onCancelled();
- clear();
+ for (T t : new ArrayList(this))
+ t.cancel(Queue.this);
+
+ clear(); // just to be sure
}
}
diff --git a/core/src/main/java/hudson/model/RestartListener.java b/core/src/main/java/hudson/model/RestartListener.java
index 0873413e38..3fc3c72c57 100644
--- a/core/src/main/java/hudson/model/RestartListener.java
+++ b/core/src/main/java/hudson/model/RestartListener.java
@@ -51,8 +51,7 @@ public abstract class RestartListener implements ExtensionPoint {
public static class Default extends RestartListener {
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
- Jenkins h = Jenkins.getInstance();
- return h.overallLoad.computeTotalExecutors() <= h.overallLoad.computeIdleExecutors();
+ return new ComputerSet().getBusyExecutors() == 0;
}
}
}
diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java
index ef98acb584..5d8c75be1f 100644
--- a/core/src/main/java/hudson/model/Run.java
+++ b/core/src/main/java/hudson/model/Run.java
@@ -91,7 +91,7 @@ import java.util.Set;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.zip.GZIPInputStream;
+import com.jcraft.jzlib.GZIPInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
@@ -1523,7 +1523,7 @@ public abstract class Run ,RunT extends Run getClockDifferenceCallable() {
+ return new GetClockDifference1();
}
public Computer createComputer() {
@@ -412,6 +405,12 @@ public abstract class Slave extends Node implements Serializable {
if(value.startsWith("\\\\") || value.startsWith("/net/"))
return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning());
+ if (!value.contains("\\") && !value.startsWith("/")) {
+ // Unix-looking path that doesn't start with '/'
+ // TODO: detect Windows-looking relative path
+ return FormValidation.error(Messages.Slave_the_remote_root_must_be_an_absolute_path());
+ }
+
return FormValidation.ok();
}
}
@@ -428,16 +427,59 @@ public abstract class Slave extends Node implements Serializable {
private transient String agentCommand;
/**
- * Obtains the system clock.
+ * Obtains the clock difference between this side and that side of the channel.
+ *
+ *
+ * This is a hack to wrap the whole thing into a simple {@link Callable}.
+ *
+ *
+ * - When the callable is sent to remote, we capture the time (on this side) in {@link GetClockDifference2#startTime}
+ *
- When the other side receives the callable it is {@link GetClockDifference2}.
+ *
- We capture the time on the other side and {@link GetClockDifference3} gets sent from the other side
+ *
- When it's read on this side as a return value, it morphs itself into {@link ClockDifference}.
+ *
*/
- private static final class GetSystemTime implements Callable {
- public Long call() {
- return System.currentTimeMillis();
+ private static final class GetClockDifference1 implements Callable {
+ public ClockDifference call() {
+ // this method must be being invoked locally, which means the clock is in sync
+ return new ClockDifference(0);
+ }
+
+ private Object writeReplace() {
+ return new GetClockDifference2();
}
private static final long serialVersionUID = 1L;
}
+ private static final class GetClockDifference2 implements Callable {
+ /**
+ * Capture the time on the master when this object is sent to remote, which is when
+ * {@link GetClockDifference1#writeReplace()} is run.
+ */
+ private final long startTime = System.nanoTime();
+
+ public GetClockDifference3 call() {
+ return new GetClockDifference3(startTime);
+ }
+
+ private static final long serialVersionUID = 1L;
+ }
+
+ private static final class GetClockDifference3 implements Serializable {
+ private final long remoteTime = System.nanoTime();
+ private final long startTime;
+
+ public GetClockDifference3(long startTime) {
+ this.startTime = startTime;
+ }
+
+ private Object readResolve() {
+ long endTime = System.nanoTime();
+ return new ClockDifference(TimeUnit2.NANOSECONDS.toMillis((startTime + endTime)/2-remoteTime));
+ }
+ }
+
/**
* Determines the workspace root file name for those who really really need the shortest possible path name.
*/
diff --git a/core/src/main/java/hudson/model/UsageStatistics.java b/core/src/main/java/hudson/model/UsageStatistics.java
index 34382a3f44..2d15348670 100644
--- a/core/src/main/java/hudson/model/UsageStatistics.java
+++ b/core/src/main/java/hudson/model/UsageStatistics.java
@@ -59,7 +59,7 @@ import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
-import java.util.zip.GZIPOutputStream;
+import com.jcraft.jzlib.GZIPOutputStream;
/**
* @author Kohsuke Kawaguchi
diff --git a/core/src/main/java/hudson/model/View.java b/core/src/main/java/hudson/model/View.java
index 40a90b97d0..6850ff2f57 100644
--- a/core/src/main/java/hudson/model/View.java
+++ b/core/src/main/java/hudson/model/View.java
@@ -93,6 +93,7 @@ import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -176,6 +177,28 @@ public abstract class View extends AbstractModelObject implements AccessControll
@Exported(name="jobs")
public abstract Collection getItems();
+ /**
+ * Gets all the items recursively contained in this collection in a read-only view.
+ *
+ * The default implementation recursively adds the items of all contained Views
+ * in case this view implements {@link ViewGroup}, which should be enough for most cases.
+ *
+ * @since 1.520
+ */
+ public Collection getAllItems() {
+
+ if (this instanceof ViewGroup) {
+ final Collection items = new LinkedHashSet(getItems());
+
+ for(View view: ((ViewGroup) this).getViews()) {
+ items.addAll(view.getAllItems());
+ }
+ return Collections.unmodifiableCollection(items);
+ } else {
+ return getItems();
+ }
+ }
+
/**
* Gets the {@link TopLevelItem} of the given name.
*/
@@ -939,7 +962,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
save();
- FormApply.success("../"+name).generateResponse(req,rsp,this);
+ FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this);
}
/**
diff --git a/core/src/main/java/hudson/model/listeners/RunListener.java b/core/src/main/java/hudson/model/listeners/RunListener.java
index 21f3e7e616..a04b3ffd22 100644
--- a/core/src/main/java/hudson/model/listeners/RunListener.java
+++ b/core/src/main/java/hudson/model/listeners/RunListener.java
@@ -249,7 +249,7 @@ public abstract class RunListener implements ExtensionPoint {
}
/**
- * Returns all the registered {@link RunListener} descriptors.
+ * Returns all the registered {@link RunListener}s.
*/
public static ExtensionList all() {
return Jenkins.getInstance().getExtensionList(RunListener.class);
diff --git a/core/src/main/java/hudson/model/queue/AbstractQueueTask.java b/core/src/main/java/hudson/model/queue/AbstractQueueTask.java
index c732df4fa3..2a5a9db50f 100644
--- a/core/src/main/java/hudson/model/queue/AbstractQueueTask.java
+++ b/core/src/main/java/hudson/model/queue/AbstractQueueTask.java
@@ -26,7 +26,10 @@ package hudson.model.queue;
import hudson.model.Queue;
import hudson.model.Queue.Task;
+import hudson.security.ACL;
+import org.acegisecurity.Authentication;
+import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
@@ -57,4 +60,13 @@ public abstract class AbstractQueueTask implements Queue.Task {
public Object getSameNodeConstraint() {
return null;
}
+
+ /**
+ * This default implementation is the historical behaviour, but this is no longer desirable. Please override.
+ * See {@link Task#getDefaultAuthentication()} for the contract.
+ */
+ @Nonnull
+ public Authentication getDefaultAuthentication() {
+ return ACL.SYSTEM;
+ }
}
diff --git a/core/src/main/java/hudson/model/queue/CauseOfBlockage.java b/core/src/main/java/hudson/model/queue/CauseOfBlockage.java
index 4c56340144..0713a89eb2 100644
--- a/core/src/main/java/hudson/model/queue/CauseOfBlockage.java
+++ b/core/src/main/java/hudson/model/queue/CauseOfBlockage.java
@@ -10,12 +10,19 @@ import hudson.slaves.Cloud;
import org.jvnet.localizer.Localizable;
/**
- * If a {@link Task} execution is blocked in the queue, this object represents why.
+ * If something is blocked/vetoed, this object represents why.
+ *
+ *
+ * Originally, this is added for {@link Task} stuck in the queue, but since then the use of this
+ * has expanded beyond queues.
*
*
View
- * summary.jelly should do one-line HTML rendering to be used while rendering
- * "build history" widget, next to the blocking build. By default it simply renders
- * {@link #getShortDescription()} text.
+ * summary.jelly should do one-line HTML rendering to be used showing the cause
+ * to the user. By default it simply renders {@link #getShortDescription()} text.
+ *
+ *
+ * For queues, this is used while rendering the "build history" widget.
+ *
*
* @since 1.330
*/
diff --git a/core/src/main/java/hudson/model/queue/MappingWorksheet.java b/core/src/main/java/hudson/model/queue/MappingWorksheet.java
index 43f15a0b44..306075b45e 100644
--- a/core/src/main/java/hudson/model/queue/MappingWorksheet.java
+++ b/core/src/main/java/hudson/model/queue/MappingWorksheet.java
@@ -25,6 +25,7 @@ package hudson.model.queue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
+import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Executor;
import hudson.model.Label;
@@ -35,6 +36,7 @@ import hudson.model.Queue.Executable;
import hudson.model.Queue.JobOffer;
import hudson.model.Queue.Task;
import hudson.model.labels.LabelAssignmentAction;
+import hudson.security.ACL;
import java.util.AbstractList;
import java.util.ArrayList;
@@ -57,7 +59,7 @@ import static java.lang.Math.*;
* which determines where each {@link SubTask} gets executed.
*
*
- * This mapping is done under two constraints:
+ * This mapping is done under the following constraints:
*
*
* -
@@ -111,6 +113,7 @@ public class MappingWorksheet {
public final int index;
public final Computer computer;
public final Node node;
+ public final ACL nodeAcl;
private ExecutorChunk(List base, int index) {
super(base);
@@ -118,14 +121,23 @@ public class MappingWorksheet {
assert !base.isEmpty();
computer = base.get(0).getExecutor().getOwner();
node = computer.getNode();
+ nodeAcl = node.getACL();
}
/**
* Is this executor chunk and the given work chunk compatible? Can the latter be run on the former?
*/
public boolean canAccept(WorkChunk c) {
- return this.size() >= c.size()
- && (c.assignedLabel==null || c.assignedLabel.contains(node));
+ if (this.size() {
public final int index;
diff --git a/core/src/main/java/hudson/model/queue/QueueListener.java b/core/src/main/java/hudson/model/queue/QueueListener.java
new file mode 100644
index 0000000000..93eafcbb73
--- /dev/null
+++ b/core/src/main/java/hudson/model/queue/QueueListener.java
@@ -0,0 +1,85 @@
+package hudson.model.queue;
+
+import hudson.ExtensionList;
+import hudson.ExtensionPoint;
+import hudson.model.Computer;
+import hudson.model.Queue;
+import hudson.model.Queue.BlockedItem;
+import hudson.model.Queue.BuildableItem;
+import hudson.model.Queue.Item;
+import hudson.model.Queue.LeftItem;
+import hudson.model.Queue.WaitingItem;
+import jenkins.model.Jenkins;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Listener for events in {@link Queue}.
+ *
+ *
+ * {@link Queue} is highly synchronized objects, and these callbacks are invoked synchronously.
+ * To avoid the risk of deadlocks and general slow down, please minimize the amount of work callbacks
+ * will perform, and push any sizable work to asynchronous execution via {@link Executor}, such as
+ * {@link Computer#threadPoolForRemoting}.
+ *
+ *
+ * For the state transition of {@link Queue.Item} in {@link Queue}, please refer to the Queue javadoc.
+ *
+ * @author Kohsuke Kawaguchi
+ * @since 1.520
+ */
+public abstract class QueueListener implements ExtensionPoint {
+ /**
+ * When a task is submitted to the queue, it first gets to the waiting phase,
+ * where it spends until the quiet period runs out and the item becomes executable.
+ *
+ * @see WaitingItem#timestamp
+ */
+ public void onEnterWaiting(WaitingItem wi) {}
+
+ /**
+ * An item leaves the waiting phase when the current time of the system is past its
+ * {@linkplain WaitingItem#timestamp due date}. The item will then enter either the blocked phase
+ * or the buildable phase.
+ */
+ public void onLeaveWaiting(WaitingItem wi) {}
+
+ /**
+ * An item enters the blocked phase when there's someone saying "NO" to it proceeding to the buildable phase,
+ * such as {@link QueueTaskDispatcher}. Note that waiting for an executor to become available is not a part of this.
+ */
+ public void onEnterBlocked(BlockedItem bi) {}
+
+ /**
+ * An item leaves the blocked phase and becomes buildable when there's no one vetoing.
+ */
+ public void onLeaveBlocked(BlockedItem bi) {}
+
+ /**
+ * An item enters the buildable phase when all signals are green (or blue!) and it's just waiting
+ * for the scheduler to allocate it to the available executor. An item can spend considerable time
+ * in this phase for example if all the executors are busy.
+ */
+ public void onEnterBuildable(BuildableItem bi) {}
+
+ /**
+ * An item leaves the buildable phase.
+ *
+ * It will move to the "left" state if the executors are allocated to it, or it will move to the
+ * blocked phase if someone starts vetoing once again.
+ */
+ public void onLeaveBuildable(BuildableItem bi) {}
+
+ /**
+ * The item has left the queue, either by getting {@link Queue#cancel(Item) cancelled} or by getting
+ * picked up by an executor and starts running.
+ */
+ public void onLeft(LeftItem li) {}
+
+ /**
+ * Returns all the registered {@link QueueListener}s.
+ */
+ public static ExtensionList all() {
+ return Jenkins.getInstance().getExtensionList(QueueListener.class);
+ }
+}
diff --git a/core/src/main/java/hudson/model/queue/ScheduleResult.java b/core/src/main/java/hudson/model/queue/ScheduleResult.java
new file mode 100644
index 0000000000..680cd77fe5
--- /dev/null
+++ b/core/src/main/java/hudson/model/queue/ScheduleResult.java
@@ -0,0 +1,111 @@
+package hudson.model.queue;
+
+import hudson.model.Action;
+import hudson.model.Queue;
+import hudson.model.Queue.Item;
+import hudson.model.Queue.Task;
+import hudson.model.Queue.WaitingItem;
+
+/**
+ * Result of {@link Queue#schedule2}
+ *
+ * @author Kohsuke Kawaguchi
+ * @since 1.521
+ * @see Queue#schedule(Task, int, Action...)
+ */
+public abstract class ScheduleResult {
+
+ /**
+ * If true, the {@link #getItem()} is newly created
+ * as a result of {@link Queue#schedule2}.
+ */
+ public boolean isCreated() {
+ return false;
+ }
+
+ /**
+ * The scheduling of the task was refused and the queue didn't change.
+ * If this method returns true, {@link #getItem()} will return null.
+ */
+ public boolean isRefused() {
+ return false;
+ }
+
+ /**
+ * Unless {@link #isRefused()} is true, this method either returns
+ * the newly created item in the queue or the existing item that's already
+ * in the queue that matched the submitted task.
+ */
+ public Item getItem() {
+ return null;
+ }
+
+ /**
+ * If {@link #isCreated()} returns true, then this method returns
+ * the newly created item, which is always of the type {@link WaitingItem}.
+ */
+ public WaitingItem getCreateItem() {
+ return null;
+ }
+
+ /**
+ * Opposite of {@link #isRefused()}
+ */
+ public final boolean isAccepted() {
+ return !isRefused();
+ }
+
+ public static final class Created extends ScheduleResult {
+ private final WaitingItem item;
+ private Created(WaitingItem item) {
+ this.item = item;
+ }
+
+ @Override
+ public boolean isCreated() {
+ return true;
+ }
+
+ @Override
+ public WaitingItem getCreateItem() {
+ return item;
+ }
+
+ @Override
+ public Item getItem() {
+ return item;
+ }
+ }
+
+ public static final class Existing extends ScheduleResult {
+ private final Item item;
+
+ private Existing(Item item) {
+ this.item = item;
+ }
+
+ @Override
+ public Item getItem() {
+ return item;
+ }
+ }
+
+ public static final class Refused extends ScheduleResult {
+ @Override
+ public boolean isRefused() {
+ return true;
+ }
+ }
+
+ public static Created created(WaitingItem i) {
+ return new Created(i);
+ }
+
+ public static Existing existing(Item i) {
+ return new Existing(i);
+ }
+
+ public static Refused refused() {
+ return new Refused();
+ }
+}
diff --git a/core/src/main/java/hudson/model/queue/SubTask.java b/core/src/main/java/hudson/model/queue/SubTask.java
index 315adece51..c5dc1391cd 100644
--- a/core/src/main/java/hudson/model/queue/SubTask.java
+++ b/core/src/main/java/hudson/model/queue/SubTask.java
@@ -29,7 +29,10 @@ import hudson.model.Node;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.ResourceActivity;
+import hudson.security.ACL;
+import org.acegisecurity.Authentication;
+import javax.annotation.Nonnull;
import java.io.IOException;
/**
diff --git a/core/src/main/java/hudson/model/queue/SubTaskContributor.java b/core/src/main/java/hudson/model/queue/SubTaskContributor.java
index e1d639e32c..f6519e5dca 100644
--- a/core/src/main/java/hudson/model/queue/SubTaskContributor.java
+++ b/core/src/main/java/hudson/model/queue/SubTaskContributor.java
@@ -47,7 +47,7 @@ public abstract class SubTaskContributor implements ExtensionPoint {
}
/**
- * All registered {@link MemberExecutionUnitContributor} instances.
+ * All registered {@link SubTaskContributor} instances.
*/
public static ExtensionList all() {
return Jenkins.getInstance().getExtensionList(SubTaskContributor.class);
diff --git a/core/src/main/java/hudson/model/queue/Tasks.java b/core/src/main/java/hudson/model/queue/Tasks.java
index cfa99357a0..2031ca5b32 100644
--- a/core/src/main/java/hudson/model/queue/Tasks.java
+++ b/core/src/main/java/hudson/model/queue/Tasks.java
@@ -24,6 +24,8 @@
package hudson.model.queue;
import hudson.model.Queue.Task;
+import hudson.security.ACL;
+import org.acegisecurity.Authentication;
import java.util.Collection;
import java.util.Collections;
@@ -83,4 +85,26 @@ public class Tasks {
return (Task)t;
}
}
+
+ /**
+ * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
+ * on BugParade for more details.
+ */
+ private static Authentication _getDefaultAuthenticationOf(Task t) {
+ return t.getDefaultAuthentication();
+ }
+
+ /**
+ * @param t a task
+ * @return {@link Task#getDefaultAuthentication}, or {@link ACL#SYSTEM}
+ * @since 1.520
+ */
+ public static Authentication getDefaultAuthenticationOf(Task t) {
+ try {
+ return _getDefaultAuthenticationOf(t);
+ } catch (AbstractMethodError e) {
+ return ACL.SYSTEM;
+ }
+ }
+
}
diff --git a/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java
new file mode 100644
index 0000000000..bfb88d264e
--- /dev/null
+++ b/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java
@@ -0,0 +1,119 @@
+package hudson.node_monitors;
+
+import hudson.model.Computer;
+import hudson.remoting.Callable;
+import hudson.remoting.VirtualChannel;
+import jenkins.model.Jenkins;
+
+import javax.annotation.CheckForNull;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.logging.Logger;
+
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.logging.Level.WARNING;
+
+/**
+ * Sophisticated version of {@link AbstractNodeMonitorDescriptor} that
+ * performs monitoring on all slaves concurrently and asynchronously.
+ *
+ * @param
+ * represents the the result of the monitoring.
+ * @author Kohsuke Kawaguchi
+ */
+public abstract class AbstractAsyncNodeMonitorDescriptor extends AbstractNodeMonitorDescriptor {
+ protected AbstractAsyncNodeMonitorDescriptor() {
+ }
+
+ protected AbstractAsyncNodeMonitorDescriptor(long interval) {
+ super(interval);
+ }
+
+ protected AbstractAsyncNodeMonitorDescriptor(Class extends NodeMonitor> clazz) {
+ super(clazz);
+ }
+
+ protected AbstractAsyncNodeMonitorDescriptor(Class extends NodeMonitor> clazz, long interval) {
+ super(clazz, interval);
+ }
+
+ /**
+ * Creates a {@link Callable} that performs the monitoring when executed.
+ */
+ protected abstract @CheckForNull Callable createCallable(Computer c);
+
+ @Override
+ protected T monitor(Computer c) throws IOException, InterruptedException {
+ VirtualChannel ch = c.getChannel();
+ if (ch != null) {
+ Callable cc = createCallable(c);
+ if (cc!=null)
+ return ch.call(cc);
+ }
+ return null;
+ }
+
+ /**
+ * Performs all monitoring concurrently.
+ */
+ @Override
+ protected Map monitor() throws InterruptedException {
+ Map> futures = new HashMap>();
+
+ for (Computer c : Jenkins.getInstance().getComputers()) {
+ try {
+ VirtualChannel ch = c.getChannel();
+ futures.put(c,null); // sentinel value
+ if (ch!=null) {
+ Callable cc = createCallable(c);
+ if (cc!=null)
+ futures.put(c,ch.callAsync(cc));
+ }
+ } catch (RuntimeException e) {
+ LOGGER.log(WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
+ } catch (IOException e) {
+ LOGGER.log(WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
+ }
+ }
+
+ final long now = System.currentTimeMillis();
+ final long end = now + getMonitoringTimeOut();
+
+ final Map data = new HashMap();
+
+ for (Entry> e : futures.entrySet()) {
+ Computer c = e.getKey();
+ Future f = futures.get(c);
+ data.put(c, null); // sentinel value
+
+ if (f!=null) {
+ try {
+ data.put(c,f.get(Math.max(0,end-System.currentTimeMillis()), MILLISECONDS));
+ } catch (RuntimeException x) {
+ LOGGER.log(WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
+ } catch (ExecutionException x) {
+ LOGGER.log(WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
+ } catch (TimeoutException x) {
+ LOGGER.log(WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
+ }
+ }
+ }
+
+ return data;
+ }
+
+ /**
+ * Controls the time out of monitoring.
+ */
+ protected long getMonitoringTimeOut() {
+ return TimeUnit.SECONDS.toMillis(30);
+ }
+
+ private static final Logger LOGGER = Logger.getLogger(AbstractAsyncNodeMonitorDescriptor.class.getName());
+}
diff --git a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java
index f6c680067e..be90b91d0e 100644
--- a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java
@@ -2,6 +2,9 @@ package hudson.node_monitors;
import hudson.model.Computer;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
+
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import java.text.ParseException;
@@ -9,6 +12,7 @@ import java.util.logging.Logger;
/**
* @author Kohsuke Kawaguchi
+ * @see DiskSpaceMonitorDescriptor
*/
public abstract class AbstractDiskSpaceMonitor extends NodeMonitor {
/**
@@ -39,13 +43,9 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor {
@Override
public Object data(Computer c) {
- DiskSpace size = (DiskSpace) super.data(c);
- if(size!=null && size.size < getThresholdBytes()) {
- size.setTriggered(this.getClass(), true);
- if(getDescriptor().markOffline(c,size)) {
- LOGGER.warning(Messages.DiskSpaceMonitor_MarkedOffline(c.getName()));
- }
- }
+ DiskSpace size = markNodeOfflineIfDiskspaceIsTooLow(c);
+
+ // mark online (again), if free space is over threshold
if(size!=null && size.size > getThresholdBytes() && c.isOffline() && c.getOfflineCause() instanceof DiskSpace)
if(this.getClass().equals(((DiskSpace)c.getOfflineCause()).getTrigger()))
if(getDescriptor().markOnline(c)) {
@@ -54,6 +54,24 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor {
return size;
}
+ /**
+ * Marks the given node as offline if free disk space is below the configured threshold.
+ * @param c the node
+ * @return the free space
+ * @since 1.521
+ */
+ @Restricted(NoExternalUse.class)
+ public DiskSpace markNodeOfflineIfDiskspaceIsTooLow(Computer c) {
+ DiskSpace size = (DiskSpace) super.data(c);
+ if(size!=null && size.size < getThresholdBytes()) {
+ size.setTriggered(this.getClass(), true);
+ if(getDescriptor().markOffline(c,size)) {
+ LOGGER.warning(Messages.DiskSpaceMonitor_MarkedOffline(c.getName()));
+ }
+ }
+ return size;
+ }
+
private static final Logger LOGGER = Logger.getLogger(AbstractDiskSpaceMonitor.class.getName());
private static final long DEFAULT_THRESHOLD = 1024L*1024*1024;
}
diff --git a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
index 48b2df9b11..3e57ea5bfe 100644
--- a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
+++ b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
@@ -34,6 +34,7 @@ import hudson.triggers.SafeTimerTask;
import hudson.slaves.OfflineCause;
import java.io.IOException;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -51,18 +52,34 @@ import java.util.logging.Logger;
* @author Kohsuke Kawaguchi
*/
public abstract class AbstractNodeMonitorDescriptor extends Descriptor {
+ /**
+ * @deprecated as of 1.522
+ * Extend from {@link AbstractAsyncNodeMonitorDescriptor}
+ */
protected AbstractNodeMonitorDescriptor() {
this(HOUR);
}
+ /**
+ * @deprecated as of 1.522
+ * Extend from {@link AbstractAsyncNodeMonitorDescriptor}
+ */
protected AbstractNodeMonitorDescriptor(long interval) {
schedule(interval);
}
+ /**
+ * @deprecated as of 1.522
+ * Extend from {@link AbstractAsyncNodeMonitorDescriptor}
+ */
protected AbstractNodeMonitorDescriptor(Class extends NodeMonitor> clazz) {
this(clazz,HOUR);
}
+ /**
+ * @deprecated as of 1.522
+ * Extend from {@link AbstractAsyncNodeMonitorDescriptor}
+ */
protected AbstractNodeMonitorDescriptor(Class extends NodeMonitor> clazz, long interval) {
super(clazz);
@@ -85,12 +102,12 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor extends Descriptor monitor() throws InterruptedException {
+ Map data = new HashMap();
+ for( Computer c : Jenkins.getInstance().getComputers() ) {
+ try {
+ Thread.currentThread().setName("Monitoring "+c.getDisplayName()+" for "+getDisplayName());
+
+ if(c.getChannel()==null)
+ data.put(c,null);
+ else
+ data.put(c,monitor(c));
+ } catch (RuntimeException e) {
+ LOGGER.log(Level.WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
+ } catch (InterruptedException e) {
+ throw (InterruptedException)new InterruptedException("Node monitoring "+c.getDisplayName()+" for "+getDisplayName()+" aborted.").initCause(e);
+ }
+ }
+ return data;
+ }
+
/**
* Obtains the monitoring result currently available, or null if no data is available.
*
@@ -214,7 +258,7 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor data = new HashMap();
+ private /*final*/ Map data = Collections.emptyMap();
private long timestamp;
@@ -235,24 +279,7 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor extends Descriptor {
- protected String monitor(Computer c) throws IOException, InterruptedException {
- return c.getChannel().call(new GetArchTask());
+ public static final class DescriptorImpl extends AbstractAsyncNodeMonitorDescriptor {
+ @Override
+ protected Callable createCallable(Computer c) {
+ return new GetArchTask();
}
public String getDisplayName() {
@@ -55,7 +56,7 @@ public class ArchitectureMonitor extends NodeMonitor {
/**
* Obtains the string that represents the architecture.
*/
- private static class GetArchTask implements Callable {
+ private static class GetArchTask implements Callable {
public String call() {
String os = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
diff --git a/core/src/main/java/hudson/node_monitors/ClockMonitor.java b/core/src/main/java/hudson/node_monitors/ClockMonitor.java
index 4352ec9bd4..cf3f025997 100644
--- a/core/src/main/java/hudson/node_monitors/ClockMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/ClockMonitor.java
@@ -25,6 +25,7 @@ package hudson.node_monitors;
import hudson.model.Computer;
import hudson.model.Node;
+import hudson.remoting.Callable;
import hudson.util.ClockDifference;
import hudson.Extension;
import org.kohsuke.stapler.StaplerRequest;
@@ -46,11 +47,12 @@ public class ClockMonitor extends NodeMonitor {
}
@Extension
- public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractNodeMonitorDescriptor() {
- protected ClockDifference monitor(Computer c) throws IOException, InterruptedException {
+ public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractAsyncNodeMonitorDescriptor() {
+ @Override
+ protected Callable createCallable(Computer c) {
Node n = c.getNode();
if(n==null) return null;
- return n.getClockDifference();
+ return n.getClockDifferenceCallable();
}
public String getDisplayName() {
diff --git a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java
index f2d49c4076..1177652124 100644
--- a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java
@@ -27,6 +27,7 @@ import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.Computer;
+import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
import org.kohsuke.stapler.DataBoundConstructor;
@@ -64,11 +65,12 @@ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor {
return Messages.DiskSpaceMonitor_DisplayName();
}
- protected DiskSpace getFreeSpace(Computer c) throws IOException, InterruptedException {
+ @Override
+ protected Callable createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
if(p==null) return null;
- return p.act(new GetUsableSpace());
+ return p.asCallableWith(new GetUsableSpace());
}
};
diff --git a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java
index cdb7e5435c..8f1fb84995 100644
--- a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java
+++ b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java
@@ -45,8 +45,9 @@ import org.kohsuke.stapler.export.Exported;
* {@link AbstractNodeMonitorDescriptor} for {@link NodeMonitor} that checks a free disk space of some directory.
*
* @author Kohsuke Kawaguchi
+ * @since 1.520
*/
-/*package*/ abstract class DiskSpaceMonitorDescriptor extends AbstractNodeMonitorDescriptor {
+public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonitorDescriptor {
/**
* Value object that represents the disk space.
*/
@@ -59,13 +60,6 @@ import org.kohsuke.stapler.export.Exported;
private boolean triggered;
private Class extends AbstractDiskSpaceMonitor> trigger;
- /**
- * @deprecated as of 1.467
- */
- public DiskSpace(long size) {
- this(".",size);
- }
-
/**
* @param path
* Specify the file path that was monitored.
@@ -165,16 +159,8 @@ import org.kohsuke.stapler.export.Exported;
private static final long serialVersionUID = 2L;
}
- protected DiskSpace monitor(Computer c) throws IOException, InterruptedException {
- return getFreeSpace(c);
- }
-
- /**
- * Computes the free size.
- */
- protected abstract DiskSpace getFreeSpace(Computer c) throws IOException, InterruptedException;
-
protected static final class GetUsableSpace implements FileCallable {
+ public GetUsableSpace() {}
@IgnoreJRERequirement
public DiskSpace invoke(File f, VirtualChannel channel) throws IOException {
try {
diff --git a/core/src/main/java/hudson/node_monitors/NodeMonitor.java b/core/src/main/java/hudson/node_monitors/NodeMonitor.java
index 64a3800a5e..b608eb4ab9 100644
--- a/core/src/main/java/hudson/node_monitors/NodeMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/NodeMonitor.java
@@ -36,6 +36,7 @@ import hudson.model.Descriptor;
import hudson.util.DescriptorList;
import java.util.List;
+import javax.annotation.CheckForNull;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
@@ -75,7 +76,7 @@ public abstract class NodeMonitor implements ExtensionPoint, Describable DESCRIPTOR = new AbstractNodeMonitorDescriptor() {
- protected Data monitor(Computer c) throws IOException, InterruptedException {
- Data old = get(c);
- Data d;
+ public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractAsyncNodeMonitorDescriptor() {
+ @Override
+ protected Callable createCallable(Computer c) {
+ return new Step1(get(c));
+ }
- long start = System.nanoTime();
- Future f = c.getChannel().callAsync(new NoopTask());
- try {
- f.get(TIMEOUT, TimeUnit.MILLISECONDS);
- long end = System.nanoTime();
- d = new Data(old,TimeUnit2.NANOSECONDS.toMillis(end-start));
- } catch (ExecutionException e) {
- throw new IOException2(e.getCause()); // I don't think this is possible
- } catch (TimeoutException e) {
- // special constant to indicate that the processing timed out.
- d = new Data(old,-1L);
- }
+ @Override
+ protected Map monitor() throws InterruptedException {
+ Map base = super.monitor();
+ for (Entry e : base.entrySet()) {
+ Computer c = e.getKey();
+ Data d = e.getValue();
+ if (d ==null) {
+ // if we failed to monitor, put in the special value that indicates a failure
+ e.setValue(d=new Data(get(c),-1L));
+ }
- if(d.hasTooManyTimeouts() && !isIgnored()) {
- // unlike other monitors whose failure still allow us to communicate with the slave,
- // the failure in this monitor indicates that we are just unable to make any requests
- // to this slave. So we should severe the connection, as opposed to marking it temporarily
- // off line, which still keeps the underlying channel open.
- c.disconnect(d);
- LOGGER.warning(Messages.ResponseTimeMonitor_MarkedOffline(c.getName()));
+ if(d.hasTooManyTimeouts() && !isIgnored()) {
+ // unlike other monitors whose failure still allow us to communicate with the slave,
+ // the failure in this monitor indicates that we are just unable to make any requests
+ // to this slave. So we should severe the connection, as opposed to marking it temporarily
+ // off line, which still keeps the underlying channel open.
+ c.disconnect(d);
+ LOGGER.warning(Messages.ResponseTimeMonitor_MarkedOffline(c.getName()));
+ }
}
- return d;
+ return base;
}
public String getDisplayName() {
@@ -88,11 +92,63 @@ public class ResponseTimeMonitor extends NodeMonitor {
}
};
+ private static final class Step1 implements Callable {
+ private Data cur;
+
+ private Step1(Data cur) {
+ this.cur = cur;
+ }
+
+ public Data call() {
+ // this method must be being invoked locally, which means the roundtrip time is zero and zero forever
+ return new Data(cur,0);
+ }
+
+ private Object writeReplace() {
+ return new Step2(cur);
+ }
+
+ private static final long serialVersionUID = 1L;
+ }
+
+ private static final class Step2 implements Callable {
+ private final Data cur;
+ private final long start = System.nanoTime();
+
+ public Step2(Data cur) {
+ this.cur = cur;
+ }
+
+ public Step3 call() {
+ // this method must be being invoked locally, which means the roundtrip time is zero and zero forever
+ return new Step3(cur,start);
+ }
+
+ private static final long serialVersionUID = 1L;
+ }
+
+ private static final class Step3 implements Serializable {
+ private final Data cur;
+ private final long start;
+
+ private Step3(Data cur, long start) {
+ this.cur = cur;
+ this.start = start;
+ }
+
+ private Object readResolve() {
+ long end = System.nanoTime();
+ return new Data(cur,TimeUnit2.NANOSECONDS.toMillis(end-start));
+ }
+
+ private static final long serialVersionUID = 1L;
+ }
+
/**
* Immutable representation of the monitoring data.
*/
@ExportedBean
- public static final class Data extends OfflineCause {
+ public static final class Data extends OfflineCause implements Serializable {
/**
* Record of the past 5 times. -1 if time out. Otherwise in milliseconds.
* Old ones first.
@@ -153,12 +209,6 @@ public class ResponseTimeMonitor extends NodeMonitor {
return Util.wrapToErrorSpan(Messages.ResponseTimeMonitor_TimeOut(fc));
return getAverage()+"ms";
}
- }
-
- private static class NoopTask implements Callable {
- public String call() {
- return null;
- }
private static final long serialVersionUID = 1L;
}
diff --git a/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java
index b2edc41fc9..404aa3f779 100644
--- a/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java
@@ -78,9 +78,10 @@ public class SwapSpaceMonitor extends NodeMonitor {
}
@Extension
- public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractNodeMonitorDescriptor() {
- protected MemoryUsage monitor(Computer c) throws IOException, InterruptedException {
- return c.getChannel().call(new MonitorTask());
+ public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractAsyncNodeMonitorDescriptor() {
+ @Override
+ protected MonitorTask createCallable(Computer c) {
+ return new MonitorTask();
}
public String getDisplayName() {
diff --git a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java
index a59fa2789a..05407d318f 100644
--- a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java
+++ b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java
@@ -28,6 +28,7 @@ import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Functions;
import hudson.model.Computer;
+import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
import hudson.remoting.VirtualChannel;
@@ -66,11 +67,12 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor {
return Messages.TemporarySpaceMonitor_DisplayName();
}
- protected DiskSpace getFreeSpace(Computer c) throws IOException, InterruptedException {
+ @Override
+ protected Callable createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
if(p==null) return null;
- return p.act(new GetTempSpace());
+ return p.asCallableWith(new GetTempSpace());
}
};
diff --git a/core/src/main/java/hudson/security/AccessDeniedException2.java b/core/src/main/java/hudson/security/AccessDeniedException2.java
index 92dbb1f2a4..0f5da052b2 100644
--- a/core/src/main/java/hudson/security/AccessDeniedException2.java
+++ b/core/src/main/java/hudson/security/AccessDeniedException2.java
@@ -2,6 +2,10 @@ package hudson.security;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
+import org.acegisecurity.GrantedAuthority;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
/**
* {@link AccessDeniedException} with more information.
@@ -23,8 +27,41 @@ public class AccessDeniedException2 extends AccessDeniedException {
}
public AccessDeniedException2(Throwable t, Authentication authentication, Permission permission) {
- super(Messages.AccessDeniedException2_MissingPermission(authentication.getName(),permission.name), t);
+ super(Messages.AccessDeniedException2_MissingPermission(authentication.getName(),
+ permission.group.title+"/"+permission.name), t);
this.authentication = authentication;
this.permission = permission;
}
+
+ /**
+ * Reports the details of the access failure in HTTP headers to assist diagnosis.
+ */
+ public void reportAsHeaders(HttpServletResponse rsp) {
+ rsp.addHeader("X-You-Are-Authenticated-As",authentication.getName());
+ for (GrantedAuthority auth : authentication.getAuthorities()) {
+ rsp.addHeader("X-You-Are-In-Group",auth.getAuthority());
+ }
+ rsp.addHeader("X-Required-Permission", permission.getId());
+ for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) {
+ rsp.addHeader("X-Permission-Implied-By", p.getId());
+ }
+ }
+
+ /**
+ * Reports the details of the access failure.
+ * This method is similar to {@link #reportAsHeaders(HttpServletResponse)} for the intention
+ * but instead of using HTTP headers, this version is meant to go inside the payload.
+ */
+ public void report(PrintWriter w) {
+ w.println("You are authenticated as: "+authentication.getName());
+ w.println("Groups that you are in:");
+ for (GrantedAuthority auth : authentication.getAuthorities()) {
+ w.println(" "+auth.getAuthority());
+ }
+
+ w.println("Permission you need to have (but didn't): "+permission.getId());
+ for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) {
+ w.println(" ... which is implied by: "+p.getId());
+ }
+ }
}
diff --git a/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java b/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java
index f14255af87..94497cf87c 100644
--- a/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java
+++ b/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java
@@ -26,18 +26,14 @@ package hudson.security;
import jenkins.model.Jenkins;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.ui.AccessDeniedHandler;
-import org.kohsuke.stapler.Stapler;
+import org.kohsuke.stapler.WebApp;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
-import java.util.Enumeration;
-import java.util.Vector;
/**
* Handles {@link AccessDeniedException} happened during request processing.
@@ -46,31 +42,18 @@ import java.util.Vector;
* @author Kohsuke Kawaguchi
*/
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
- public void handle(ServletRequest request, ServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
+ public void handle(ServletRequest request, ServletResponse response, AccessDeniedException cause) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
- req.setAttribute("exception",accessDeniedException);
- Stapler stapler = new Stapler();
- stapler.init(new ServletConfig() {
- public String getServletName() {
- return "Stapler";
- }
+ req.setAttribute("exception",cause);
- public ServletContext getServletContext() {
- return Jenkins.getInstance().servletContext;
- }
+ if (cause instanceof AccessDeniedException2) {
+ ((AccessDeniedException2)cause).reportAsHeaders(rsp);
+ }
- public String getInitParameter(String name) {
- return null;
- }
-
- public Enumeration getInitParameterNames() {
- return new Vector().elements();
- }
- });
-
- stapler.invoke(req,rsp, Jenkins.getInstance(),"/accessDenied");
+ WebApp.get(Jenkins.getInstance().servletContext).getSomeStapler()
+ .invoke(req,rsp, Jenkins.getInstance(), "/accessDenied");
}
}
diff --git a/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java b/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java
index 31dd6855e3..9ebe8aa81f 100644
--- a/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java
+++ b/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java
@@ -50,6 +50,8 @@ import org.kohsuke.stapler.StaplerResponse;
/**
* Security configuration.
*
+ * For historical reasons, most of the actual configuration values are stored in {@link Jenkins}.
+ *
* @author Kohsuke Kawaguchi
*/
@Extension(ordinal = Integer.MAX_VALUE - 210)
diff --git a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java
index 6a3c21efec..64aaff2ba0 100644
--- a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java
+++ b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java
@@ -25,24 +25,21 @@ package hudson.security;
import com.google.common.base.Strings;
import org.acegisecurity.AuthenticationException;
+import org.acegisecurity.InsufficientAuthenticationException;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint;
import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
-import java.io.FilterOutputStream;
import java.io.IOException;
-import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.MessageFormat;
-import java.util.zip.GZIPOutputStream;
/**
* For anonymous requests to pages that require authentication,
@@ -61,7 +58,7 @@ import java.util.zip.GZIPOutputStream;
*/
public class HudsonAuthenticationEntryPoint extends AuthenticationProcessingFilterEntryPoint {
@Override
- public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException {
+ public void commence(ServletRequest request, ServletResponse response, AuthenticationException reason) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
@@ -83,6 +80,16 @@ public class HudsonAuthenticationEntryPoint extends AuthenticationProcessingFilt
rsp.setStatus(SC_FORBIDDEN);
rsp.setContentType("text/html;charset=UTF-8");
+
+ AccessDeniedException2 cause = null;
+ // report the diagnosis information if possible
+ if (reason instanceof InsufficientAuthenticationException) {
+ if (reason.getCause() instanceof AccessDeniedException2) {
+ cause = (AccessDeniedException2) reason.getCause();
+ cause.reportAsHeaders(rsp);
+ }
+ }
+
PrintWriter out;
try {
out = new PrintWriter(new OutputStreamWriter(rsp.getOutputStream()));
@@ -94,9 +101,17 @@ public class HudsonAuthenticationEntryPoint extends AuthenticationProcessingFilt
"" +
"" +
"" +
- "" +
- "Authentication required