/
Jenkins.java
executable file
·4009 lines (3498 loc) · 137 KB
/
Jenkins.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.,
* Yahoo!, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.model.LoadStatistics;
import hudson.model.Messages;
import hudson.model.Node;
import hudson.model.AbstractCIBase;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.AllView;
import hudson.model.Api;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DescriptorByNameOwner;
import hudson.model.DirectoryBrowserSupport;
import hudson.model.Failure;
import hudson.model.Fingerprint;
import hudson.model.FingerprintCleanupThread;
import hudson.model.FingerprintMap;
import hudson.model.FullDuplexHttpChannel;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.ItemGroupMixIn;
import hudson.model.Items;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.JobPropertyDescriptor;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.LoadBalancer;
import hudson.model.ManagementLink;
import hudson.model.NoFingerprintMatch;
import hudson.model.OverallLoadStatistics;
import hudson.model.Project;
import hudson.model.Queue.FlyweightTask;
import hudson.model.RestartListener;
import hudson.model.RootAction;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.UnprotectedRootAction;
import hudson.model.UpdateCenter;
import hudson.model.User;
import hudson.model.View;
import hudson.model.ViewGroup;
import hudson.model.ViewGroupMixIn;
import hudson.model.Descriptor.FormException;
import hudson.model.labels.LabelAtom;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.Queue;
import hudson.model.WorkspaceCleanupThread;
import antlr.ANTLRException;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.XStream;
import hudson.BulkChange;
import hudson.DNSMultiCast;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Launcher.LocalLauncher;
import hudson.LocalPluginManager;
import hudson.Lookup;
import hudson.markup.MarkupFormatter;
import hudson.Plugin;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.ProxyConfiguration;
import hudson.TcpSlaveAgentListener;
import hudson.UDPBroadcastThread;
import hudson.Util;
import static hudson.Util.fixEmpty;
import static hudson.Util.fixNull;
import hudson.WebAppMain;
import hudson.XmlFile;
import hudson.cli.CLICommand;
import hudson.cli.CliEntryPoint;
import hudson.cli.CliManagerImpl;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.init.InitMilestone;
import hudson.init.InitStrategy;
import hudson.lifecycle.Lifecycle;
import hudson.logging.LogRecorderManager;
import hudson.lifecycle.RestartNotSupportedException;
import hudson.markup.RawHtmlMarkupFormatter;
import hudson.remoting.Channel;
import hudson.remoting.LocalChannel;
import hudson.remoting.VirtualChannel;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.AuthorizationStrategy;
import hudson.security.FederatedLoginService;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonFilter;
import hudson.security.LegacyAuthorizationStrategy;
import hudson.security.LegacySecurityRealm;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityMode;
import hudson.security.SecurityRealm;
import hudson.security.csrf.CrumbIssuer;
import hudson.slaves.Cloud;
import hudson.slaves.ComputerListener;
import hudson.slaves.DumbSlave;
import hudson.slaves.EphemeralNode;
import hudson.slaves.NodeDescriptor;
import hudson.slaves.NodeList;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import hudson.tasks.BuildWrapper;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AdministrativeError;
import hudson.util.CaseInsensitiveComparator;
import hudson.util.ClockDifference;
import hudson.util.CopyOnWriteList;
import hudson.util.CopyOnWriteMap;
import hudson.util.DaemonThreadFactory;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
import hudson.util.MultipartFormDataParser;
import hudson.util.RemotingDiagnostics;
import hudson.util.RemotingDiagnostics.HeapDump;
import hudson.util.StreamTaskListener;
import hudson.util.TextFile;
import hudson.util.TimeUnit2;
import hudson.util.VersionNumber;
import hudson.util.XStream2;
import hudson.views.DefaultMyViewsTabBar;
import hudson.views.DefaultViewsTabBar;
import hudson.views.MyViewsTabBar;
import hudson.views.ViewsTabBar;
import hudson.widgets.Widget;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.InitReactorRunner;
import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy;
import jenkins.security.ConfidentialKey;
import jenkins.security.ConfidentialStore;
import jenkins.slaves.WorkspaceLocator;
import jenkins.util.io.FileBoolean;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiSecurityException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;
import org.acegisecurity.ui.AbstractProcessingFilter;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Script;
import org.apache.commons.logging.LogFactory;
import org.jvnet.hudson.reactor.Executable;
import org.jvnet.hudson.reactor.ReactorException;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.hudson.reactor.TaskGraphBuilder;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebApp;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.framework.adjunct.AdjunctManager;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff;
import org.kohsuke.stapler.jelly.JellyRequestDispatcher;
import org.xml.sax.InputSource;
import javax.crypto.SecretKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import static hudson.init.InitMilestone.*;
import hudson.security.BasicAuthenticationFilter;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import static java.util.logging.Level.SEVERE;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Root object of the system.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Jenkins extends AbstractCIBase implements ModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu {
private transient final Queue queue;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
public transient final Lookup lookup = new Lookup();
/**
* We update this field to the current version of Hudson whenever we save {@code config.xml}.
* This can be used to detect when an upgrade happens from one version to next.
*
* <p>
* Since this field is introduced starting 1.301, "1.0" is used to represent every version
* up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or
* "?", etc., so parsing needs to be done with a care.
*
* @since 1.301
*/
// this field needs to be at the very top so that other components can look at this value even during unmarshalling
private String version = "1.0";
/**
* Number of executors of the master node.
*/
private int numExecutors = 2;
/**
* Job allocation strategy.
*/
private Mode mode = Mode.NORMAL;
/**
* False to enable anyone to do anything.
* Left as a field so that we can still read old data that uses this flag.
*
* @see #authorizationStrategy
* @see #securityRealm
*/
private Boolean useSecurity;
/**
* Controls how the
* <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a>
* is handled in Hudson.
* <p>
* This ultimately controls who has access to what.
*
* Never null.
*/
private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED;
/**
* Controls a part of the
* <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a>
* handling in Hudson.
* <p>
* Intuitively, this corresponds to the user database.
*
* See {@link HudsonFilter} for the concrete authentication protocol.
*
* Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to
* update this field.
*
* @see #getSecurity()
* @see #setSecurityRealm(SecurityRealm)
*/
private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION;
/**
* 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?
*/
private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY;
/**
* Root directory for the workspaces.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getWorkspaceFor(TopLevelItem)
*/
private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME;
/**
* Root directory for the builds.
* This value will be variable-expanded as per {@link #expandVariablesForDirectory}.
* @see #getBuildDirFor(Job)
*/
private String buildsDir = "${ITEM_ROOTDIR}/builds";
/**
* Message displayed in the top page.
*/
private String systemMessage;
private MarkupFormatter markupFormatter;
/**
* Root directory of the system.
*/
public transient final File root;
/**
* Where are we in the initialization?
*/
private transient volatile InitMilestone initLevel = InitMilestone.STARTED;
/**
* All {@link Item}s keyed by their {@link Item#getName() name}s.
*/
/*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE);
/**
* The sole instance.
*/
private static Jenkins theInstance;
private transient volatile boolean isQuietingDown;
private transient volatile boolean terminating;
private List<JDK> jdks = new ArrayList<JDK>();
private transient volatile DependencyGraph dependencyGraph;
/**
* Currently active Views tab bar.
*/
private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar();
/**
* Currently active My Views tab bar.
*/
private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar();
/**
* All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}.
*/
private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() {
public ExtensionList compute(Class key) {
return ExtensionList.create(Jenkins.this,key);
}
};
/**
* All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}.
*/
private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() {
public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>();
/**
* Active {@link Cloud}s.
*/
public final Hudson.CloudList clouds = new Hudson.CloudList(this);
public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> {
public CloudList(Jenkins h) {
super(h);
}
public CloudList() {// needed for XStream deserialization
}
public Cloud getByName(String name) {
for (Cloud c : this)
if (c.name.equals(name))
return c;
return null;
}
@Override
protected void onModified() throws IOException {
super.onModified();
Jenkins.getInstance().trimLabels();
}
}
/**
* Set of installed cluster nodes.
* <p>
* We use this field with copy-on-write semantics.
* This field has mutable list (to keep the serialization look clean),
* but it shall never be modified. Only new completely populated slave
* list can be set here.
* <p>
* The field name should be really {@code nodes}, but again the backward compatibility
* prevents us from renaming.
*/
protected volatile NodeList slaves;
/**
* Quiet period.
*
* This is {@link Integer} so that we can initialize it to '5' for upgrading users.
*/
/*package*/ Integer quietPeriod;
/**
* Global default for {@link AbstractProject#getScmCheckoutRetryCount()}
*/
/*package*/ int scmCheckoutRetryCount;
/**
* {@link View}s.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
/**
* Name of the primary view.
* <p>
* Start with null, so that we can upgrade pre-1.269 data well.
* @since 1.269
*/
private volatile String primaryView;
private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) {
protected List<View> views() { return views; }
protected String primaryView() { return primaryView; }
protected void primaryView(String name) { primaryView=name; }
};
private transient final FingerprintMap fingerprintMap = new FingerprintMap();
/**
* Loaded plugins.
*/
public transient final PluginManager pluginManager;
public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener;
private transient UDPBroadcastThread udpBroadcastThread;
private transient DNSMultiCast dnsMultiCast;
/**
* List of registered {@link SCMListener}s.
*/
private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>();
/**
* TCP slave agent port.
* 0 for random, -1 to disable.
*/
private int slaveAgentPort =0;
/**
* Whitespace-separated labels assigned to the master as a {@link Node}.
*/
private String label="";
/**
* {@link hudson.security.csrf.CrumbIssuer}
*/
private volatile CrumbIssuer crumbIssuer;
/**
* All labels known to Jenkins. This allows us to reuse the same label instances
* as much as possible, even though that's not a strict requirement.
*/
private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>();
/**
* Load statistics of the entire system.
*
* This includes every executor and every job in the system.
*/
@Exported
public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics();
/**
* Load statistics of the free roaming jobs and slaves.
*
* This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes.
*
* @since 1.467
*/
@Exported
public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
/**
* {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}.
* @since 1.467
*/
public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad);
/**
* @deprecated as of 1.467
* Use {@link #unlabeledNodeProvisioner}.
* This was broken because it was tracking all the executors in the system, but it was only tracking
* free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive
* slaves and free-roaming jobs in the queue.
*/
@Restricted(NoExternalUse.class)
public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner;
public transient final ServletContext servletContext;
/**
* Transient action list. Useful for adding navigation items to the navigation bar
* on the left.
*/
private transient final List<Action> actions = new CopyOnWriteArrayList<Action>();
/**
* List of master node properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* List of global properties
*/
private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this);
/**
* {@link AdministrativeMonitor}s installed on this system.
*
* @see AdministrativeMonitor
*/
public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class);
/**
* Widgets on Hudson.
*/
private transient final List<Widget> widgets = getExtensionList(Widget.class);
/**
* {@link AdjunctManager}
*/
private transient final AdjunctManager adjuncts;
/**
* Code that handles {@link ItemGroup} work.
*/
private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) {
@Override
protected void add(TopLevelItem item) {
items.put(item.getName(),item);
}
@Override
protected File getRootDirFor(String name) {
return Jenkins.this.getRootDirFor(name);
}
/**
* Send the browser to the config page.
* use View to trim view/{default-view} from URL if possible
*/
@Override
protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
String redirect = result.getUrl()+"configure";
List<Ancestor> ancestors = req.getAncestors();
for (int i = ancestors.size() - 1; i >= 0; i--) {
Object o = ancestors.get(i).getObject();
if (o instanceof View) {
redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect;
break;
}
}
return redirect;
}
};
/**
* Hook for a test harness to intercept Jenkins.getInstance()
*
* Do not use in the production code as the signature may change.
*/
public interface JenkinsHolder {
Jenkins getInstance();
}
static JenkinsHolder HOLDER = new JenkinsHolder() {
public Jenkins getInstance() {
return theInstance;
}
};
@CLIResolver
public static Jenkins getInstance() {
return HOLDER.getInstance();
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
* accidental exposure.
*/
private transient final String secretKey;
private transient final UpdateCenter updateCenter = new UpdateCenter();
/**
* True if the user opted out from the statistics tracking. We'll never send anything if this is true.
*/
private Boolean noUsageStatistics;
/**
* HTTP proxy configuration.
*/
public transient volatile ProxyConfiguration proxy;
/**
* Bound to "/log".
*/
private transient final LogRecorderManager log = new LogRecorderManager();
protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException {
this(root,context,null);
}
/**
* @param pluginManager
* If non-null, use existing plugin manager. create a new one.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings({
"SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer
})
protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException {
long start = System.currentTimeMillis();
// As Jenkins is starting, grant this process full control
ACL.impersonate(ACL.SYSTEM);
try {
this.root = root;
this.servletContext = context;
computeVersion(context);
if(theInstance!=null)
throw new IllegalStateException("second instance");
theInstance = this;
if (!new File(root,"jobs").exists()) {
// if this is a fresh install, use more modern default layout that's consistent with slaves
workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}";
}
// doing this early allows InitStrategy to set environment upfront
final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader());
Trigger.timer = new Timer("Jenkins cron thread");
queue = new Queue(LoadBalancer.CONSISTENT_HASH);
try {
dependencyGraph = DependencyGraph.EMPTY;
} catch (InternalError e) {
if(e.getMessage().contains("window server")) {
throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e);
}
throw e;
}
// get or create the secret
TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key"));
if(secretFile.exists()) {
secretKey = secretFile.readTrim();
} else {
SecureRandom sr = new SecureRandom();
byte[] random = new byte[32];
sr.nextBytes(random);
secretKey = Util.toHexString(random);
secretFile.write(secretKey);
// this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49.
// this indicates that there's no need to rewrite secrets on disk
new FileBoolean(new File(root,"secret.key.not-so-secret")).on();
}
try {
proxy = ProxyConfiguration.load();
} catch (IOException e) {
LOGGER.log(SEVERE, "Failed to load proxy configuration", e);
}
if (pluginManager==null)
pluginManager = new LocalPluginManager(this);
this.pluginManager = pluginManager;
// JSON binding needs to be able to see all the classes from all the plugins
WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader);
adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365));
// initialization consists of ...
executeReactor( is,
pluginManager.initTasks(is), // loading and preparing plugins
loadTasks(), // load jobs
InitMilestone.ordering() // forced ordering among key milestones
);
if(KILL_AFTER_LOAD)
System.exit(0);
if(slaveAgentPort!=-1) {
try {
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} catch (BindException e) {
new AdministrativeError(getClass().getName()+".tcpBind",
"Failed to listen to incoming slave connection",
"Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e);
}
} else
tcpSlaveAgentListener = null;
try {
udpBroadcastThread = new UDPBroadcastThread(this);
udpBroadcastThread.start();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to broadcast over UDP",e);
}
dnsMultiCast = new DNSMultiCast(this);
Timer timer = Trigger.timer;
if (timer != null) {
timer.scheduleAtFixedRate(new SafeTimerTask() {
@Override
protected void doRun() throws Exception {
trimLabels();
}
}, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5));
}
updateComputerList();
{// master is online now
Computer c = toComputer();
if(c!=null)
for (ComputerListener cl : ComputerListener.all())
cl.onOnline(c,StreamTaskListener.fromStdout());
}
for (ItemListener l : ItemListener.all()) {
long itemListenerStart = System.currentTimeMillis();
l.onLoaded();
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for item listener %s startup",
System.currentTimeMillis()-itemListenerStart,l.getClass().getName()));
}
if (LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for complete Jenkins startup",
System.currentTimeMillis()-start));
} finally {
SecurityContextHolder.clearContext();
}
}
/**
* Executes a reactor.
*
* @param is
* If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson.
*/
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
Reactor reactor = new Reactor(builders) {
/**
* Sets the thread name to the task for better diagnostics.
*/
@Override
protected void runTask(Task task) throws Exception {
if (is!=null && is.skipInitTask(task)) return;
ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
String taskName = task.getDisplayName();
Thread t = Thread.currentThread();
String name = t.getName();
if (taskName !=null)
t.setName(taskName);
try {
long start = System.currentTimeMillis();
super.runTask(task);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms for %s by %s",
System.currentTimeMillis()-start, taskName, name));
} finally {
t.setName(name);
SecurityContextHolder.clearContext();
}
}
};
new InitReactorRunner() {
@Override
protected void onInitMilestoneAttained(InitMilestone milestone) {
initLevel = milestone;
}
}.run(reactor);
}
public TcpSlaveAgentListener getTcpSlaveAgentListener() {
return tcpSlaveAgentListener;
}
/**
* Makes {@link AdjunctManager} URL-bound.
* The dummy parameter allows us to use different URLs for the same adjunct,
* for proper cache handling.
*/
public AdjunctManager getAdjuncts(String dummy) {
return adjuncts;
}
@Exported
public int getSlaveAgentPort() {
return slaveAgentPort;
}
/**
* @param port
* 0 to indicate random available TCP port. -1 to disable this service.
*/
public void setSlaveAgentPort(int port) throws IOException {
this.slaveAgentPort = port;
// relaunch the agent
if(tcpSlaveAgentListener==null) {
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
} else {
if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) {
tcpSlaveAgentListener.shutdown();
tcpSlaveAgentListener = null;
if(slaveAgentPort!=-1)
tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
}
}
}
public void setNodeName(String name) {
throw new UnsupportedOperationException(); // not allowed
}
public String getNodeDescription() {
return Messages.Hudson_NodeDescription();
}
@Exported
public String getDescription() {
return systemMessage;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public UpdateCenter getUpdateCenter() {
return updateCenter;
}
public boolean isUsageStatisticsCollected() {
return noUsageStatistics==null || !noUsageStatistics;
}
public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException {
this.noUsageStatistics = noUsageStatistics;
save();
}
public View.People getPeople() {
return new View.People(this);
}
/**
* @since 1.484
*/
public View.AsynchPeople getAsynchPeople() {
return new View.AsynchPeople(this);
}
/**
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
public boolean hasPeople() {
return View.People.isApplicable(items.values());
}
public Api getApi() {
return new Api(this);
}
/**