4
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
5
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
6
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
9
* Permission is hereby granted, free of charge, to any person obtaining a copy
10
* of this software and associated documentation files (the "Software"), to deal
11
* in the Software without restriction, including without limitation the rights
12
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
* copies of the Software, and to permit persons to whom the Software is
14
* furnished to do so, subject to the following conditions:
16
* The above copyright notice and this permission notice shall be included in
17
* all copies or substantial portions of the Software.
19
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
package jenkins.model;
29
import com.google.common.collect.Lists;
30
import com.google.inject.Injector;
31
import hudson.ExtensionComponent;
32
import hudson.ExtensionFinder;
33
import hudson.model.LoadStatistics;
34
import hudson.model.Messages;
35
import hudson.model.Node;
36
import hudson.model.AbstractCIBase;
37
import hudson.model.AbstractProject;
38
import hudson.model.Action;
39
import hudson.model.AdministrativeMonitor;
40
import hudson.model.AllView;
41
import hudson.model.Api;
42
import hudson.model.Computer;
43
import hudson.model.ComputerSet;
44
import hudson.model.DependencyGraph;
45
import hudson.model.Describable;
46
import hudson.model.Descriptor;
47
import hudson.model.DescriptorByNameOwner;
48
import hudson.model.DirectoryBrowserSupport;
49
import hudson.model.Failure;
50
import hudson.model.Fingerprint;
51
import hudson.model.FingerprintCleanupThread;
52
import hudson.model.FingerprintMap;
53
import hudson.model.FullDuplexHttpChannel;
54
import hudson.model.Hudson;
55
import hudson.model.Item;
56
import hudson.model.ItemGroup;
57
import hudson.model.ItemGroupMixIn;
58
import hudson.model.Items;
59
import hudson.model.JDK;
60
import hudson.model.Job;
61
import hudson.model.JobPropertyDescriptor;
62
import hudson.model.Label;
63
import hudson.model.ListView;
64
import hudson.model.LoadBalancer;
65
import hudson.model.ManagementLink;
66
import hudson.model.NoFingerprintMatch;
67
import hudson.model.OverallLoadStatistics;
68
import hudson.model.Project;
69
import hudson.model.RestartListener;
70
import hudson.model.RootAction;
71
import hudson.model.Slave;
72
import hudson.model.TaskListener;
73
import hudson.model.TopLevelItem;
74
import hudson.model.TopLevelItemDescriptor;
75
import hudson.model.UnprotectedRootAction;
76
import hudson.model.UpdateCenter;
77
import hudson.model.User;
78
import hudson.model.View;
79
import hudson.model.ViewGroup;
80
import hudson.model.ViewGroupMixIn;
81
import hudson.model.Descriptor.FormException;
82
import hudson.model.labels.LabelAtom;
83
import hudson.model.listeners.ItemListener;
84
import hudson.model.listeners.SCMListener;
85
import hudson.model.listeners.SaveableListener;
86
import hudson.model.Queue;
87
import hudson.model.WorkspaceCleanupThread;
89
import antlr.ANTLRException;
90
import com.google.common.collect.ImmutableMap;
91
import com.thoughtworks.xstream.XStream;
92
import hudson.BulkChange;
93
import hudson.DNSMultiCast;
94
import hudson.DescriptorExtensionList;
95
import hudson.Extension;
96
import hudson.ExtensionList;
97
import hudson.ExtensionPoint;
98
import hudson.FilePath;
99
import hudson.Functions;
100
import hudson.Launcher;
101
import hudson.Launcher.LocalLauncher;
102
import hudson.LocalPluginManager;
103
import hudson.Lookup;
104
import hudson.markup.MarkupFormatter;
105
import hudson.Plugin;
106
import hudson.PluginManager;
107
import hudson.PluginWrapper;
108
import hudson.ProxyConfiguration;
109
import hudson.TcpSlaveAgentListener;
110
import hudson.UDPBroadcastThread;
112
import static hudson.Util.fixEmpty;
113
import static hudson.Util.fixNull;
114
import hudson.WebAppMain;
115
import hudson.XmlFile;
116
import hudson.cli.CLICommand;
117
import hudson.cli.CliEntryPoint;
118
import hudson.cli.CliManagerImpl;
119
import hudson.cli.declarative.CLIMethod;
120
import hudson.cli.declarative.CLIResolver;
121
import hudson.init.InitMilestone;
122
import hudson.init.InitStrategy;
123
import hudson.lifecycle.Lifecycle;
124
import hudson.logging.LogRecorderManager;
125
import hudson.lifecycle.RestartNotSupportedException;
126
import hudson.markup.RawHtmlMarkupFormatter;
127
import hudson.remoting.Channel;
128
import hudson.remoting.LocalChannel;
129
import hudson.remoting.VirtualChannel;
130
import hudson.scm.RepositoryBrowser;
131
import hudson.scm.SCM;
132
import hudson.search.CollectionSearchIndex;
133
import hudson.search.SearchIndexBuilder;
134
import hudson.search.SearchItem;
135
import hudson.security.ACL;
136
import hudson.security.AccessControlled;
137
import hudson.security.AuthorizationStrategy;
138
import hudson.security.BasicAuthenticationFilter;
139
import hudson.security.FederatedLoginService;
140
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
141
import hudson.security.HudsonFilter;
142
import hudson.security.LegacyAuthorizationStrategy;
143
import hudson.security.LegacySecurityRealm;
144
import hudson.security.Permission;
145
import hudson.security.PermissionGroup;
146
import hudson.security.PermissionScope;
147
import hudson.security.SecurityMode;
148
import hudson.security.SecurityRealm;
149
import hudson.security.csrf.CrumbIssuer;
150
import hudson.slaves.Cloud;
151
import hudson.slaves.ComputerListener;
152
import hudson.slaves.DumbSlave;
153
import hudson.slaves.EphemeralNode;
154
import hudson.slaves.NodeDescriptor;
155
import hudson.slaves.NodeList;
156
import hudson.slaves.NodeProperty;
157
import hudson.slaves.NodePropertyDescriptor;
158
import hudson.slaves.NodeProvisioner;
159
import hudson.slaves.OfflineCause;
160
import hudson.slaves.RetentionStrategy;
161
import hudson.tasks.BuildWrapper;
162
import hudson.tasks.Builder;
163
import hudson.tasks.Mailer;
164
import hudson.tasks.Publisher;
165
import hudson.triggers.SafeTimerTask;
166
import hudson.triggers.Trigger;
167
import hudson.triggers.TriggerDescriptor;
168
import hudson.util.AdministrativeError;
169
import hudson.util.CaseInsensitiveComparator;
170
import hudson.util.ClockDifference;
171
import hudson.util.CopyOnWriteList;
172
import hudson.util.CopyOnWriteMap;
173
import hudson.util.DaemonThreadFactory;
174
import hudson.util.DescribableList;
175
import hudson.util.FormApply;
176
import hudson.util.FormValidation;
177
import hudson.util.Futures;
178
import hudson.util.HudsonIsLoading;
179
import hudson.util.HudsonIsRestarting;
180
import hudson.util.Iterators;
181
import hudson.util.JenkinsReloadFailed;
182
import hudson.util.Memoizer;
183
import hudson.util.MultipartFormDataParser;
184
import hudson.util.RemotingDiagnostics;
185
import hudson.util.RemotingDiagnostics.HeapDump;
186
import hudson.util.StreamTaskListener;
187
import hudson.util.TextFile;
188
import hudson.util.TimeUnit2;
189
import hudson.util.VersionNumber;
190
import hudson.util.XStream2;
191
import hudson.views.DefaultMyViewsTabBar;
192
import hudson.views.DefaultViewsTabBar;
193
import hudson.views.MyViewsTabBar;
194
import hudson.views.ViewsTabBar;
195
import hudson.widgets.Widget;
196
import jenkins.ExtensionComponentSet;
197
import jenkins.ExtensionRefreshException;
198
import jenkins.InitReactorRunner;
199
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
200
import jenkins.security.ConfidentialKey;
201
import jenkins.security.ConfidentialStore;
202
import jenkins.util.io.FileBoolean;
203
import net.sf.json.JSONObject;
204
import org.acegisecurity.AccessDeniedException;
205
import org.acegisecurity.AcegiSecurityException;
206
import org.acegisecurity.Authentication;
207
import org.acegisecurity.GrantedAuthority;
208
import org.acegisecurity.GrantedAuthorityImpl;
209
import org.acegisecurity.context.SecurityContextHolder;
210
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
211
import org.acegisecurity.ui.AbstractProcessingFilter;
212
import org.apache.commons.jelly.JellyException;
213
import org.apache.commons.jelly.Script;
214
import org.apache.commons.logging.LogFactory;
215
import org.jvnet.hudson.reactor.Executable;
216
import org.jvnet.hudson.reactor.ReactorException;
217
import org.jvnet.hudson.reactor.Task;
218
import org.jvnet.hudson.reactor.TaskBuilder;
219
import org.jvnet.hudson.reactor.TaskGraphBuilder;
220
import org.jvnet.hudson.reactor.Reactor;
221
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
222
import org.kohsuke.accmod.Restricted;
223
import org.kohsuke.accmod.restrictions.NoExternalUse;
224
import org.kohsuke.args4j.Argument;
225
import org.kohsuke.args4j.Option;
226
import org.kohsuke.stapler.Ancestor;
227
import org.kohsuke.stapler.HttpRedirect;
228
import org.kohsuke.stapler.HttpResponse;
229
import org.kohsuke.stapler.HttpResponses;
230
import org.kohsuke.stapler.MetaClass;
231
import org.kohsuke.stapler.QueryParameter;
232
import org.kohsuke.stapler.Stapler;
233
import org.kohsuke.stapler.StaplerFallback;
234
import org.kohsuke.stapler.StaplerProxy;
235
import org.kohsuke.stapler.StaplerRequest;
236
import org.kohsuke.stapler.StaplerResponse;
237
import org.kohsuke.stapler.WebApp;
238
import org.kohsuke.stapler.export.Exported;
239
import org.kohsuke.stapler.export.ExportedBean;
240
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
241
import org.kohsuke.stapler.interceptor.RequirePOST;
242
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
243
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
244
import org.xml.sax.InputSource;
246
import javax.crypto.SecretKey;
247
import javax.servlet.RequestDispatcher;
248
import javax.servlet.ServletContext;
249
import javax.servlet.ServletException;
250
import javax.servlet.http.Cookie;
251
import javax.servlet.http.HttpServletResponse;
253
import static hudson.init.InitMilestone.*;
254
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
255
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
257
import java.io.FileFilter;
258
import java.io.IOException;
259
import java.io.InputStream;
260
import java.io.PrintWriter;
261
import java.io.StringWriter;
262
import java.net.BindException;
264
import java.nio.charset.Charset;
265
import java.security.SecureRandom;
266
import java.text.Collator;
267
import java.text.ParseException;
268
import java.util.ArrayList;
269
import java.util.Arrays;
270
import java.util.Collection;
271
import java.util.Collections;
272
import java.util.Comparator;
273
import java.util.HashMap;
274
import java.util.HashSet;
275
import java.util.Iterator;
276
import java.util.List;
277
import java.util.Map;
278
import java.util.Map.Entry;
279
import java.util.Properties;
280
import java.util.Set;
281
import java.util.Stack;
282
import java.util.StringTokenizer;
283
import java.util.Timer;
284
import java.util.TreeSet;
285
import java.util.UUID;
286
import java.util.concurrent.ConcurrentHashMap;
287
import java.util.concurrent.CopyOnWriteArrayList;
288
import java.util.concurrent.ExecutionException;
289
import java.util.concurrent.ExecutorService;
290
import java.util.concurrent.Future;
291
import java.util.concurrent.LinkedBlockingQueue;
292
import java.util.concurrent.ThreadPoolExecutor;
293
import java.util.concurrent.TimeUnit;
294
import java.util.concurrent.TimeoutException;
295
import java.util.logging.Level;
296
import static java.util.logging.Level.SEVERE;
297
import java.util.logging.LogRecord;
298
import java.util.logging.Logger;
299
import java.util.regex.Pattern;
300
import javax.annotation.CheckForNull;
303
* Root object of the system.
305
* @author Kohsuke Kawaguchi
308
public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu {
309
private transient final Queue queue;
312
* Stores various objects scoped to {@link Jenkins}.
314
public transient final Lookup lookup = new Lookup();
317
* We update this field to the current version of Hudson whenever we save {@code config.xml}.
318
* This can be used to detect when an upgrade happens from one version to next.
321
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
322
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
323
* "?", etc., so parsing needs to be done with a care.
327
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
328
private String version = "1.0";
331
* Number of executors of the master node.
333
private int numExecutors = 2;
336
* Job allocation strategy.
338
private Mode mode = Mode.NORMAL;
341
* False to enable anyone to do anything.
342
* Left as a field so that we can still read old data that uses this flag.
344
* @see #authorizationStrategy
345
* @see #securityRealm
347
private Boolean useSecurity;
351
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
352
* is handled in Hudson.
354
* This ultimately controls who has access to what.
358
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
361
* Controls a part of the
362
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
363
* handling in Hudson.
365
* Intuitively, this corresponds to the user database.
367
* See {@link HudsonFilter} for the concrete authentication protocol.
369
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
372
* @see #getSecurity()
373
* @see #setSecurityRealm(SecurityRealm)
375
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
378
* The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention?
380
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
383
* Root directory for the workspaces. This value will be variable-expanded against
384
* job name and JENKINS_HOME.
386
* @see #getWorkspaceFor(TopLevelItem)
388
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
391
* Root directory for the workspaces. This value will be variable-expanded against
392
* job name and JENKINS_HOME.
394
* @see #getBuildDirFor(Job)
396
private String buildsDir = "${ITEM_ROOTDIR}/builds";
399
* Message displayed in the top page.
401
private String systemMessage;
403
private MarkupFormatter markupFormatter;
406
* Root directory of the system.
408
public transient final File root;
411
* Where are we in the initialization?
413
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
416
* All {@link Item}s keyed by their {@link Item#getName() name}s.
418
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
423
private static Jenkins theInstance;
425
private transient volatile boolean isQuietingDown;
426
private transient volatile boolean terminating;
428
private List<JDK> jdks = new ArrayList<JDK>();
430
private transient volatile DependencyGraph dependencyGraph;
433
* Currently active Views tab bar.
435
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
438
* Currently active My Views tab bar.
440
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
443
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
445
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
446
public ExtensionList compute(Class key) {
447
return ExtensionList.create(Jenkins.this,key);
452
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
454
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
455
public DescriptorExtensionList compute(Class key) {
456
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
461
* {@link Computer}s in this Hudson system. Read-only.
463
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
466
* Active {@link Cloud}s.
468
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
470
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
471
public CloudList(Jenkins h) {
475
public CloudList() {// needed for XStream deserialization
478
public Cloud getByName(String name) {
480
if (c.name.equals(name))
486
protected void onModified() throws IOException {
488
Jenkins.getInstance().trimLabels();
493
* Set of installed cluster nodes.
495
* We use this field with copy-on-write semantics.
496
* This field has mutable list (to keep the serialization look clean),
497
* but it shall never be modified. Only new completely populated slave
498
* list can be set here.
500
* The field name should be really {@code nodes}, but again the backward compatibility
501
* prevents us from renaming.
503
protected volatile NodeList slaves;
508
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
510
/*package*/ Integer quietPeriod;
513
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
515
/*package*/ int scmCheckoutRetryCount;
520
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
523
* Name of the primary view.
525
* Start with null, so that we can upgrade pre-1.269 data well.
528
private volatile String primaryView;
530
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
531
protected List<View> views() { return views; }
532
protected String primaryView() { return primaryView; }
533
protected void primaryView(String name) { primaryView=name; }
537
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
542
public transient final PluginManager pluginManager;
544
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
546
private transient UDPBroadcastThread udpBroadcastThread;
548
private transient DNSMultiCast dnsMultiCast;
551
* List of registered {@link SCMListener}s.
553
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
556
* TCP slave agent port.
557
* 0 for random, -1 to disable.
559
private int slaveAgentPort =0;
562
* Whitespace-separated labels assigned to the master as a {@link Node}.
564
private String label="";
567
* {@link hudson.security.csrf.CrumbIssuer}
569
private volatile CrumbIssuer crumbIssuer;
572
* All labels known to Jenkins. This allows us to reuse the same label instances
573
* as much as possible, even though that's not a strict requirement.
575
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
578
* Load statistics of the entire system.
580
* This includes every executor and every job in the system.
583
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
586
* Load statistics of the free roaming jobs and slaves.
588
* This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
593
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
596
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
599
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
602
* @deprecated as of 1.467
603
* Use {@link #unlabeledNodeProvisioner}.
604
* This was broken because it was tracking all the executors in the system, but it was only tracking
605
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
606
* slaves and free-roaming jobs in the queue.
608
@Restricted(NoExternalUse.class)
609
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
612
public transient final ServletContext servletContext;
615
* Transient action list. Useful for adding navigation items to the navigation bar
618
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
621
* List of master node properties
623
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
626
* List of global properties
628
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
631
* {@link AdministrativeMonitor}s installed on this system.
633
* @see AdministrativeMonitor
635
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
640
private transient final List<Widget> widgets = getExtensionList(Widget.class);
643
* {@link AdjunctManager}
645
private transient final AdjunctManager adjuncts;
648
* Code that handles {@link ItemGroup} work.
650
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
652
protected void add(TopLevelItem item) {
653
items.put(item.getName(),item);
657
protected File getRootDirFor(String name) {
658
return Jenkins.this.getRootDirFor(name);
662
* Send the browser to the config page.
663
* use View to trim view/{default-view} from URL if possible
666
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
667
String redirect = result.getUrl()+"configure";
668
List<Ancestor> ancestors = req.getAncestors();
669
for (int i = ancestors.size() - 1; i >= 0; i--) {
670
Object o = ancestors.get(i).getObject();
671
if (o instanceof View) {
672
redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
682
* Hook for a test harness to intercept Jenkins.getInstance()
684
* Do not use in the production code as the signature may change.
686
public interface JenkinsHolder {
687
Jenkins getInstance();
690
static JenkinsHolder HOLDER = new JenkinsHolder() {
691
public Jenkins getInstance() {
697
public static Jenkins getInstance() {
698
return HOLDER.getInstance();
702
* Secret key generated once and used for a long time, beyond
703
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
704
* accidental exposure.
706
private transient final String secretKey;
708
private transient final UpdateCenter updateCenter = new UpdateCenter();
711
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
713
private Boolean noUsageStatistics;
716
* HTTP proxy configuration.
718
public transient volatile ProxyConfiguration proxy;
723
private transient final LogRecorderManager log = new LogRecorderManager();
725
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
726
this(root,context,null);
730
* @param pluginManager
731
* If non-null, use existing plugin manager. create a new one.
733
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SC_START_IN_CTOR") // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
734
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
735
long start = System.currentTimeMillis();
737
// As Jenkins is starting, grant this process full control
738
ACL.impersonate(ACL.SYSTEM);
741
this.servletContext = context;
742
computeVersion(context);
743
if(theInstance!=null)
744
throw new IllegalStateException("second instance");
747
if (!new File(root,"jobs").exists()) {
748
// if this is a fresh install, use more modern default layout that's consistent with slaves
749
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
752
// doing this early allows InitStrategy to set environment upfront
753
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
755
Trigger.timer = new Timer("Jenkins cron thread");
756
queue = new Queue(CONSISTENT_HASH?LoadBalancer.CONSISTENT_HASH:LoadBalancer.DEFAULT);
759
dependencyGraph = DependencyGraph.EMPTY;
760
} catch (InternalError e) {
761
if(e.getMessage().contains("window server")) {
762
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
767
// get or create the secret
768
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
769
if(secretFile.exists()) {
770
secretKey = secretFile.readTrim();
772
SecureRandom sr = new SecureRandom();
773
byte[] random = new byte[32];
774
sr.nextBytes(random);
775
secretKey = Util.toHexString(random);
776
secretFile.write(secretKey);
778
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
779
// this indicates that there's no need to rewrite secrets on disk
780
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
784
proxy = ProxyConfiguration.load();
785
} catch (IOException e) {
786
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
789
if (pluginManager==null)
790
pluginManager = new LocalPluginManager(this);
791
this.pluginManager = pluginManager;
792
// JSON binding needs to be able to see all the classes from all the plugins
793
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
795
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH);
797
// initialization consists of ...
799
pluginManager.initTasks(is), // loading and preparing plugins
800
loadTasks(), // load jobs
801
InitMilestone.ordering() // forced ordering among key milestones
807
if(slaveAgentPort!=-1) {
809
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
810
} catch (BindException e) {
811
new AdministrativeError(getClass().getName()+".tcpBind",
812
"Failed to listen to incoming slave connection",
813
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
816
tcpSlaveAgentListener = null;
819
udpBroadcastThread = new UDPBroadcastThread(this);
820
udpBroadcastThread.start();
821
} catch (IOException e) {
822
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP",e);
824
dnsMultiCast = new DNSMultiCast(this);
826
Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() {
828
protected void doRun() throws Exception {
831
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5));
833
updateComputerList();
835
{// master is online now
836
Computer c = toComputer();
838
for (ComputerListener cl : ComputerListener.all())
839
cl.onOnline(c,StreamTaskListener.fromStdout());
842
for (ItemListener l : ItemListener.all()) {
843
long itemListenerStart = System.currentTimeMillis();
845
if (LOG_STARTUP_PERFORMANCE)
846
LOGGER.info(String.format("Took %dms for item listener %s startup",
847
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
850
if (LOG_STARTUP_PERFORMANCE)
851
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
852
System.currentTimeMillis()-start));
854
SecurityContextHolder.clearContext();
859
* Executes a reactor.
862
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson.
864
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
865
Reactor reactor = new Reactor(builders) {
867
* Sets the thread name to the task for better diagnostics.
870
protected void runTask(Task task) throws Exception {
871
if (is!=null && is.skipInitTask(task)) return;
873
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
874
String taskName = task.getDisplayName();
876
Thread t = Thread.currentThread();
877
String name = t.getName();
881
long start = System.currentTimeMillis();
883
if(LOG_STARTUP_PERFORMANCE)
884
LOGGER.info(String.format("Took %dms for %s by %s",
885
System.currentTimeMillis()-start, taskName, name));
888
SecurityContextHolder.clearContext();
893
new InitReactorRunner() {
895
protected void onInitMilestoneAttained(InitMilestone milestone) {
896
initLevel = milestone;
902
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
903
return tcpSlaveAgentListener;
907
* Makes {@link AdjunctManager} URL-bound.
908
* The dummy parameter allows us to use different URLs for the same adjunct,
909
* for proper cache handling.
911
public AdjunctManager getAdjuncts(String dummy) {
916
public int getSlaveAgentPort() {
917
return slaveAgentPort;
922
* 0 to indicate random available TCP port. -1 to disable this service.
924
public void setSlaveAgentPort(int port) throws IOException {
925
this.slaveAgentPort = port;
927
// relaunch the agent
928
if(tcpSlaveAgentListener==null) {
929
if(slaveAgentPort!=-1)
930
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
932
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
933
tcpSlaveAgentListener.shutdown();
934
tcpSlaveAgentListener = null;
935
if(slaveAgentPort!=-1)
936
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
941
public void setNodeName(String name) {
942
throw new UnsupportedOperationException(); // not allowed
945
public String getNodeDescription() {
946
return Messages.Hudson_NodeDescription();
950
public String getDescription() {
951
return systemMessage;
954
public PluginManager getPluginManager() {
955
return pluginManager;
958
public UpdateCenter getUpdateCenter() {
962
public boolean isUsageStatisticsCollected() {
963
return noUsageStatistics==null || !noUsageStatistics;
966
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
967
this.noUsageStatistics = noUsageStatistics;
971
public View.People getPeople() {
972
return new View.People(this);
978
public View.AsynchPeople getAsynchPeople() {
979
return new View.AsynchPeople(this);
983
* Does this {@link View} has any associated user information recorded?
984
* @deprecated Potentially very expensive call; do not use from Jelly views.
986
public boolean hasPeople() {
987
return View.People.isApplicable(items.values());
990
public Api getApi() {
991
return new Api(this);
995
* Returns a secret key that survives across container start/stop.
997
* This value is useful for implementing some of the security features.
1000
* Due to the past security advisory, this value should not be used any more to protect sensitive information.
1001
* See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets.
1003
public String getSecretKey() {
1008
* Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128.
1011
* See {@link #getSecretKey()}.
1013
public SecretKey getSecretKeyAsAES128() {
1014
return Util.toAes128Key(secretKey);
1018
* Returns the unique identifier of this Jenkins that has been historically used to identify
1019
* this Jenkins to the outside world.
1022
* This form of identifier is weak in that it can be impersonated by others. See
1023
* https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID
1024
* that can be challenged and verified.
1028
@SuppressWarnings("deprecation")
1029
public String getLegacyInstanceId() {
1030
return Util.getDigestOf(getSecretKey());
1034
* Gets the SCM descriptor by name. Primarily used for making them web-visible.
1036
public Descriptor<SCM> getScm(String shortClassName) {
1037
return findDescriptor(shortClassName,SCM.all());
1041
* Gets the repository browser descriptor by name. Primarily used for making them web-visible.
1043
public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) {
1044
return findDescriptor(shortClassName,RepositoryBrowser.all());
1048
* Gets the builder descriptor by name. Primarily used for making them web-visible.
1050
public Descriptor<Builder> getBuilder(String shortClassName) {
1051
return findDescriptor(shortClassName, Builder.all());
1055
* Gets the build wrapper descriptor by name. Primarily used for making them web-visible.
1057
public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) {
1058
return findDescriptor(shortClassName, BuildWrapper.all());
1062
* Gets the publisher descriptor by name. Primarily used for making them web-visible.
1064
public Descriptor<Publisher> getPublisher(String shortClassName) {
1065
return findDescriptor(shortClassName, Publisher.all());
1069
* Gets the trigger descriptor by name. Primarily used for making them web-visible.
1071
public TriggerDescriptor getTrigger(String shortClassName) {
1072
return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all());
1076
* Gets the retention strategy descriptor by name. Primarily used for making them web-visible.
1078
public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) {
1079
return findDescriptor(shortClassName, RetentionStrategy.all());
1083
* Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible.
1085
public JobPropertyDescriptor getJobProperty(String shortClassName) {
1086
// combining these two lines triggers javac bug. See issue #610.
1087
Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all());
1088
return (JobPropertyDescriptor) d;
1093
* UI method. Not meant to be used programatically.
1095
public ComputerSet getComputer() {
1096
return new ComputerSet();
1100
* Exposes {@link Descriptor} by its name to URL.
1102
* After doing all the {@code getXXX(shortClassName)} methods, I finally realized that
1103
* this just doesn't scale.
1106
* Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility)
1108
public Descriptor getDescriptor(String id) {
1109
// legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly.
1110
for( Descriptor d : Iterators.sequence(getExtensionList(Descriptor.class),DescriptorExtensionList.listLegacyInstances()) ) {
1111
String name = d.getId();
1114
if(name.substring(name.lastIndexOf('.')+1).equals(id))
1121
* Alias for {@link #getDescriptor(String)}.
1123
public Descriptor getDescriptorByName(String id) {
1124
return getDescriptor(id);
1128
* Gets the {@link Descriptor} that corresponds to the given {@link Describable} type.
1130
* If you have an instance of {@code type} and call {@link Describable#getDescriptor()},
1131
* you'll get the same instance that this method returns.
1133
public Descriptor getDescriptor(Class<? extends Describable> type) {
1134
for( Descriptor d : getExtensionList(Descriptor.class) )
1141
* Works just like {@link #getDescriptor(Class)} but don't take no for an answer.
1143
* @throws AssertionError
1144
* If the descriptor is missing.
1147
public Descriptor getDescriptorOrDie(Class<? extends Describable> type) {
1148
Descriptor d = getDescriptor(type);
1150
throw new AssertionError(type+" is missing its descriptor");
1155
* Gets the {@link Descriptor} instance in the current Hudson by its type.
1157
public <T extends Descriptor> T getDescriptorByType(Class<T> type) {
1158
for( Descriptor d : getExtensionList(Descriptor.class) )
1159
if(d.getClass()==type)
1160
return type.cast(d);
1165
* Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible.
1167
public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) {
1168
return findDescriptor(shortClassName,SecurityRealm.all());
1172
* Finds a descriptor that has the specified name.
1174
private <T extends Describable<T>>
1175
Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) {
1176
String name = '.'+shortClassName;
1177
for (Descriptor<T> d : descriptors) {
1178
if(d.clazz.getName().endsWith(name))
1184
protected void updateComputerList() throws IOException {
1185
updateComputerList(AUTOMATIC_SLAVE_LAUNCH);
1189
* Gets all the installed {@link SCMListener}s.
1191
public CopyOnWriteList<SCMListener> getSCMListeners() {
1192
return scmListeners;
1196
* Gets the plugin object from its short name.
1199
* This allows URL <tt>hudson/plugin/ID</tt> to be served by the views
1200
* of the plugin class.
1202
public Plugin getPlugin(String shortName) {
1203
PluginWrapper p = pluginManager.getPlugin(shortName);
1204
if(p==null) return null;
1205
return p.getPlugin();
1209
* Gets the plugin object from its class.
1212
* This allows easy storage of plugin information in the plugin singleton without
1213
* every plugin reimplementing the singleton pattern.
1215
* @param clazz The plugin class (beware class-loader fun, this will probably only work
1216
* from within the jpi that defines the plugin class, it may or may not work in other cases)
1218
* @return The plugin instance.
1220
@SuppressWarnings("unchecked")
1221
public <P extends Plugin> P getPlugin(Class<P> clazz) {
1222
PluginWrapper p = pluginManager.getPlugin(clazz);
1223
if(p==null) return null;
1224
return (P) p.getPlugin();
1228
* Gets the plugin objects from their super-class.
1230
* @param clazz The plugin class (beware class-loader fun)
1232
* @return The plugin instances.
1234
public <P extends Plugin> List<P> getPlugins(Class<P> clazz) {
1235
List<P> result = new ArrayList<P>();
1236
for (PluginWrapper w: pluginManager.getPlugins(clazz)) {
1237
result.add((P)w.getPlugin());
1239
return Collections.unmodifiableList(result);
1243
* Synonym to {@link #getNodeDescription()}.
1245
public String getSystemMessage() {
1246
return systemMessage;
1250
* Gets the markup formatter used in the system.
1256
public MarkupFormatter getMarkupFormatter() {
1257
return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE;
1261
* Sets the markup formatter used in the system globally.
1265
public void setMarkupFormatter(MarkupFormatter f) {
1266
this.markupFormatter = f;
1270
* Sets the system message.
1272
public void setSystemMessage(String message) throws IOException {
1273
this.systemMessage = message;
1277
public FederatedLoginService getFederatedLoginService(String name) {
1278
for (FederatedLoginService fls : FederatedLoginService.all()) {
1279
if (fls.getUrlName().equals(name))
1285
public List<FederatedLoginService> getFederatedLoginServices() {
1286
return FederatedLoginService.all();
1289
public Launcher createLauncher(TaskListener listener) {
1290
return new LocalLauncher(listener).decorateFor(this);
1294
public String getFullName() {
1298
public String getFullDisplayName() {
1303
* Returns the transient {@link Action}s associated with the top page.
1306
* Adding {@link Action} is primarily useful for plugins to contribute
1307
* an item to the navigation bar of the top page. See existing {@link Action}
1308
* implementation for it affects the GUI.
1311
* To register an {@link Action}, implement {@link RootAction} extension point, or write code like
1312
* {@code Hudson.getInstance().getActions().add(...)}.
1315
* Live list where the changes can be made. Can be empty but never null.
1318
public List<Action> getActions() {
1323
* Gets just the immediate children of {@link Jenkins}.
1325
* @see #getAllItems(Class)
1327
@Exported(name="jobs")
1328
public List<TopLevelItem> getItems() {
1329
if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured ||
1330
authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
1331
return new ArrayList(items.values());
1334
List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>();
1335
for (TopLevelItem item : items.values()) {
1336
if (item.hasPermission(Item.READ))
1337
viewableItems.add(item);
1340
return viewableItems;
1344
* Returns the read-only view of all the {@link TopLevelItem}s keyed by their names.
1346
* This method is efficient, as it doesn't involve any copying.
1350
public Map<String,TopLevelItem> getItemMap() {
1351
return Collections.unmodifiableMap(items);
1355
* Gets just the immediate children of {@link Jenkins} but of the given type.
1357
public <T> List<T> getItems(Class<T> type) {
1358
List<T> r = new ArrayList<T>();
1359
for (TopLevelItem i : getItems())
1360
if (type.isInstance(i))
1361
r.add(type.cast(i));
1366
* Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
1367
* and filter them by the given type.
1369
public <T extends Item> List<T> getAllItems(Class<T> type) {
1370
List<T> r = new ArrayList<T>();
1372
Stack<ItemGroup> q = new Stack<ItemGroup>();
1375
while(!q.isEmpty()) {
1376
ItemGroup<?> parent = q.pop();
1377
for (Item i : parent.getItems()) {
1378
if(type.isInstance(i)) {
1379
if (i.hasPermission(Item.READ))
1380
r.add(type.cast(i));
1382
if(i instanceof ItemGroup)
1383
q.push((ItemGroup)i);
1391
* Gets all the items recursively.
1395
public List<Item> getAllItems() {
1396
return getAllItems(Item.class);
1400
* Gets a list of simple top-level projects.
1401
* @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders.
1402
* You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject},
1403
* perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s.
1404
* (That will also consider the caller's permissions.)
1405
* If you really want to get just {@link Project}s at top level, ignoring permissions,
1406
* you can filter the values from {@link #getItemMap} using {@link Util#createSubList}.
1409
public List<Project> getProjects() {
1410
return Util.createSubList(items.values(),Project.class);
1414
* Gets the names of all the {@link Job}s.
1416
public Collection<String> getJobNames() {
1417
List<String> names = new ArrayList<String>();
1418
for (Job j : getAllItems(Job.class))
1419
names.add(j.getFullName());
1423
public List<Action> getViewActions() {
1424
return getActions();
1428
* Gets the names of all the {@link TopLevelItem}s.
1430
public Collection<String> getTopLevelItemNames() {
1431
List<String> names = new ArrayList<String>();
1432
for (TopLevelItem j : items.values())
1433
names.add(j.getName());
1437
public View getView(String name) {
1438
return viewGroupMixIn.getView(name);
1442
* Gets the read-only list of all {@link View}s.
1445
public Collection<View> getViews() {
1446
return viewGroupMixIn.getViews();
1449
public void addView(View v) throws IOException {
1450
viewGroupMixIn.addView(v);
1453
public boolean canDelete(View view) {
1454
return viewGroupMixIn.canDelete(view);
1457
public synchronized void deleteView(View view) throws IOException {
1458
viewGroupMixIn.deleteView(view);
1461
public void onViewRenamed(View view, String oldName, String newName) {
1462
viewGroupMixIn.onViewRenamed(view,oldName,newName);
1466
* Returns the primary {@link View} that renders the top-page of Hudson.
1469
public View getPrimaryView() {
1470
return viewGroupMixIn.getPrimaryView();
1473
public void setPrimaryView(View v) {
1474
this.primaryView = v.getViewName();
1477
public ViewsTabBar getViewsTabBar() {
1481
public void setViewsTabBar(ViewsTabBar viewsTabBar) {
1482
this.viewsTabBar = viewsTabBar;
1485
public Jenkins getItemGroup() {
1489
public MyViewsTabBar getMyViewsTabBar() {
1490
return myViewsTabBar;
1493
public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) {
1494
this.myViewsTabBar = myViewsTabBar;
1498
* Returns true if the current running Hudson is upgraded from a version earlier than the specified version.
1501
* This method continues to return true until the system configuration is saved, at which point
1502
* {@link #version} will be overwritten and Hudson forgets the upgrade history.
1505
* To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version
1506
* equal or younger than N. So say if you implement a feature in 1.301 and you want to check
1507
* if the installation upgraded from pre-1.301, pass in "1.300.*"
1511
public boolean isUpgradedFromBefore(VersionNumber v) {
1513
return new VersionNumber(version).isOlderThan(v);
1514
} catch (IllegalArgumentException e) {
1515
// fail to parse this version number
1521
* Gets the read-only list of all {@link Computer}s.
1523
public Computer[] getComputers() {
1524
Computer[] r = computers.values().toArray(new Computer[computers.size()]);
1525
Arrays.sort(r,new Comparator<Computer>() {
1526
final Collator collator = Collator.getInstance();
1527
public int compare(Computer lhs, Computer rhs) {
1528
if(lhs.getNode()==Jenkins.this) return -1;
1529
if(rhs.getNode()==Jenkins.this) return 1;
1530
return collator.compare(lhs.getDisplayName(), rhs.getDisplayName());
1537
public Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") String name) {
1538
if(name.equals("(master)"))
1541
for (Computer c : computers.values()) {
1542
if(c.getName().equals(name))
1549
* Gets the label that exists on this system by the name.
1551
* @return null if name is null.
1552
* @see Label#parseExpression(String) (String)
1554
public Label getLabel(String expr) {
1555
if(expr==null) return null;
1557
Label l = labels.get(expr);
1563
labels.putIfAbsent(expr,Label.parseExpression(expr));
1564
} catch (ANTLRException e) {
1565
// laxly accept it as a single label atom for backward compatibility
1566
return getLabelAtom(expr);
1572
* Returns the label atom of the given name.
1574
public LabelAtom getLabelAtom(String name) {
1575
if (name==null) return null;
1578
Label l = labels.get(name);
1580
return (LabelAtom)l;
1583
LabelAtom la = new LabelAtom(name);
1584
if (labels.putIfAbsent(name, la)==null)
1590
* Gets all the active labels in the current system.
1592
public Set<Label> getLabels() {
1593
Set<Label> r = new TreeSet<Label>();
1594
for (Label l : labels.values()) {
1601
public Set<LabelAtom> getLabelAtoms() {
1602
Set<LabelAtom> r = new TreeSet<LabelAtom>();
1603
for (Label l : labels.values()) {
1604
if(!l.isEmpty() && l instanceof LabelAtom)
1605
r.add((LabelAtom)l);
1610
public Queue getQueue() {
1615
public String getDisplayName() {
1616
return Messages.Hudson_DisplayName();
1619
public List<JDK> getJDKs() {
1621
jdks = new ArrayList<JDK>();
1626
* Gets the JDK installation of the given name, or returns null.
1628
public JDK getJDK(String name) {
1630
// if only one JDK is configured, "default JDK" should mean that JDK.
1631
List<JDK> jdks = getJDKs();
1632
if(jdks.size()==1) return jdks.get(0);
1635
for (JDK j : getJDKs()) {
1636
if(j.getName().equals(name))
1645
* Gets the slave node of the give name, hooked under this Hudson.
1647
public Node getNode(String name) {
1648
return slaves.getNode(name);
1652
* Gets a {@link Cloud} by {@link Cloud#name its name}, or null.
1654
public Cloud getCloud(String name) {
1655
return clouds.getByName(name);
1658
protected Map<Node,Computer> getComputerMap() {
1663
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
1664
* represents the master.
1666
public List<Node> getNodes() {
1671
* Adds one more {@link Node} to Hudson.
1673
public synchronized void addNode(Node n) throws IOException {
1674
if(n==null) throw new IllegalArgumentException();
1675
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
1676
if(!nl.contains(n)) // defensive check
1682
* Removes a {@link Node} from Hudson.
1684
public synchronized void removeNode(Node n) throws IOException {
1685
Computer c = n.toComputer();
1687
c.disconnect(OfflineCause.create(Messages._Hudson_NodeBeingRemoved()));
1689
ArrayList<Node> nl = new ArrayList<Node>(this.slaves);
1694
public void setNodes(List<? extends Node> nodes) throws IOException {
1695
this.slaves = new NodeList(nodes);
1696
updateComputerList();
1701
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() {
1702
return nodeProperties;
1705
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() {
1706
return globalNodeProperties;
1710
* Resets all labels and remove invalid ones.
1712
* This should be called when the assumptions behind label cache computation changes,
1713
* but we also call this periodically to self-heal any data out-of-sync issue.
1715
private void trimLabels() {
1716
for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) {
1717
Label l = itr.next();
1725
* Binds {@link AdministrativeMonitor}s to URL.
1727
public AdministrativeMonitor getAdministrativeMonitor(String id) {
1728
for (AdministrativeMonitor m : administrativeMonitors)
1734
public NodeDescriptor getDescriptor() {
1735
return DescriptorImpl.INSTANCE;
1738
public static final class DescriptorImpl extends NodeDescriptor {
1740
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
1742
public String getDisplayName() {
1747
public boolean isInstantiable() {
1751
public FormValidation doCheckNumExecutors(@QueryParameter String value) {
1752
return FormValidation.validateNonNegativeInteger(value);
1755
// to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx
1756
public Object getDynamic(String token) {
1757
return Jenkins.getInstance().getDescriptor(token);
1762
* Gets the system default quiet period.
1764
public int getQuietPeriod() {
1765
return quietPeriod!=null ? quietPeriod : 5;
1769
* Sets the global quiet period.
1771
* @param quietPeriod
1772
* null to the default value.
1774
public void setQuietPeriod(Integer quietPeriod) throws IOException {
1775
this.quietPeriod = quietPeriod;
1780
* Gets the global SCM check out retry count.
1782
public int getScmCheckoutRetryCount() {
1783
return scmCheckoutRetryCount;
1786
public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException {
1787
this.scmCheckoutRetryCount = scmCheckoutRetryCount;
1792
public String getSearchUrl() {
1797
public SearchIndexBuilder makeSearchIndex() {
1798
return super.makeSearchIndex()
1799
.add("configure", "config","configure")
1802
.add(new CollectionSearchIndex<TopLevelItem>() {
1803
protected SearchItem get(String key) { return getItem(key); }
1804
protected Collection<TopLevelItem> all() { return getItems(); }
1806
.add(getPrimaryView().makeSearchIndex())
1807
.add(new CollectionSearchIndex() {// for computers
1808
protected Computer get(String key) { return getComputer(key); }
1809
protected Collection<Computer> all() { return computers.values(); }
1811
.add(new CollectionSearchIndex() {// for users
1812
protected User get(String key) { return User.get(key,false); }
1813
protected Collection<User> all() { return User.getAll(); }
1815
.add(new CollectionSearchIndex() {// for views
1816
protected View get(String key) { return getView(key); }
1817
protected Collection<View> all() { return views; }
1821
public String getUrlChildPrefix() {
1826
* Gets the absolute URL of Jenkins,
1827
* such as "http://localhost/jenkins/".
1830
* This method first tries to use the manually configured value, then
1831
* fall back to {@link StaplerRequest#getRootPath()}.
1832
* It is done in this order so that it can work correctly even in the face
1833
* of a reverse proxy.
1836
* This method returns null if this parameter is not configured by the user.
1837
* The caller must gracefully deal with this situation.
1838
* The returned URL will always have the trailing '/'.
1840
* @see Descriptor#getCheckUrl(String)
1841
* @see #getRootUrlFromRequest()
1843
public String getRootUrl() {
1844
// for compatibility. the actual data is stored in Mailer
1845
String url = Mailer.descriptor().getUrl();
1847
if (!url.endsWith("/")) url += '/';
1851
StaplerRequest req = Stapler.getCurrentRequest();
1853
return getRootUrlFromRequest();
1858
* Is Jenkins running in HTTPS?
1860
* Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated
1861
* in the reverse proxy.
1863
public boolean isRootUrlSecure() {
1864
String url = getRootUrl();
1865
return url!=null && url.startsWith("https");
1869
* Gets the absolute URL of Hudson top page, such as "http://localhost/hudson/".
1872
* Unlike {@link #getRootUrl()}, which uses the manually configured value,
1873
* this one uses the current request to reconstruct the URL. The benefit is
1874
* that this is immune to the configuration mistake (users often fail to set the root URL
1875
* correctly, especially when a migration is involved), but the downside
1876
* is that unless you are processing a request, this method doesn't work.
1878
* Please note that this will not work in all cases if Jenkins is running behind a
1879
* reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is
1880
* default setup or the actual url uses https) and you should use getRootUrl if
1881
* you want to be sure you reflect user setup.
1882
* See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache
1886
public String getRootUrlFromRequest() {
1887
StaplerRequest req = Stapler.getCurrentRequest();
1888
StringBuilder buf = new StringBuilder();
1889
buf.append(req.getScheme()+"://");
1890
buf.append(req.getServerName());
1891
if(req.getServerPort()!=80)
1892
buf.append(':').append(req.getServerPort());
1893
buf.append(req.getContextPath()).append('/');
1894
return buf.toString();
1897
public File getRootDir() {
1901
public FilePath getWorkspaceFor(TopLevelItem item) {
1902
return new FilePath(expandVariablesForDirectory(workspaceDir, item));
1905
public File getBuildDirFor(Job job) {
1906
return expandVariablesForDirectory(buildsDir, job);
1909
private File expandVariablesForDirectory(String base, Item item) {
1910
return new File(Util.replaceMacro(base, ImmutableMap.of(
1911
"JENKINS_HOME", getRootDir().getPath(),
1912
"ITEM_ROOTDIR", item.getRootDir().getPath(),
1913
"ITEM_FULLNAME", item.getFullName())));
1916
public String getRawWorkspaceDir() {
1917
return workspaceDir;
1920
public String getRawBuildsDir() {
1924
public FilePath getRootPath() {
1925
return new FilePath(getRootDir());
1929
public FilePath createPath(String absolutePath) {
1930
return new FilePath((VirtualChannel)null,absolutePath);
1933
public ClockDifference getClockDifference() {
1934
return ClockDifference.ZERO;
1938
* For binding {@link LogRecorderManager} to "/log".
1939
* Everything below here is admin-only, so do the check here.
1941
public LogRecorderManager getLog() {
1942
checkPermission(ADMINISTER);
1947
* A convenience method to check if there's some security
1948
* restrictions in place.
1951
public boolean isUseSecurity() {
1952
return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED;
1955
public boolean isUseProjectNamingStrategy(){
1956
return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
1960
* If true, all the POST requests to Hudson would have to have crumb in it to protect
1961
* Hudson from CSRF vulnerabilities.
1964
public boolean isUseCrumbs() {
1965
return crumbIssuer!=null;
1969
* Returns the constant that captures the three basic security modes
1972
public SecurityMode getSecurity() {
1973
// fix the variable so that this code works under concurrent modification to securityRealm.
1974
SecurityRealm realm = securityRealm;
1976
if(realm==SecurityRealm.NO_AUTHENTICATION)
1977
return SecurityMode.UNSECURED;
1978
if(realm instanceof LegacySecurityRealm)
1979
return SecurityMode.LEGACY;
1980
return SecurityMode.SECURED;
1987
public SecurityRealm getSecurityRealm() {
1988
return securityRealm;
1991
public void setSecurityRealm(SecurityRealm securityRealm) {
1992
if(securityRealm==null)
1993
securityRealm= SecurityRealm.NO_AUTHENTICATION;
1994
this.useSecurity = true;
1995
this.securityRealm = securityRealm;
1996
// reset the filters and proxies for the new SecurityRealm
1998
HudsonFilter filter = HudsonFilter.get(servletContext);
1999
if (filter == null) {
2000
// Fix for #3069: This filter is not necessarily initialized before the servlets.
2001
// when HudsonFilter does come back, it'll initialize itself.
2002
LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now");
2004
LOGGER.fine("HudsonFilter has been previously initialized: Setting security up");
2005
filter.reset(securityRealm);
2006
LOGGER.fine("Security is now fully set up");
2008
} catch (ServletException e) {
2009
// for binary compatibility, this method cannot throw a checked exception
2010
throw new AcegiSecurityException("Failed to configure filter",e) {};
2014
public void setAuthorizationStrategy(AuthorizationStrategy a) {
2016
a = AuthorizationStrategy.UNSECURED;
2018
authorizationStrategy = a;
2021
public void disableSecurity() {
2023
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2024
authorizationStrategy = AuthorizationStrategy.UNSECURED;
2025
markupFormatter = null;
2028
public void setProjectNamingStrategy(ProjectNamingStrategy ns) {
2030
ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
2032
projectNamingStrategy = ns;
2035
public Lifecycle getLifecycle() {
2036
return Lifecycle.get();
2040
* Gets the dependency injection container that hosts all the extension implementations and other
2041
* components in Jenkins.
2045
public Injector getInjector() {
2046
return lookup(Injector.class);
2050
* Returns {@link ExtensionList} that retains the discovered instances for the given extension type.
2052
* @param extensionType
2053
* The base type that represents the extension point. Normally {@link ExtensionPoint} subtype
2054
* but that's not a hard requirement.
2056
* Can be an empty list but never null.
2058
@SuppressWarnings({"unchecked"})
2059
public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) {
2060
return extensionLists.get(extensionType);
2064
* Used to bind {@link ExtensionList}s to URLs.
2068
public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException {
2069
return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType));
2073
* Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given
2074
* kind of {@link Describable}.
2077
* Can be an empty list but never null.
2079
@SuppressWarnings({"unchecked"})
2080
public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) {
2081
return descriptorLists.get(type);
2085
* Refresh {@link ExtensionList}s by adding all the newly discovered extensions.
2087
* Exposed only for {@link PluginManager#dynamicLoad(File)}.
2089
public void refreshExtensions() throws ExtensionRefreshException {
2090
ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class);
2091
for (ExtensionFinder ef : finders) {
2092
if (!ef.isRefreshable())
2093
throw new ExtensionRefreshException(ef+" doesn't support refresh");
2096
List<ExtensionComponentSet> fragments = Lists.newArrayList();
2097
for (ExtensionFinder ef : finders) {
2098
fragments.add(ef.refresh());
2100
ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered();
2102
// if we find a new ExtensionFinder, we need it to list up all the extension points as well
2103
List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class));
2104
while (!newFinders.isEmpty()) {
2105
ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance();
2107
ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered();
2108
newFinders.addAll(ecs.find(ExtensionFinder.class));
2109
delta = ExtensionComponentSet.union(delta, ecs);
2112
for (ExtensionList el : extensionLists.values()) {
2115
for (ExtensionList el : descriptorLists.values()) {
2119
// TODO: we need some generalization here so that extension points can be notified when a refresh happens?
2120
for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) {
2121
Action a = ea.getInstance();
2122
if (!actions.contains(a)) actions.add(a);
2127
* Returns the root {@link ACL}.
2129
* @see AuthorizationStrategy#getRootACL()
2132
public ACL getACL() {
2133
return authorizationStrategy.getRootACL();
2140
public AuthorizationStrategy getAuthorizationStrategy() {
2141
return authorizationStrategy;
2145
* The strategy used to check the project names.
2146
* @return never <code>null</code>
2148
public ProjectNamingStrategy getProjectNamingStrategy() {
2149
return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy;
2153
* Returns true if Hudson is quieting down.
2155
* No further jobs will be executed unless it
2156
* can be finished while other current pending builds
2157
* are still in progress.
2160
public boolean isQuietingDown() {
2161
return isQuietingDown;
2165
* Returns true if the container initiated the termination of the web application.
2167
public boolean isTerminating() {
2172
* Gets the initialization milestone that we've already reached.
2175
* {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method
2176
* never returns null.
2178
public InitMilestone getInitLevel() {
2182
public void setNumExecutors(int n) throws IOException {
2183
this.numExecutors = n;
2192
* Note that the look up is case-insensitive.
2194
public TopLevelItem getItem(String name) {
2195
if (name==null) return null;
2196
TopLevelItem item = items.get(name);
2199
if (!item.hasPermission(Item.READ)) {
2200
if (item.hasPermission(Item.DISCOVER)) {
2201
throw new AccessDeniedException("Please login to access job " + name);
2209
* Gets the item by its path name from the given context
2211
* <h2>Path Names</h2>
2213
* If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute.
2214
* Otherwise, the name should be something like "foo/bar" and it's interpreted like
2215
* relative path name in the file system is, against the given context.
2218
* null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation.
2221
public Item getItem(String pathName, ItemGroup context) {
2222
if (context==null) context = this;
2223
if (pathName==null) return null;
2225
if (pathName.startsWith("/")) // absolute
2226
return getItemByFullName(pathName);
2228
Object/*Item|ItemGroup*/ ctx = context;
2230
StringTokenizer tokens = new StringTokenizer(pathName,"/");
2231
while (tokens.hasMoreTokens()) {
2232
String s = tokens.nextToken();
2233
if (s.equals("..")) {
2234
if (ctx instanceof Item) {
2235
ctx = ((Item)ctx).getParent();
2239
ctx=null; // can't go up further
2242
if (s.equals(".")) {
2246
if (ctx instanceof ItemGroup) {
2247
ItemGroup g = (ItemGroup) ctx;
2248
Item i = g.getItem(s);
2249
if (i==null || !i.hasPermission(Item.READ)) {
2250
ctx=null; // can't go up further
2259
if (ctx instanceof Item)
2262
// fall back to the classic interpretation
2263
return getItemByFullName(pathName);
2266
public final Item getItem(String pathName, Item context) {
2267
return getItem(pathName,context!=null?context.getParent():null);
2270
public final <T extends Item> T getItem(String pathName, ItemGroup context, Class<T> type) {
2271
Item r = getItem(pathName, context);
2272
if (type.isInstance(r))
2273
return type.cast(r);
2277
public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) {
2278
return getItem(pathName,context!=null?context.getParent():null,type);
2281
public File getRootDirFor(TopLevelItem child) {
2282
return getRootDirFor(child.getName());
2285
private File getRootDirFor(String name) {
2286
return new File(new File(getRootDir(),"jobs"), name);
2290
* Gets the {@link Item} object by its full name.
2291
* Full names are like path names, where each name of {@link Item} is
2295
* null if either such {@link Item} doesn't exist under the given full name,
2296
* or it exists but it's no an instance of the given type.
2298
public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) {
2299
StringTokenizer tokens = new StringTokenizer(fullName,"/");
2300
ItemGroup parent = this;
2302
if(!tokens.hasMoreTokens()) return null; // for example, empty full name.
2305
Item item = parent.getItem(tokens.nextToken());
2306
if(!tokens.hasMoreTokens()) {
2307
if(type.isInstance(item))
2308
return type.cast(item);
2313
if(!(item instanceof ItemGroup))
2314
return null; // this item can't have any children
2316
if (!item.hasPermission(Item.READ))
2319
parent = (ItemGroup) item;
2323
public @CheckForNull Item getItemByFullName(String fullName) {
2324
return getItemByFullName(fullName,Item.class);
2328
* Gets the user of the given name.
2330
* @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null
2331
* @see User#get(String,boolean)
2333
public @CheckForNull User getUser(String name) {
2334
return User.get(name,hasPermission(ADMINISTER));
2337
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {
2338
return createProject(type, name, true);
2341
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException {
2342
return itemGroupMixIn.createProject(type,name,notify);
2346
* Overwrites the existing item by new one.
2349
* This is a short cut for deleting an existing job and adding a new one.
2351
public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException {
2352
String name = item.getName();
2353
TopLevelItem old = items.get(name);
2354
if (old ==item) return; // noop
2356
checkPermission(Item.CREATE);
2359
items.put(name,item);
2360
ItemListener.fireOnCreated(item);
2364
* Creates a new job.
2367
* This version infers the descriptor from the type of the top-level item.
2369
* @throws IllegalArgumentException
2370
* if the project of the given name already exists.
2372
public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException {
2373
return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name));
2377
* Called by {@link Job#renameTo(String)} to update relevant data structure.
2378
* assumed to be synchronized on Hudson by the caller.
2380
public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException {
2381
items.remove(oldName);
2382
items.put(newName,job);
2384
for (View v : views)
2385
v.onJobRenamed(job, oldName, newName);
2390
* Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)}
2392
public void onDeleted(TopLevelItem item) throws IOException {
2393
for (ItemListener l : ItemListener.all())
2396
items.remove(item.getName());
2397
for (View v : views)
2398
v.onJobRenamed(item, item.getName(), null);
2402
public FingerprintMap getFingerprintMap() {
2403
return fingerprintMap;
2406
// if no finger print matches, display "not found page".
2407
public Object getFingerprint( String md5sum ) throws IOException {
2408
Fingerprint r = fingerprintMap.get(md5sum);
2409
if(r==null) return new NoFingerprintMatch(md5sum);
2414
* Gets a {@link Fingerprint} object if it exists.
2417
public Fingerprint _getFingerprint( String md5sum ) throws IOException {
2418
return fingerprintMap.get(md5sum);
2422
* The file we save our configuration.
2424
private XmlFile getConfigFile() {
2425
return new XmlFile(XSTREAM, new File(root,"config.xml"));
2428
public int getNumExecutors() {
2429
return numExecutors;
2432
public Mode getMode() {
2436
public void setMode(Mode m) throws IOException {
2441
public String getLabelString() {
2442
return fixNull(label).trim();
2446
public void setLabelString(String label) throws IOException {
2452
public LabelAtom getSelfLabel() {
2453
return getLabelAtom("master");
2456
public Computer createComputer() {
2457
return new Hudson.MasterComputer();
2460
private synchronized TaskBuilder loadTasks() throws IOException {
2461
File projectsDir = new File(root,"jobs");
2462
if(!projectsDir.isDirectory() && !projectsDir.mkdirs()) {
2463
if(projectsDir.exists())
2464
throw new IOException(projectsDir+" is not a directory");
2465
throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually.");
2467
File[] subdirs = projectsDir.listFiles(new FileFilter() {
2468
public boolean accept(File child) {
2469
return child.isDirectory() && Items.getConfigFile(child).exists();
2473
TaskGraphBuilder g = new TaskGraphBuilder();
2474
Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() {
2475
public void run(Reactor session) throws Exception {
2476
// JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file
2477
// and will get overwritten when reloading. Make a backup copy now, and re-add them later
2478
NodeList oldSlaves = slaves;
2480
XmlFile cfg = getConfigFile();
2482
// reset some data that may not exist in the disk file
2483
// so that we can take a proper compensation action later.
2488
cfg.unmarshal(Jenkins.this);
2491
// if we are loading old data that doesn't have this field
2492
if (slaves == null) slaves = new NodeList();
2494
clouds.setOwner(Jenkins.this);
2497
// JENKINS-8043: re-add the slaves which were not saved into the config file
2498
// and are now missing, but still connected.
2499
if (oldSlaves != null) {
2500
ArrayList<Node> newSlaves = new ArrayList<Node>(slaves);
2501
for (Node n: oldSlaves) {
2502
if (n instanceof EphemeralNode) {
2503
if(!newSlaves.contains(n)) {
2508
setNodes(newSlaves);
2513
for (final File subdir : subdirs) {
2514
g.requires(loadHudson).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() {
2515
public void run(Reactor session) throws Exception {
2516
TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir);
2517
items.put(item.getName(), item);
2522
g.requires(JOB_LOADED).add("Finalizing set up",new Executable() {
2523
public void run(Reactor session) throws Exception {
2524
rebuildDependencyGraph();
2526
{// recompute label objects - populates the labels mapping.
2527
for (Node slave : slaves)
2528
// Note that not all labels are visible until the slaves have connected.
2529
slave.getAssignedLabels();
2530
getAssignedLabels();
2533
// initialize views by inserting the default view if necessary
2534
// this is both for clean Hudson and for backward compatibility.
2535
if(views.size()==0 || primaryView==null) {
2536
View v = new AllView(Messages.Hudson_ViewName());
2539
primaryView = v.getViewName();
2542
// read in old data that doesn't have the security field set
2543
if(authorizationStrategy==null) {
2544
if(useSecurity==null || !useSecurity)
2545
authorizationStrategy = AuthorizationStrategy.UNSECURED;
2547
authorizationStrategy = new LegacyAuthorizationStrategy();
2549
if(securityRealm==null) {
2550
if(useSecurity==null || !useSecurity)
2551
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2553
setSecurityRealm(new LegacySecurityRealm());
2555
// force the set to proxy
2556
setSecurityRealm(securityRealm);
2559
if(useSecurity!=null && !useSecurity) {
2560
// forced reset to the unsecure mode.
2561
// this works as an escape hatch for people who locked themselves out.
2562
authorizationStrategy = AuthorizationStrategy.UNSECURED;
2563
setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
2566
// Initialize the filter with the crumb issuer
2567
setCrumbIssuer(crumbIssuer);
2569
// auto register root actions
2570
for (Action a : getExtensionList(RootAction.class))
2571
if (!actions.contains(a)) actions.add(a);
2579
* Save the settings to a file.
2581
public synchronized void save() throws IOException {
2582
if(BulkChange.contains(this)) return;
2583
getConfigFile().write(this);
2584
SaveableListener.fireOnChange(this, getConfigFile());
2589
* Called to shut down the system.
2591
public void cleanUp() {
2592
for (ItemListener l : ItemListener.all())
2593
l.onBeforeShutdown();
2595
Set<Future<?>> pending = new HashSet<Future<?>>();
2597
for( Computer c : computers.values() ) {
2600
pending.add(c.disconnect(null));
2602
if(udpBroadcastThread!=null)
2603
udpBroadcastThread.shutdown();
2604
if(dnsMultiCast!=null)
2605
dnsMultiCast.close();
2606
interruptReloadThread();
2607
Trigger.timer.cancel();
2608
// TODO: how to wait for the completion of the last job?
2609
Trigger.timer = null;
2610
if(tcpSlaveAgentListener!=null)
2611
tcpSlaveAgentListener.shutdown();
2613
if(pluginManager!=null) // be defensive. there could be some ugly timing related issues
2614
pluginManager.stop();
2616
if(getRootDir().exists())
2617
// if we are aborting because we failed to create JENKINS_HOME,
2618
// don't try to save. Issue #536
2621
threadPoolForLoad.shutdown();
2622
for (Future<?> f : pending)
2624
f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test
2625
} catch (InterruptedException e) {
2626
Thread.currentThread().interrupt();
2627
break; // someone wants us to die now. quick!
2628
} catch (ExecutionException e) {
2629
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
2630
} catch (TimeoutException e) {
2631
LOGGER.log(Level.WARNING, "Failed to shut down properly",e);
2634
LogFactory.releaseAll();
2639
public Object getDynamic(String token) {
2640
for (Action a : getActions()) {
2641
String url = a.getUrlName();
2642
if (url==null) continue;
2643
if (url.equals(token) || url.equals('/' + token))
2646
for (Action a : getManagementLinks())
2647
if(a.getUrlName().equals(token))
2659
* Accepts submission from the configuration page.
2661
public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
2662
BulkChange bc = new BulkChange(this);
2664
checkPermission(ADMINISTER);
2666
JSONObject json = req.getSubmittedForm();
2668
workspaceDir = json.getString("rawWorkspaceDir");
2669
buildsDir = json.getString("rawBuildsDir");
2671
systemMessage = Util.nullify(req.getParameter("system_message"));
2674
jdks.addAll(req.bindJSONToList(JDK.class,json.get("jdks")));
2676
boolean result = true;
2677
for( Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfig() )
2678
result &= configureDescriptor(req,json,d);
2683
updateComputerList();
2685
FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null);
2687
FormApply.success("configure").generateResponse(req, rsp, null); // back to config
2694
* Gets the {@link CrumbIssuer} currently in use.
2696
* @return null if none is in use.
2698
public CrumbIssuer getCrumbIssuer() {
2702
public void setCrumbIssuer(CrumbIssuer issuer) {
2703
crumbIssuer = issuer;
2706
public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2707
rsp.sendRedirect("foo");
2710
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
2711
// collapse the structure to remain backward compatible with the JSON structure before 1.
2712
String name = d.getJsonSafeClassName();
2713
JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object.
2715
return d.configure(req, js);
2719
* Accepts submission from the node configuration page.
2721
public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
2722
checkPermission(ADMINISTER);
2724
BulkChange bc = new BulkChange(this);
2726
JSONObject json = req.getSubmittedForm();
2728
MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class);
2730
mbc.configure(req,json);
2732
getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all());
2737
rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page
2741
* Accepts the new description.
2743
public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2744
getPrimaryView().doSubmitDescription(req, rsp);
2747
public synchronized HttpRedirect doQuietDown() throws IOException {
2749
return doQuietDown(false,0);
2750
} catch (InterruptedException e) {
2751
throw new AssertionError(); // impossible
2755
@CLIMethod(name="quiet-down")
2756
public HttpRedirect doQuietDown(
2757
@Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block,
2758
@Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException {
2759
synchronized (this) {
2760
checkPermission(ADMINISTER);
2761
isQuietingDown = true;
2764
if (timeout > 0) timeout += System.currentTimeMillis();
2765
while (isQuietingDown
2766
&& (timeout <= 0 || System.currentTimeMillis() < timeout)
2767
&& !RestartListener.isAllReady()) {
2771
return new HttpRedirect(".");
2774
@CLIMethod(name="cancel-quiet-down")
2775
public synchronized HttpRedirect doCancelQuietDown() {
2776
checkPermission(ADMINISTER);
2777
isQuietingDown = false;
2778
getQueue().scheduleMaintenance();
2779
return new HttpRedirect(".");
2783
* Backward compatibility. Redirect to the thread dump.
2785
public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException {
2786
rsp.sendRedirect2("threadDump");
2790
* Obtains the thread dump of all slaves (including the master.)
2793
* Since this is for diagnostics, it has a built-in precautionary measure against hang slaves.
2795
public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException {
2796
checkPermission(ADMINISTER);
2798
// issue the requests all at once
2799
Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>();
2801
for (Computer c : getComputers()) {
2802
future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel()));
2804
if (toComputer() == null) {
2805
future.put("master", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel));
2808
// if the result isn't available in 5 sec, ignore that.
2809
// this is a precaution against hang nodes
2810
long endTime = System.currentTimeMillis() + 5000;
2812
Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>();
2813
for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) {
2815
r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS));
2816
} catch (Exception x) {
2817
StringWriter sw = new StringWriter();
2818
x.printStackTrace(new PrintWriter(sw,true));
2819
r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString()));
2825
public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2826
return itemGroupMixIn.createTopLevelItem(req, rsp);
2832
public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
2833
return itemGroupMixIn.createProjectFromXML(name, xml);
2837
@SuppressWarnings({"unchecked"})
2838
public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
2839
return itemGroupMixIn.copy(src, name);
2842
// a little more convenient overloading that assumes the caller gives us the right type
2843
// (or else it will fail with ClassCastException)
2844
public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException {
2845
return (T)copy((TopLevelItem)src,name);
2848
public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
2849
checkPermission(View.CREATE);
2850
addView(View.create(req,rsp, this));
2854
* Check if the given name is suitable as a name
2855
* for job, view, etc.
2857
* @throws ParseException
2858
* if the given name is not good
2860
public static void checkGoodName(String name) throws Failure {
2861
if(name==null || name.length()==0)
2862
throw new Failure(Messages.Hudson_NoName());
2864
for( int i=0; i<name.length(); i++ ) {
2865
char ch = name.charAt(i);
2866
if(Character.isISOControl(ch)) {
2867
throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name)));
2869
if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1)
2870
throw new Failure(Messages.Hudson_UnsafeChar(ch));
2877
* Makes sure that the given name is good as a job name.
2878
* @return trimmed name if valid; throws ParseException if not
2880
private String checkJobName(String name) throws Failure {
2881
checkGoodName(name);
2883
projectNamingStrategy.checkName(name);
2884
if(getItem(name)!=null)
2885
throw new Failure(Messages.Hudson_JobAlreadyExists(name));
2890
private static String toPrintableName(String name) {
2891
StringBuilder printableName = new StringBuilder();
2892
for( int i=0; i<name.length(); i++ ) {
2893
char ch = name.charAt(i);
2894
if(Character.isISOControl(ch))
2895
printableName.append("\\u").append((int)ch).append(';');
2897
printableName.append(ch);
2899
return printableName.toString();
2903
* Checks if the user was successfully authenticated.
2905
* @see BasicAuthenticationFilter
2907
public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2908
if(req.getUserPrincipal()==null) {
2909
// authentication must have failed
2910
rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
2914
// the user is now authenticated, so send him back to the target
2915
String path = req.getContextPath()+req.getOriginalRestOfPath();
2916
String q = req.getQueryString();
2920
rsp.sendRedirect2(path);
2924
* Called once the user logs in. Just forward to the top page.
2926
public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException {
2927
if(req.getUserPrincipal()==null) {
2928
rsp.sendRedirect2("noPrincipal");
2932
String from = req.getParameter("from");
2933
if(from!=null && from.startsWith("/") && !from.equals("/loginError")) {
2934
rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain
2938
String url = AbstractProcessingFilter.obtainFullRequestUrl(req);
2940
// if the login redirect is initiated by Acegi
2941
// this should send the user back to where s/he was from.
2942
rsp.sendRedirect2(url);
2946
rsp.sendRedirect2(".");
2950
* Logs out the user.
2952
public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
2953
securityRealm.doLogout(req, rsp);
2957
* Serves jar files for JNLP slave agents.
2959
public Slave.JnlpJar getJnlpJars(String fileName) {
2960
return new Slave.JnlpJar(fileName);
2963
public Slave.JnlpJar doJnlpJars(StaplerRequest req) {
2964
return new Slave.JnlpJar(req.getRestOfPath().substring(1));
2968
* Reloads the configuration.
2970
@CLIMethod(name="reload-configuration")
2971
public synchronized HttpResponse doReload() throws IOException {
2972
checkPermission(ADMINISTER);
2974
// engage "loading ..." UI and then run the actual task in a separate thread
2975
servletContext.setAttribute("app", new HudsonIsLoading());
2977
new Thread("Jenkins config reload thread") {
2981
ACL.impersonate(ACL.SYSTEM);
2983
} catch (Exception e) {
2984
LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
2985
WebApp.get(servletContext).setApp(new JenkinsReloadFailed(e));
2990
return HttpResponses.redirectViaContextPath("/");
2994
* Reloads the configuration synchronously.
2996
public void reload() throws IOException, InterruptedException, ReactorException {
2997
executeReactor(null, loadTasks());
2999
servletContext.setAttribute("app", this);
3003
* Do a finger-print check.
3005
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
3006
// Parse the request
3007
MultipartFormDataParser p = new MultipartFormDataParser(req);
3008
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
3009
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
3012
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
3013
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
3020
* For debugging. Expose URL to perform GC.
3022
@edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC")
3023
public void doGc(StaplerResponse rsp) throws IOException {
3024
checkPermission(Jenkins.ADMINISTER);
3026
rsp.setStatus(HttpServletResponse.SC_OK);
3027
rsp.setContentType("text/plain");
3028
rsp.getWriter().println("GCed");
3032
* End point that intentionally throws an exception to test the error behaviour.
3034
public void doException() {
3035
throw new RuntimeException();
3038
public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException {
3039
ContextMenu menu = new ContextMenu().from(this, request, response);
3040
for (MenuItem i : menu.items) {
3041
if (i.url.equals("/manage")) {
3042
// add "Manage Jenkins" subitems
3043
i.subMenu = new ContextMenu().from(this, request, response, "manage");
3050
* Obtains the heap dump.
3052
public HeapDump getHeapDump() throws IOException {
3053
return new HeapDump(this,MasterComputer.localChannel);
3057
* Simulates OutOfMemoryError.
3058
* Useful to make sure OutOfMemoryHeapDump setting.
3060
public void doSimulateOutOfMemory() throws IOException {
3061
checkPermission(ADMINISTER);
3063
System.out.println("Creating artificial OutOfMemoryError situation");
3064
List<Object> args = new ArrayList<Object>();
3066
args.add(new byte[1024*1024]);
3069
private transient final Map<UUID,FullDuplexHttpChannel> duplexChannels = new HashMap<UUID, FullDuplexHttpChannel>();
3072
* Handles HTTP requests for duplex channels for CLI.
3074
public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {
3075
if (!"POST".equals(req.getMethod())) {
3076
// for GET request, serve _cli.jelly, assuming this is a browser
3077
checkPermission(READ);
3078
req.getView(this,"_cli.jelly").forward(req,rsp);
3082
// do not require any permission to establish a CLI connection
3083
// the actual authentication for the connecting Channel is done by CLICommand
3085
UUID uuid = UUID.fromString(req.getHeader("Session"));
3086
rsp.setHeader("Hudson-Duplex",""); // set the header so that the client would know
3088
FullDuplexHttpChannel server;
3089
if(req.getHeader("Side").equals("download")) {
3090
duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) {
3091
protected void main(Channel channel) throws IOException, InterruptedException {
3092
// capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator()
3093
channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION,getAuthentication());
3094
channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(channel));
3098
server.download(req,rsp);
3100
duplexChannels.remove(uuid);
3103
duplexChannels.get(uuid).upload(req,rsp);
3108
* Binds /userContent/... to $JENKINS_HOME/userContent.
3110
public DirectoryBrowserSupport doUserContent() {
3111
return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true);
3115
* Perform a restart of Hudson, if we can.
3117
* This first replaces "app" to {@link HudsonIsRestarting}
3119
@CLIMethod(name="restart")
3120
public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException {
3121
checkPermission(ADMINISTER);
3122
if (req != null && req.getMethod().equals("GET")) {
3123
req.getView(this,"_restart.jelly").forward(req,rsp);
3129
if (rsp != null) // null for CLI
3130
rsp.sendRedirect2(".");
3134
* Queues up a restart of Hudson for when there are no builds running, if we can.
3136
* This first replaces "app" to {@link HudsonIsRestarting}
3140
@CLIMethod(name="safe-restart")
3141
public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException {
3142
checkPermission(ADMINISTER);
3143
if (req != null && req.getMethod().equals("GET"))
3144
return HttpResponses.forwardToView(this,"_safeRestart.jelly");
3148
return HttpResponses.redirectToDot();
3152
* Performs a restart.
3154
public void restart() throws RestartNotSupportedException {
3155
final Lifecycle lifecycle = Lifecycle.get();
3156
lifecycle.verifyRestartable(); // verify that Hudson is restartable
3157
servletContext.setAttribute("app", new HudsonIsRestarting());
3159
new Thread("restart thread") {
3160
final String exitUser = getAuthentication().getName();
3164
ACL.impersonate(ACL.SYSTEM);
3166
// give some time for the browser to load the "reloading" page
3168
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
3169
for (RestartListener listener : RestartListener.all())
3170
listener.onRestart();
3171
lifecycle.restart();
3172
} catch (InterruptedException e) {
3173
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
3174
} catch (IOException e) {
3175
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
3182
* Queues up a restart to be performed once there are no builds currently running.
3185
public void safeRestart() throws RestartNotSupportedException {
3186
final Lifecycle lifecycle = Lifecycle.get();
3187
lifecycle.verifyRestartable(); // verify that Hudson is restartable
3188
// Quiet down so that we won't launch new builds.
3189
isQuietingDown = true;
3191
new Thread("safe-restart thread") {
3192
final String exitUser = getAuthentication().getName();
3196
ACL.impersonate(ACL.SYSTEM);
3198
// Wait 'til we have no active executors.
3199
doQuietDown(true, 0);
3201
// Make sure isQuietingDown is still true.
3202
if (isQuietingDown) {
3203
servletContext.setAttribute("app",new HudsonIsRestarting());
3204
// give some time for the browser to load the "reloading" page
3205
LOGGER.info("Restart in 10 seconds");
3206
Thread.sleep(10000);
3207
LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser));
3208
for (RestartListener listener : RestartListener.all())
3209
listener.onRestart();
3210
lifecycle.restart();
3212
LOGGER.info("Safe-restart mode cancelled");
3214
} catch (InterruptedException e) {
3215
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
3216
} catch (IOException e) {
3217
LOGGER.log(Level.WARNING, "Failed to restart Hudson",e);
3224
* Shutdown the system.
3227
@CLIMethod(name="shutdown")
3228
public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException {
3229
checkPermission(ADMINISTER);
3230
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
3231
getAuthentication().getName(), req!=null?req.getRemoteAddr():"???"));
3233
rsp.setStatus(HttpServletResponse.SC_OK);
3234
rsp.setContentType("text/plain");
3235
PrintWriter w = rsp.getWriter();
3236
w.println("Shutting down");
3245
* Shutdown the system safely.
3248
@CLIMethod(name="safe-shutdown")
3249
public HttpResponse doSafeExit(StaplerRequest req) throws IOException {
3250
checkPermission(ADMINISTER);
3251
isQuietingDown = true;
3252
final String exitUser = getAuthentication().getName();
3253
final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown";
3254
new Thread("safe-exit thread") {
3258
ACL.impersonate(ACL.SYSTEM);
3259
LOGGER.severe(String.format("Shutting down VM as requested by %s from %s",
3260
exitUser, exitAddr));
3261
// Wait 'til we have no active executors.
3262
while (isQuietingDown
3263
&& (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) {
3266
// Make sure isQuietingDown is still true.
3267
if (isQuietingDown) {
3271
} catch (InterruptedException e) {
3272
LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e);
3277
return HttpResponses.plainText("Shutting down as soon as all jobs are complete");
3281
* Gets the {@link Authentication} object that represents the user
3282
* associated with the current request.
3284
public static Authentication getAuthentication() {
3285
Authentication a = SecurityContextHolder.getContext().getAuthentication();
3286
// on Tomcat while serving the login page, this is null despite the fact
3287
// that we have filters. Looking at the stack trace, Tomcat doesn't seem to
3288
// run the request through filters when this is the login request.
3289
// see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
3296
* For system diagnostics.
3297
* Run arbitrary Groovy script.
3299
public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3300
doScript(req, rsp, req.getView(this, "_script.jelly"));
3304
* Run arbitrary Groovy script and return result as plain text.
3306
public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3307
doScript(req, rsp, req.getView(this, "_scriptText.jelly"));
3310
private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException {
3311
// ability to run arbitrary script is dangerous
3312
checkPermission(RUN_SCRIPTS);
3314
String text = req.getParameter("script");
3317
req.setAttribute("output",
3318
RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
3319
} catch (InterruptedException e) {
3320
throw new ServletException(e);
3324
view.forward(req, rsp);
3328
* Evaluates the Jelly script submitted by the client.
3330
* This is useful for system administration as well as unit testing.
3333
public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3334
checkPermission(ADMINISTER);
3337
MetaClass mc = WebApp.getCurrent().getMetaClass(getClass());
3338
Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader()));
3339
new JellyRequestDispatcher(this,script).forward(req,rsp);
3340
} catch (JellyException e) {
3341
throw new ServletException(e);
3346
* Sign up for the user account.
3348
public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
3349
req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp);
3353
* Changes the icon size by changing the cookie
3355
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
3356
String qs = req.getQueryString();
3357
if(qs==null || !ICON_SIZE.matcher(qs).matches())
3358
throw new ServletException();
3359
Cookie cookie = new Cookie("iconSize", qs);
3360
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
3361
rsp.addCookie(cookie);
3362
String ref = req.getHeader("Referer");
3363
if(ref==null) ref=".";
3364
rsp.sendRedirect2(ref);
3367
public void doFingerprintCleanup(StaplerResponse rsp) throws IOException {
3368
FingerprintCleanupThread.invoke();
3369
rsp.setStatus(HttpServletResponse.SC_OK);
3370
rsp.setContentType("text/plain");
3371
rsp.getWriter().println("Invoked");
3374
public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException {
3375
WorkspaceCleanupThread.invoke();
3376
rsp.setStatus(HttpServletResponse.SC_OK);
3377
rsp.setContentType("text/plain");
3378
rsp.getWriter().println("Invoked");
3382
* If the user chose the default JDK, make sure we got 'java' in PATH.
3384
public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) {
3385
if(!value.equals("(Default)"))
3386
// assume the user configured named ones properly in system config ---
3387
// or else system config should have reported form field validation errors.
3388
return FormValidation.ok();
3390
// default JDK selected. Does such java really exist?
3391
if(JDK.isDefaultJDKValid(Jenkins.this))
3392
return FormValidation.ok();
3394
return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath()));
3398
* Makes sure that the given name is good as a job name.
3400
public FormValidation doCheckJobName(@QueryParameter String value) {
3401
// this method can be used to check if a file exists anywhere in the file system,
3402
// so it should be protected.
3403
checkPermission(Item.CREATE);
3405
if(fixEmpty(value)==null)
3406
return FormValidation.ok();
3409
checkJobName(value);
3410
return FormValidation.ok();
3411
} catch (Failure e) {
3412
return FormValidation.error(e.getMessage());
3417
* Checks if a top-level view with the given name exists.
3419
public FormValidation doViewExistsCheck(@QueryParameter String value) {
3420
checkPermission(View.CREATE);
3422
String view = fixEmpty(value);
3423
if(view==null) return FormValidation.ok();
3425
if(getView(view)==null)
3426
return FormValidation.ok();
3428
return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view));
3432
* Serves static resources placed along with Jelly view files.
3434
* This method can serve a lot of files, so care needs to be taken
3435
* to make this method secure. It's not clear to me what's the best
3436
* strategy here, though the current implementation is based on
3439
public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3440
String path = req.getRestOfPath();
3441
// cut off the "..." portion of /resources/.../path/to/file
3442
// as this is only used to make path unique (which in turn
3443
// allows us to set a long expiration date
3444
path = path.substring(path.indexOf('/',1)+1);
3446
int idx = path.lastIndexOf('.');
3447
String extension = path.substring(idx+1);
3448
if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) {
3449
URL url = pluginManager.uberClassLoader.getResource(path);
3451
long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/
3452
rsp.serveFile(req,url,expires);
3456
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
3460
* Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve.
3461
* This set is mutable to allow plugins to add additional extensions.
3463
public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList(
3464
"js|css|jpeg|jpg|png|gif|html|htm".split("\\|")
3468
* Checks if container uses UTF-8 to decode URLs. See
3469
* http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n
3471
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException {
3472
// expected is non-ASCII String
3473
final String expected = "\u57f7\u4e8b";
3474
final String value = fixEmpty(request.getParameter("value"));
3475
if (!expected.equals(value))
3476
return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL());
3477
return FormValidation.ok();
3481
* Does not check when system default encoding is "ISO-8859-1".
3483
public static boolean isCheckURIEncodingEnabled() {
3484
return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding"));
3488
* Rebuilds the dependency map.
3490
public void rebuildDependencyGraph() {
3491
DependencyGraph graph = new DependencyGraph();
3493
// volatile acts a as a memory barrier here and therefore guarantees
3494
// that graph is fully build, before it's visible to other threads
3495
dependencyGraph = graph;
3498
public DependencyGraph getDependencyGraph() {
3499
return dependencyGraph;
3503
public List<ManagementLink> getManagementLinks() {
3504
return ManagementLink.all();
3508
* Exposes the current user to <tt>/me</tt> URL.
3510
public User getMe() {
3511
User u = User.current();
3513
throw new AccessDeniedException("/me is not available when not logged in");
3518
* Gets the {@link Widget}s registered on this object.
3521
* Plugins who wish to contribute boxes on the side panel can add widgets
3522
* by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}.
3524
public List<Widget> getWidgets() {
3528
public Object getTarget() {
3530
checkPermission(READ);
3531
} catch (AccessDeniedException e) {
3532
String rest = Stapler.getCurrentRequest().getRestOfPath();
3533
if(rest.startsWith("/login")
3534
|| rest.startsWith("/logout")
3535
|| rest.startsWith("/accessDenied")
3536
|| rest.startsWith("/adjuncts/")
3537
|| rest.startsWith("/signup")
3538
|| rest.startsWith("/jnlpJars/")
3539
|| rest.startsWith("/tcpSlaveAgentListener")
3540
// XXX SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access
3541
|| rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))
3542
|| rest.startsWith("/cli")
3543
|| rest.startsWith("/whoAmI")
3544
|| rest.startsWith("/federatedLoginService/")
3545
|| rest.startsWith("/securityRealm"))
3546
return this; // URLs that are always visible without READ permission
3548
for (Action a : getActions()) {
3549
if (a instanceof UnprotectedRootAction) {
3550
if (rest.startsWith("/"+a.getUrlName()+"/") || rest.equals("/"+a.getUrlName()))
3561
* Fallback to the primary view.
3563
public View getStaplerFallback() {
3564
return getPrimaryView();
3568
* This method checks all existing jobs to see if displayName is
3569
* unique. It does not check the displayName against the displayName of the
3570
* job that the user is configuring though to prevent a validation warning
3571
* if the user sets the displayName to what it currently is.
3572
* @param displayName
3573
* @param currentJobName
3576
boolean isDisplayNameUnique(String displayName, String currentJobName) {
3577
Collection<TopLevelItem> itemCollection = items.values();
3579
// if there are a lot of projects, we'll have to store their
3580
// display names in a HashSet or something for a quick check
3581
for(TopLevelItem item : itemCollection) {
3582
if(item.getName().equals(currentJobName)) {
3583
// we won't compare the candidate displayName against the current
3584
// item. This is to prevent an validation warning if the user
3585
// sets the displayName to what the existing display name is
3588
else if(displayName.equals(item.getDisplayName())) {
3597
* True if there is no item in Jenkins that has this name
3598
* @param name The name to test
3599
* @param currentJobName The name of the job that the user is configuring
3602
boolean isNameUnique(String name, String currentJobName) {
3603
Item item = getItem(name);
3606
// the candidate name didn't return any items so the name is unique
3609
else if(item.getName().equals(currentJobName)) {
3610
// the candidate name returned an item, but the item is the item
3611
// that the user is configuring so this is ok
3615
// the candidate name returned an item, so it is not unique
3621
* Checks to see if the candidate displayName collides with any
3622
* existing display names or project names
3623
* @param displayName The display name to test
3624
* @param jobName The name of the job the user is configuring
3627
public FormValidation doCheckDisplayName(@QueryParameter String displayName,
3628
@QueryParameter String jobName) {
3629
displayName = displayName.trim();
3631
if(LOGGER.isLoggable(Level.FINE)) {
3632
LOGGER.log(Level.FINE, "Current job name is " + jobName);
3635
if(!isNameUnique(displayName, jobName)) {
3636
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName));
3638
else if(!isDisplayNameUnique(displayName, jobName)){
3639
return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName));
3642
return FormValidation.ok();
3646
public static class MasterComputer extends Computer {
3647
protected MasterComputer() {
3648
super(Jenkins.getInstance());
3652
* Returns "" to match with {@link Jenkins#getNodeName()}.
3655
public String getName() {
3660
public boolean isConnecting() {
3665
public String getDisplayName() {
3666
return Messages.Hudson_Computer_DisplayName();
3670
public String getCaption() {
3671
return Messages.Hudson_Computer_Caption();
3675
public String getUrl() {
3676
return "computer/(master)/";
3679
public RetentionStrategy getRetentionStrategy() {
3680
return RetentionStrategy.NOOP;
3687
public HttpResponse doDoDelete() throws IOException {
3688
throw HttpResponses.status(SC_BAD_REQUEST);
3692
public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
3693
Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp);
3697
public boolean hasPermission(Permission permission) {
3698
// no one should be allowed to delete the master.
3699
// this hides the "delete" link from the /computer/(master) page.
3700
if(permission==Computer.DELETE)
3702
// Configuration of master node requires ADMINISTER permission
3703
return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission);
3707
public VirtualChannel getChannel() {
3708
return localChannel;
3712
public Charset getDefaultCharset() {
3713
return Charset.defaultCharset();
3716
public List<LogRecord> getLogRecords() throws IOException, InterruptedException {
3720
public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
3721
// this computer never returns null from channel, so
3722
// this method shall never be invoked.
3723
rsp.sendError(SC_NOT_FOUND);
3726
protected Future<?> _connect(boolean forceReconnect) {
3727
return Futures.precomputed(null);
3731
* {@link LocalChannel} instance that can be used to execute programs locally.
3733
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
3737
* Shortcut for {@code Hudson.getInstance().lookup.get(type)}
3739
public static <T> T lookup(Class<T> type) {
3740
return Jenkins.getInstance().lookup.get(type);
3744
* Live view of recent {@link LogRecord}s produced by Hudson.
3746
public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE
3749
* Thread-safe reusable {@link XStream}.
3751
public static final XStream XSTREAM = new XStream2();
3754
* Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily.
3756
public static final XStream2 XSTREAM2 = (XStream2)XSTREAM;
3758
private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2);
3761
* Thread pool used to load configuration in parallel, to improve the start up time.
3763
* The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers.
3765
/*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor(
3766
TWICE_CPU_NUM, TWICE_CPU_NUM,
3767
5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory());
3770
private static void computeVersion(ServletContext context) {
3772
Properties props = new Properties();
3774
InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
3777
} catch (IOException e) {
3778
e.printStackTrace(); // if the version properties is missing, that's OK.
3780
String ver = props.getProperty("version");
3781
if(ver==null) ver="?";
3783
context.setAttribute("version",ver);
3785
VERSION_HASH = Util.getDigestOf(ver).substring(0, 8);
3786
SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8);
3788
if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache"))
3791
RESOURCE_PATH = "/static/"+SESSION_HASH;
3793
VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH;
3797
* Version number of this Hudson.
3799
public static String VERSION="?";
3802
* Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number
3803
* (such as when Hudson is run with "mvn hudson-dev:run")
3805
public static VersionNumber getVersion() {
3807
return new VersionNumber(VERSION);
3808
} catch (NumberFormatException e) {
3810
// for non-released version of Hudson, this looks like "1.345 (private-foobar), so try to approximate.
3811
int idx = VERSION.indexOf(' ');
3813
return new VersionNumber(VERSION.substring(0,idx));
3814
} catch (NumberFormatException _) {
3818
// totally unparseable
3820
} catch (IllegalArgumentException e) {
3821
// totally unparseable
3827
* Hash of {@link #VERSION}.
3829
public static String VERSION_HASH;
3832
* Unique random token that identifies the current session.
3833
* Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header.
3835
* We used to use {@link #VERSION_HASH}, but making this session local allows us to
3836
* reuse the same {@link #RESOURCE_PATH} for static resources in plugins.
3838
public static String SESSION_HASH;
3841
* Prefix to static resources like images and javascripts in the war file.
3842
* Either "" or strings like "/static/VERSION", which avoids Hudson to pick up
3843
* stale cache when the user upgrades to a different version.
3845
* Value computed in {@link WebAppMain}.
3847
public static String RESOURCE_PATH = "";
3850
* Prefix to resources alongside view scripts.
3851
* Strings like "/resources/VERSION", which avoids Hudson to pick up
3852
* stale cache when the user upgrades to a different version.
3854
* Value computed in {@link WebAppMain}.
3856
public static String VIEW_RESOURCE_PATH = "/resources/TBD";
3858
public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true);
3859
public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false);
3860
private static final boolean CONSISTENT_HASH = true; // Boolean.getBoolean(Hudson.class.getName()+".consistentHash");
3862
* Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems.
3864
public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter("flyweightSupport", true);
3867
* Tentative switch to activate the concurrent build behavior.
3868
* When we merge this back to the trunk, this allows us to keep
3869
* this feature hidden for a while until we iron out the kinks.
3870
* @see AbstractProject#isConcurrentBuild()
3871
* @deprecated as of 1.464
3872
* This flag will have no effect.
3874
@Restricted(NoExternalUse.class)
3875
public static boolean CONCURRENT_BUILD = true;
3878
* Switch to enable people to use a shorter workspace name.
3880
private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace");
3883
* Automatically try to launch a slave when Jenkins is initialized or a new slave is created.
3885
public static boolean AUTOMATIC_SLAVE_LAUNCH = true;
3887
private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName());
3889
private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
3891
public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS;
3892
public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER;
3893
public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS);
3894
public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS);
3897
* {@link Authentication} object that represents the anonymous user.
3898
* Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not
3899
* expect the singleton semantics. This is just a convenient instance.
3903
public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken(
3904
"anonymous","anonymous",new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")});
3907
XSTREAM.alias("jenkins",Jenkins.class);
3908
XSTREAM.alias("slave", DumbSlave.class);
3909
XSTREAM.alias("jdk",JDK.class);
3910
// for backward compatibility with <1.75, recognize the tag name "view" as well.
3911
XSTREAM.alias("view", ListView.class);
3912
XSTREAM.alias("listView", ListView.class);
3913
// this seems to be necessary to force registration of converter early enough
3914
Mode.class.getEnumConstants();
3916
// double check that initialization order didn't do any harm
3917
assert PERMISSIONS!=null;
3918
assert ADMINISTER!=null;