This commit is contained in:
liorha committed 2015-05-02 16:46:02 +03:00
commit 791bf56822
345 files changed
+6509 -5366

No files matched your search

-32
View File
@@ -1,32 +0,0 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
#
# Subline Text: https://github.com/editorconfig/editorconfig-sublime
# Emacs: https://github.com/editorconfig/editorconfig-emacs
# Jetbrains (IntelliJ etc): https://github.com/editorconfig/editorconfig-jetbrains
# Eclipse: ??
#
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[**.jelly]
indent_style = space
indent_size = 2
[**.js]
indent_style = space
indent_size = 4
[**.css]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false~
+3
View File
@@ -0,0 +1,3 @@
# Contributing to Jenkins
For information on contributing to Jenkins, check out the https://wiki.jenkins-ci.org/display/JENKINS/contributing and https://wiki.jenkins-ci.org/display/JENKINS/Extend+Jenkins wiki pages over at the official https://wiki.jenkins-ci.org . They will help you get started with contributing to Jenkins.
+39 -16
View File
@@ -1,28 +1,51 @@
[![][ButlerImage]][website]
Jenkins CI
==========
Copyright © 2004–, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other contributors. Licensed under [MIT License].
# About
In a nutshell, Jenkins CI is the leading open-source continuous integration server. Built with Java, it provides over 1000 plugins to support building and testing virtually any project.
About
-----
In a nutshell Jenkins CI is the leading open-source continuous integration server. Built with Java, it provides over 1000 plugins to support building and testing virtually any project.
# Downloads
Non-source downloads such as WAR files and several Linux packages can be found on our [Mirrors].
Downloads
---------
Non-source downloads such as WAR file and several Linux packages can be found on our [Mirrors].
Source
------
# Source
Our latest and greatest source of Jenkins CI can be found on [GitHub]. Fork us!
News and Website
----------------
All about Jenkins CI can be found on our [website]. Follow us on Twitter @[jenkinsci].
# Contributing to Jenkins
Follow [contributing](CONTRIBUTING.md) file.
# News and Website
All information about Jenkins CI can be found on our [website]. Follow us on Twitter [@jenkinsci].
# License
Jenkins is **licensed** under the **[MIT License]**. The terms of the license are as follows:
The MIT License (MIT)
Copyright (c) 2004 Kohsuke Kawaguchi, Sun Microsystems Inc., and a number of other contributors.
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.
[ButlerImage]: http://jenkins-ci.org/sites/default/files/jenkins_logo.png
[MIT License]: https://github.com/jenkinsci/jenkins/raw/master/LICENSE.txt
[Mirrors]: http://mirrors.jenkins-ci.org
[GitHub]: https://github.com/jenkinsci/jenkins
[website]: http://jenkins-ci.org
[jenkinsci]: http://twitter.com/jenkinsci
[@jenkinsci]: http://twitter.com/jenkinsci
[Contributing]: https://wiki.jenkins-ci.org/display/JENKINS/contributing
[Extend Jenkins]: https://wiki.jenkins-ci.org/display/JENKINS/Extend+Jenkins
[wiki]: https://wiki.jenkins-ci.org
+178 -19
View File
@@ -39,47 +39,203 @@ Some tips:
Help other Jenkins users by letting the community know which releases you've used,
and whether they had any significant issues. <br>
Legend: <br>
<img src="http://ci.jenkins-ci.org/images/16x16/health-80plus.gif" width="16" height="16"
<img src="//ci.jenkins-ci.org/images/16x16/health-80plus.gif" width="16" height="16"
alt="Sunny"> = I use it on my production site without major issues. <br>
<img src="http://ci.jenkins-ci.org/images/16x16/health-40to59.gif" width="16" height="16"
<img src="//ci.jenkins-ci.org/images/16x16/health-40to59.gif" width="16" height="16"
alt="Cloudy"> = I don't recommend it. <br>
<img src="http://ci.jenkins-ci.org/images/16x16/health-00to19.gif" width="16" height="16"
<img src="//ci.jenkins-ci.org/images/16x16/health-00to19.gif" width="16" height="16"
alt="Lightning"> = I tried it but rolled back to a previous version. <br>
View ratings below, and click one of the icons next to your version to provide your input.
</div>
<a href="" onClick="document.getElementById('trunk').style.display=document.getElementById('rc').style.display='block';return false">
<a href="" onClick="document.getElementById('trunk').style.display='block';return false">
Upcoming changes</a>
<a href="" style="padding-left:3em" onClick="return loaddata(this)">Community ratings</a>
<!-- Record your changes in the trunk here. -->
<div id="trunk" style="display:none"><!--=TRUNK-BEGIN=-->
<ul class=image>
<li class=>
<li class=bug>
Handle AbortException publisher status in the same way as deprecated false boolean status
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26964">issue 26964</a>)
<li class=bug>
Ensures GlobalSettingsProvider does not swallow fatal exceptions
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26604">issue 26604</a>)
<li class=rfe>
add datestamp to node-offline message
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-23917">issue 23917</a>)
<li class=rfe>
Larger minimum popup menu height.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27067">issue 27067</a>)
<li class=rfe>
As <a href="http://jenkins-ci.org/content/good-bye-java6">promised</a>, shipping
with Java7 class files.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28120">issue 28120</a>)
<li class=bug>
<code>Descriptor.getId</code> fix in 1.610 introduced regressions affecting at least the Performance and NodeJS plugins.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28093">issue 28093</a> and <a href="https://issues.jenkins-ci.org/browse/JENKINS-28110">issue 28110</a>)
<li class=bug>
Under rare conditions Executor.getProgress() can throw a Division by zero exception.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28115">issue 28115</a>)
<li class=bug>
The Run from the command line option for launching a JNLP slave should display the
configured JVM options.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28111">issue 28111</a>)
</ul>
</div><!--=TRUNK-END=-->
<!-- these changes are controlled by the release process. DO NOT MODIFY -->
<div id="rc" style="display:none;"><!--=BEGIN=-->
<h3><a name=v1.603>What's new in 1.603</a> <!--=DATE=--></h3>
<h3><a name=v1.611>What's new in 1.611</a> (2015/04/26)</h3>
<ul class=image>
<li class=bug>
<code>Descriptor.getId</code> fix in 1.610 introduced a regression affecting at least the Copy Artifacts plugin.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28011">issue 28011</a>)
<li class=bug>
Search box did not work well inside folders.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-24433">issue 24433</a>)
<li class="major bug">
Revert changes in 1.610 made to resolve <a href="https://issues.jenkins-ci.org/browse/JENKINS-10629">issue 10629</a>.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28012">issue 28012</a>, <a href="https://issues.jenkins-ci.org/browse/JENKINS-28013">issue 28013</a>)
<li class=rfe>
Advertise JNLP slave agents to the correct host name, even in the presence of a reverse proxy.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27218">issue 27218</a>)
<li class=rfe>
Advertised TCP slave agent port number is made tweakable.
<li class=bug>
Correctly identify Channel listener onClose propagated exceptions
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-28062">issue 28062</a>
</ul>
<h3><a name=v1.610>What's new in 1.610</a> (2015/04/19)</h3>
<ul class=image>
<li class=bug>
Since 1.598 overrides of <code>Descriptor.getId</code> were not correctly handled by form binding, breaking at least the CloudBees Templates plugin.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26781">issue 26781</a>)
<li class=bug>
<b>Reverted in 1.611</b>. Archiving of large artifacts. Tar implementation cannot handle files having a size >8GB.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-10629">issue 10629</a>)
<li class=bug>
The queue state was not updated between scheduling builds.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27708">issue 27708</a>,
<a href="https://issues.jenkins-ci.org/browse/JENKINS-27871">issue 27871</a>)
</ul>
<h3><a name=v1.609>What's new in 1.609</a> (2015/04/12)</h3>
<ul class=image>
<li class=bug>
When concurrent builds are enabled, artifact retention policy may delete artifact being
used by an actually running build.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27836">issue 27836</a>)
<li class=bug>
Documentation for $BUILD_ID did not reflect current reality
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26520">issue 26520</a>)
</ul>
<h3><a name=v1.608>What's new in 1.608</a> (2015/04/05)</h3>
<ul class=image>
<li class=bug>
PeepholePermalink RunListenerImpl oncompleted should be triggered before downstream builds are triggered.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-20989">issue 20989</a>)
<li class=bug>
NPE when /script used on offline slave.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26751">issue 26751</a>)
<li class=rfe>
Make periodic workspace cleanup configurable through system properties.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-21322">issue 21322</a>)
<li class=bug>
Do not offer to restart on /restart and /safeRestart if the configuration does not support it.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27414">issue 27414</a>)
<li class=rfe>
Polling was skipped while quieting down, resulting in ignored commit notifications. This behavior was changed.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26208">issue 26208</a>)
<li class=rfe>
Starting this version, native packages are produced from <a href="https://github.com/jenkinsci/packaging">the new repository</a>.
File issues related to installers and packages in the <code>packaging</code> component.
</ul>
<h3><a name=v1.607>What's new in 1.607</a> (2015/03/30)</h3>
<ul class=image>
<li class=bug>
JSONP served with the wrong MIME type and rejected by Chrome.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27607">issue 27607</a>)
<li class=bug>
Security file pattern whitelist was broken for some plugins since 1.597.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27055">issue 27055</a>)
<li class=rfe>
Lock an Executor without creating a Thread
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-25938">issue 25938</a>)
<li class=rfe>
Hide flyweight master executor when ≥1 heavyweight executors running as subtasks
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26900">issue 26900</a>)
<li class=rfe>
Way to mark an Executable that should not block isReadyToRestart
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22941">issue 22941</a>)
<li class=rfe>
Refactor the Queue and Nodes to use a consistent locking strategy
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27565">issue 27565</a>)
<strong>Note</strong> that this change involved moving slave definitions outside the main <code>config.xml</code> file.
If you downgrade after this, your slave settings will be lost.
<li class=bug>
Makes the Jenkins is loading screen not block on the extensions loading lock
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27563">issue 27563</a>)
<li class=bug>
AdjunctManager: exception upon startup
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-15355">issue 15355</a>)
<li class=bug>
Removes race condition rendering the list of executors
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27564">issue 27564</a>)
<li class=bug>
Tidy up the locks that were causing deadlocks with the once retention strategy in durable tasks
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27476">issue 27476</a>)
<li class=bug>
Remove any requirement from Jenkins Core to lock on the Queue when rendering the Jenkins UI
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27566">issue 27566</a>)
<li class=bug>
Prevent lazy loading operation when obtaining label information.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26391">issue 26391</a>)
<li class=bug>
Ensure that the LoadStatistics return a self-consistent result.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-21618">issue 21618</a>)
<li class=bug>
Build reports to be running for 45 yr and counting.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26777">issue 26777</a>)
</ul>
<h3><a name=v1.606>What's new in 1.606</a> (2015/03/23)</h3>
<ul class=image>
<li class=bug>
Jenkins CLI doesn't handle arguments with equal signs
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-21160">issue 21160</a>)
<li class=bug>
master/slave communication ping reacts badly if a clock jumps.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-21251">issue 21251</a>)
<li class=rfe>
JNLP slaves can now connect to master through HTTP proxy.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-6167">issue 6167</a>)
<li class='major bug'>
Fixes to several security vulnerabilities.
(<a href="https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2015-03-23">advisory</a>)
</ul>
<h3><a name=v1.605>What's new in 1.605</a> (2015/03/16)</h3>
<ul class=image>
<li class=bug>
Integrate Stapler fix for queue item API always returning 404 Not Found since 1.601.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27256">issue 27256</a>)
</ul>
<h3><a name=v1.604>What's new in 1.604</a> (2015/03/15)</h3>
<ul class=image>
<li class=rfe>
Added a switch (<tt>-Dhudson.model.User.allowNonExistentUserToLogin=true</tt>) to let users login even when the record is not found in the backend security realm.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22346">issue 22346</a>)
<li class=bug>
Avoid deadlock when using build-monitor-plugin.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27183">issue 27183</a>)
<li class=rfe>
As security hardening, mark "remember me" cookie as HTTP only
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27277">issue 27277</a>)
</ul>
</div><!--=END=-->
<h3><a name=v1.602>What's new in 1.602</a> (2015/03/08)</h3>
<ul class=image>
<li class="major bug">
Regression with environment variables in 1.600.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27188">issue 27188</a>)
<li class="major bug">
Errors with concurrent matrix builds since 1.597.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26739">issue 26739</a>)
<li class="rfe">
Show displayName in build remote API.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26723">issue 26723</a>)
</ul>
<h3><a name=v1.602>What's new in 1.602</a> (2015/03/08)</h3>
<ul class=image>
<li class="rfe">
Show Check Now button also on Available and Updates tabs of plugin manager.
(<a href="https://github.com/jenkinsci/jenkins/pull/1593">PR 1593</a>)
</ul>
<h3><a name=v1.601>What's new in 1.601</a> (2015/03/03)</h3>
<ul class=image>
<li class="major bug">
@@ -91,6 +247,9 @@ Upcoming changes</a>
<li class=bug>
Errors in Dashboard View plugin since 1.597.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-26690">issue 26690</a>)
<li class=bug>
Robustness improvement when setting up Archive Artifacts programmatically.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-25779">issue 25779</a>)
<li class="rfe">
Map Queue.Item.id onto Run
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-27096">issue 27096</a>)
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>pom</artifactId>
<version>1.604-SNAPSHOT</version>
<version>1.612-SNAPSHOT</version>
</parent>
<artifactId>cli</artifactId>
@@ -42,7 +42,7 @@
<dependency>
<groupId>org.jvnet.localizer</groupId>
<artifactId>localizer</artifactId>
<version>1.10</version>
<version>1.23</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci</groupId>
+17 -4
View File
@@ -97,6 +97,7 @@ public class CLI {
* @deprecated
* Use {@link CLIConnectionFactory} to create {@link CLI}
*/
@Deprecated
public CLI(URL jenkins, ExecutorService exec) throws IOException, InterruptedException {
this(jenkins,exec,null);
}
@@ -105,6 +106,7 @@ public class CLI {
* @deprecated
* Use {@link CLIConnectionFactory} to create {@link CLI}
*/
@Deprecated
public CLI(URL jenkins, ExecutorService exec, String httpsProxyTunnel) throws IOException, InterruptedException {
this(new CLIConnectionFactory().url(jenkins).executorService(exec).httpsProxyTunnel(httpsProxyTunnel));
}
@@ -169,12 +171,18 @@ public class CLI {
private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
LOGGER.log(FINE, "Trying to connect directly via TCP/IP to {0}", clip.endpoint);
final Socket s;
final Socket s = new Socket();
// this prevents a connection from silently terminated by the router in between or the other peer
// and that goes without unnoticed. However, the time out is often very long (for example 2 hours
// by default in Linux) that this alone is enough to prevent that.
s.setKeepAlive(true);
// we take care of buffering on our own
s.setTcpNoDelay(true);
OutputStream out;
if (httpsProxyTunnel!=null) {
String[] tokens = httpsProxyTunnel.split(":");
s = new Socket(tokens[0], Integer.parseInt(tokens[1]));
s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1])));
PrintStream o = new PrintStream(s.getOutputStream());
o.print("CONNECT " + clip.endpoint.getHostName() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n");
@@ -199,7 +207,6 @@ public class CLI {
}
};
} else {
s = new Socket();
s.connect(clip.endpoint,3000);
out = SocketChannelStream.out(s);
}
@@ -379,7 +386,13 @@ public class CLI {
// h.setLevel(ALL);
// l.addHandler(h);
//
System.exit(_main(_args));
try {
System.exit(_main(_args));
} catch (Throwable t) {
// if the CLI main thread die, make sure to kill the JVM.
t.printStackTrace();
System.exit(-1);
}
}
public static int _main(String[] _args) throws Exception {
+5 -5
View File
@@ -29,7 +29,7 @@ THE SOFTWARE.
<parent>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>pom</artifactId>
<version>1.604-SNAPSHOT</version>
<version>1.612-SNAPSHOT</version>
</parent>
<artifactId>jenkins-core</artifactId>
@@ -39,7 +39,7 @@ THE SOFTWARE.
<properties>
<staplerFork>true</staplerFork>
<stapler.version>1.234</stapler.version>
<stapler.version>1.237</stapler.version>
<spring.version>2.5.6.SEC03</spring.version>
<groovy.version>1.8.9</groovy.version>
</properties>
@@ -190,7 +190,7 @@ THE SOFTWARE.
<dependency><!-- JENKINS-21160: remoting also depends on args4j, please update accordingly -->
<groupId>args4j</groupId>
<artifactId>args4j</artifactId>
<version>2.0.23</version>
<version>2.0.31</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci</groupId>
@@ -210,7 +210,7 @@ THE SOFTWARE.
<dependency>
<groupId>org.jvnet.localizer</groupId>
<artifactId>localizer</artifactId>
<version>1.10</version>
<version>1.23</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
@@ -749,7 +749,7 @@ THE SOFTWARE.
<configuration>
<forkCount>0.5C</forkCount>
<reuseForks>true</reuseForks>
<argLine>-XX:MaxPermSize=128m</argLine>
<argLine>-XX:MaxPermSize=128m -noverify</argLine> <!-- some versions of JDK7/8 causes VerifyError during mock tests: http://code.google.com/p/powermock/issues/detail?id=504 -->
</configuration>
</plugin>
<plugin><!-- set main class -->
@@ -81,6 +81,7 @@ public class DescriptorExtensionList<T extends Describable<T>, D extends Descrip
* @deprecated as of 1.416
* Use {@link #create(Jenkins, Class)}
*/
@Deprecated
public static <T extends Describable<T>,D extends Descriptor<T>>
DescriptorExtensionList<T,D> createDescriptorList(Hudson hudson, Class<T> describableType) {
return (DescriptorExtensionList)createDescriptorList((Jenkins)hudson,describableType);
@@ -95,6 +96,7 @@ public class DescriptorExtensionList<T extends Describable<T>, D extends Descrip
* @deprecated as of 1.416
* Use {@link #DescriptorExtensionList(Jenkins, Class)}
*/
@Deprecated
protected DescriptorExtensionList(Hudson hudson, Class<T> describableType) {
this((Jenkins)hudson,describableType);
}
@@ -109,6 +111,7 @@ public class DescriptorExtensionList<T extends Describable<T>, D extends Descrip
*
* @param fqcn
* Fully qualified name of the descriptor, not the describable.
* @deprecated {@link Descriptor#getId} is supposed to be used for new code, not the descriptor class name.
*/
public D find(String fqcn) {
return Descriptor.find(this,fqcn);
@@ -85,6 +85,7 @@ public abstract class ExtensionFinder implements ExtensionPoint {
* Use and implement {@link #find(Class,Hudson)} that allows us to put some metadata.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public <T> Collection<T> findExtensions(Class<T> type, Hudson hudson) {
return Collections.emptyList();
}
@@ -73,6 +73,7 @@ public class ExtensionList<T> extends AbstractList<T> {
* @deprecated as of 1.417
* Use {@link #jenkins}
*/
@Deprecated
public final Hudson hudson;
public final @CheckForNull Jenkins jenkins;
public final Class<T> extensionType;
@@ -93,6 +94,7 @@ public class ExtensionList<T> extends AbstractList<T> {
* @deprecated as of 1.416
* Use {@link #ExtensionList(Jenkins, Class)}
*/
@Deprecated
protected ExtensionList(Hudson hudson, Class<T> extensionType) {
this((Jenkins)hudson,extensionType);
}
@@ -105,6 +107,7 @@ public class ExtensionList<T> extends AbstractList<T> {
* @deprecated as of 1.416
* Use {@link #ExtensionList(Jenkins, Class, CopyOnWriteArrayList)}
*/
@Deprecated
protected ExtensionList(Hudson hudson, Class<T> extensionType, CopyOnWriteArrayList<ExtensionComponent<T>> legacyStore) {
this((Jenkins)hudson,extensionType,legacyStore);
}
@@ -214,6 +217,7 @@ public class ExtensionList<T> extends AbstractList<T> {
* Prefer automatic registration.
*/
@Override
@Deprecated
public synchronized boolean add(T t) {
legacyInstances.add(new ExtensionComponent<T>(t));
// if we've already filled extensions, add it
@@ -325,6 +329,7 @@ public class ExtensionList<T> extends AbstractList<T> {
* @deprecated as of 1.416
* Use {@link #create(Jenkins, Class)}
*/
@Deprecated
public static <T> ExtensionList<T> create(Hudson hudson, Class<T> type) {
return create((Jenkins)hudson,type);
}
+3
View File
@@ -367,6 +367,7 @@ public final class FilePath implements Serializable {
*
* @deprecated as of 1.315. Use {@link #zip(OutputStream)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
zip(os);
}
@@ -411,6 +412,7 @@ public final class FilePath implements Serializable {
* @deprecated as of 1.315
* Use {@link #zip(OutputStream,String)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
@@ -2337,6 +2339,7 @@ public final class FilePath implements Serializable {
* @see #validateFileMask(FilePath, String)
* @deprecated use {@link #validateAntFileMask(String, int)} instead
*/
@Deprecated
public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException {
return validateAntFileMask(fileMasks, Integer.MAX_VALUE);
}
@@ -204,6 +204,7 @@ public abstract class FileSystemProvisioner implements ExtensionPoint, Describab
/**
* @deprecated as of 1.350
*/
@Deprecated
public WorkspaceSnapshot snapshot(AbstractBuild<?, ?> build, FilePath ws, TaskListener listener) throws IOException, InterruptedException {
return snapshot(build, ws, "**/*", listener);
}
+27 -4
View File
@@ -28,6 +28,7 @@ package hudson;
import hudson.cli.CLICommand;
import hudson.console.ConsoleAnnotationDescriptor;
import hudson.console.ConsoleAnnotatorFactory;
import hudson.init.InitMilestone;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Describable;
@@ -201,7 +202,25 @@ public class Functions {
public static String rfc822Date(Calendar cal) {
return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime());
}
/**
* During Jenkins start-up, before {@link InitMilestone#PLUGINS_STARTED} the extensions lists will be empty
* and they are not guaranteed to be fully populated until after {@link InitMilestone#EXTENSIONS_AUGMENTED}.
* If you attempt to access the extensions list from a UI thread while the extensions are being loaded you will
* hit a big honking great monitor lock that will block until the effective extension list has been determined
* (as if a plugin fails to start, all of the failed plugin's extensions and any dependent plugins' extensions
* will have to be evicted from the list of extensions. In practical terms this only affects the
* "Jenkins is loading" screen, but as that screen uses the generic layouts we provide this utility method
* so that the generic layouts can avoid iterating extension lists while Jenkins is starting up.
*
* @return {@code true} if the extensions lists have been populated.
* @since 1.607
*/
public static boolean isExtensionsAvailable() {
final Jenkins jenkins = Jenkins.getInstance();
return jenkins != null && jenkins.getInitLevel().compareTo(InitMilestone.EXTENSIONS_AUGMENTED) >= 0;
}
public static void initPageVariables(JellyContext context) {
StaplerRequest currentRequest = Stapler.getCurrentRequest();
String rootURL = currentRequest.getContextPath();
@@ -419,6 +438,7 @@ public class Functions {
* JEXL now supports the real ternary operator "x?y:z", so this work around
* is no longer necessary.
*/
@Deprecated
public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) {
return cond ? thenValue : elseValue;
}
@@ -1554,6 +1574,7 @@ public class Functions {
* @deprecated
* Use {@link #calcCheckUrl}
*/
@Deprecated
public String getCheckUrl(String userDefined, Object descriptor, String field) {
if(userDefined!=null || field==null) return userDefined;
if (descriptor instanceof Descriptor) {
@@ -1804,6 +1825,7 @@ public class Functions {
* @deprecated as of 1.451
* Use {@link #getAvatar}
*/
@Deprecated
public String getUserAvatar(User user, String avatarSize) {
return getAvatar(user,avatarSize);
}
@@ -1868,9 +1890,10 @@ public class Functions {
TcpSlaveAgentListener tal = j.tcpSlaveAgentListener;
if (tal !=null) {
rsp.setIntHeader("X-Hudson-CLI-Port", tal.getPort());
rsp.setIntHeader("X-Jenkins-CLI-Port", tal.getPort());
rsp.setIntHeader("X-Jenkins-CLI2-Port", tal.getPort());
int p = TcpSlaveAgentListener.CLI_PORT !=null ? TcpSlaveAgentListener.CLI_PORT : tal.getPort();
rsp.setIntHeader("X-Hudson-CLI-Port", p);
rsp.setIntHeader("X-Jenkins-CLI-Port", p);
rsp.setIntHeader("X-Jenkins-CLI2-Port", p);
rsp.setHeader("X-Jenkins-CLI-Host", TcpSlaveAgentListener.CLI_HOST_NAME);
}
}
+13
View File
@@ -133,6 +133,7 @@ public abstract class Launcher {
* figure out the current {@link Computer} from within a build, use
* {@link Computer#currentComputer()}
*/
@Deprecated
public Computer getComputer() {
for( Computer c : Jenkins.getInstance().getComputers() )
if(c.getChannel()==channel)
@@ -412,6 +413,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String cmd, Map<String,String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,Util.mapToEnv(env),out,workDir);
}
@@ -420,6 +422,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, Map<String, String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd, Util.mapToEnv(env), out, workDir);
}
@@ -428,6 +431,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, Map<String, String> env, InputStream in, OutputStream out) throws IOException {
return launch(cmd, Util.mapToEnv(env), in, out);
}
@@ -449,6 +453,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, boolean[] mask, Map<String, String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd, mask, Util.mapToEnv(env), out, workDir);
}
@@ -470,6 +475,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, boolean[] mask, Map<String, String> env, InputStream in, OutputStream out) throws IOException {
return launch(cmd, mask, Util.mapToEnv(env), in, out);
}
@@ -478,6 +484,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String cmd,String[] env,OutputStream out, FilePath workDir) throws IOException {
return launch(Util.tokenize(cmd),env,out,workDir);
}
@@ -486,6 +493,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, String[] env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd, env, null, out, workDir);
}
@@ -494,6 +502,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, String[] env, InputStream in, OutputStream out) throws IOException {
return launch(cmd, env, in, out, null);
}
@@ -515,6 +524,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, boolean[] mask, String[] env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd, mask, env, null, out, workDir);
}
@@ -536,6 +546,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public final Proc launch(String[] cmd, boolean[] mask, String[] env, InputStream in, OutputStream out) throws IOException {
return launch(cmd, mask, env, in, out, null);
}
@@ -554,6 +565,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public Proc launch(String[] cmd, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException {
return launch(launch().cmds(cmd).envs(env).stdin(in).stdout(out).pwd(workDir));
}
@@ -576,6 +588,7 @@ public abstract class Launcher {
* @deprecated as of 1.311
* Use {@link #launch()} and its associated builder pattern
*/
@Deprecated
public Proc launch(String[] cmd, boolean[] mask, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException {
return launch(launch().cmds(cmd).masks(mask).envs(env).stdin(in).stdout(out).pwd(workDir));
}
@@ -283,6 +283,7 @@ public class MarkupText extends AbstractMarkupText {
* Use {@link #toString(boolean)} to be explicit about the escape mode.
*/
@Override
@Deprecated
public String toString() {
return toString(false);
}
+1
View File
@@ -164,6 +164,7 @@ public abstract class Plugin implements Saveable {
* @since 1.233
* @deprecated as of 1.305 override {@link #configure(StaplerRequest,JSONObject)} instead
*/
@Deprecated
public void configure(JSONObject formData) throws IOException, ServletException, FormException {
}
@@ -151,6 +151,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
* {@link PluginManager} can now live longer than {@link jenkins.model.Jenkins} instance, so
* use {@code Hudson.getInstance().servletContext} instead.
*/
@Deprecated
public final ServletContext context;
/**
+1
View File
@@ -431,6 +431,7 @@ public abstract class Proc {
*
* @deprecated as of 1.399. Replaced by {@link Launcher.RemoteLauncher.ProcImpl}
*/
@Deprecated
public static final class RemoteProc extends Proc {
private final Future<Integer> process;
@@ -165,6 +165,7 @@ public final class ProxyConfiguration extends AbstractDescribableImpl<ProxyConfi
* @deprecated
* Use {@link #createProxy(String)}
*/
@Deprecated
public Proxy createProxy() {
return createProxy(null);
}
@@ -43,6 +43,7 @@ public class StructuredForm {
* @deprecated
* Use {@link StaplerRequest#getSubmittedForm()}. Since 1.238.
*/
@Deprecated
public static JSONObject get(StaplerRequest req) throws ServletException {
return req.getSubmittedForm();
}
@@ -204,6 +204,18 @@ public final class TcpSlaveAgentListener extends Thread {
* TODO: think about how to expose this (including whether this needs to be exposed at all.)
*/
public static String CLI_HOST_NAME = System.getProperty(TcpSlaveAgentListener.class.getName()+".hostName");
/**
* Port number that we advertise the CLI client to connect to.
* This is primarily for the case where the port that Jenkins runs is different from the port
* that external world should connect to, because of the presence of NAT / port-forwarding / TCP reverse
* proxy.
*
* If left to null, fall back to {@link #getPort()}
*
* @since 1.611
*/
public static Integer CLI_PORT = Integer.getInteger(TcpSlaveAgentListener.class.getName()+".port");
}
/*
@@ -59,6 +59,7 @@ public class UDPBroadcastThread extends Thread {
* @deprecated as of 1.416
* Use {@link #UDPBroadcastThread(Jenkins)}
*/
@Deprecated
public UDPBroadcastThread(Hudson jenkins) throws IOException {
this((Jenkins)jenkins);
}
+37 -11
View File
@@ -131,7 +131,7 @@ public class Util {
public static String replaceMacro( @CheckForNull String s, @Nonnull Map<String,String> properties) {
return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
}
/**
* Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>.
*
@@ -143,7 +143,7 @@ public class Util {
if (s == null) {
return null;
}
int idx=0;
while(true) {
Matcher m = VARIABLE.matcher(s);
@@ -370,6 +370,30 @@ public class Util {
}
}
/**
* A mostly accurate check of whether a path is a relative path or not. This is designed to take a path against
* an unknown operating system so may give invalid results.
*
* @param path the path.
* @return {@code true} if the path looks relative.
* @since 1.606
*/
public static boolean isRelativePath(String path) {
if (path.startsWith("/"))
return false;
if (path.startsWith("\\\\") && path.length() > 3 && path.indexOf('\\', 3) != -1)
return false; // a UNC path which is the most absolute you can get on windows
if (path.length() >= 3 && ':' == path.charAt(1)) {
// never mind that the drive mappings can be changed between sessions, we just want to
// know if the 3rd character is a `\` (or a '/' is acceptable too)
char p = path.charAt(0);
if (('A' <= p && p <= 'Z') || ('a' <= p && p <= 'z')) {
return path.charAt(2) != '\\' && path.charAt(2) != '/';
}
}
return true;
}
/**
* Creates a new temporary directory.
*/
@@ -624,7 +648,7 @@ public class Util {
* Converts a string into 128-bit AES key.
* @since 1.308
*/
@Nonnull
@Nonnull
public static SecretKey toAes128Key(@Nonnull String s) {
try {
// turn secretKey into 256 bit hash
@@ -743,13 +767,14 @@ public class Util {
/**
* Combines number and unit, with a plural suffix if needed.
*
* @deprecated
* Use individual localization methods instead.
*
* @deprecated
* Use individual localization methods instead.
* See {@link Messages#Util_year(Object)} for an example.
* Deprecated since 2009-06-24, remove method after 2009-12-24.
*/
@Nonnull
@Deprecated
public static String combine(long n, @Nonnull String suffix) {
String s = Long.toString(n)+' '+suffix;
if(n!=1)
@@ -780,7 +805,7 @@ public class Util {
* {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
* a single path component to that method (it will encode /, but this method does not).
*/
@Nonnull
@Nonnull
public static String encode(@Nonnull String s) {
try {
boolean escaped = false;
@@ -888,7 +913,7 @@ public class Util {
/**
* Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.
*/
@Nonnull
@Nonnull
public static String escape(@Nonnull String text) {
if (text==null) return null;
StringBuilder buf = new StringBuilder(text.length()+64);
@@ -1112,7 +1137,7 @@ public class Util {
* @param symlinkPath
* Where to create a symlink in (relative to {@code baseDir})
*/
public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath,
public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath,
@Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException {
try {
if (createSymlinkJava7(baseDir, targetPath, symlinkPath)) {
@@ -1245,6 +1270,7 @@ public class Util {
* @deprecated as of 1.456
* Use {@link #resolveSymlink(File)}
*/
@Deprecated
public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
return resolveSymlink(link);
}
@@ -1346,7 +1372,7 @@ public class Util {
* @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
* be removed but I'm not sure if it is considered part of the public API
* that needs to be maintained for backwards compatibility.
* Use {@link #encode(String)} instead.
* Use {@link #encode(String)} instead.
*/
@Deprecated
public static String encodeRFC2396(String url) {
@@ -1367,7 +1393,7 @@ public class Util {
s = "<span class=error style='display:inline-block'>"+s+"</span>";
return s;
}
/**
* Returns the parsed string if parsed successful; otherwise returns the default number.
* If the string is null, empty or a ParseException is thrown then the defaultNumber
@@ -48,6 +48,7 @@ public class CliProtocol extends AgentProtocol {
* @deprecated as of 1.559
* Use {@link #Handler(NioChannelHub, Socket)}
*/
@Deprecated
public Handler(Socket socket) {
this(null,socket);
}
@@ -37,6 +37,7 @@ public class CliProtocol2 extends CliProtocol {
* @deprecated as of 1.559
* Use {@link #Handler2(NioChannelHub, Socket)}
*/
@Deprecated
public Handler2(Socket socket) {
super(socket);
}
@@ -30,10 +30,12 @@ import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.FieldSetter;
import org.kohsuke.args4j.spi.Setter;
import org.kohsuke.args4j.spi.OptionHandler;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
@@ -79,6 +81,16 @@ class MethodBinder {
public boolean isMultiValued() {
return false;
}
@Override
public FieldSetter asFieldSetter() {
return null;
}
@Override
public AnnotatedElement asAnnotatedElement() {
return p;
}
};
Option option = p.annotation(Option.class);
if (option!=null) {
@@ -148,5 +160,10 @@ class MethodBinder {
public Class<? extends Annotation> annotationType() {
return base.annotationType();
}
@Override
public boolean hidden() {
return base.hidden();
}
}
}
@@ -413,6 +413,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @deprecated as of 1.467
* Please use {@link hudson.model.Run.RunExecution}
*/
@Deprecated
public abstract class AbstractRunner extends AbstractBuildExecution {
}
@@ -691,6 +692,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @deprecated as of 1.356
* Use {@link #performAllBuildSteps(BuildListener, Map, boolean)}
*/
@Deprecated
protected final void performAllBuildStep(BuildListener listener, Map<?,? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
performAllBuildSteps(listener,buildSteps.values(),phase);
}
@@ -703,6 +705,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @deprecated as of 1.356
* Use {@link #performAllBuildSteps(BuildListener, Iterable, boolean)}
*/
@Deprecated
protected final void performAllBuildStep(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
performAllBuildSteps(listener,buildSteps,phase);
}
@@ -712,6 +715,8 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
*
* @param phase
* true for the post build processing, and false for the final "run after finished" execution.
*
* @return false if any build step failed
*/
protected final boolean performAllBuildSteps(BuildListener listener, Iterable<? extends BuildStep> buildSteps, boolean phase) throws InterruptedException, IOException {
boolean r = true;
@@ -721,20 +726,33 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
if (!perform(bs,listener)) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, bs});
r = false;
if (phase) {
setResult(Result.FAILURE);
}
}
} catch (Exception e) {
reportError(bs, e, listener, phase);
r = false;
} catch (LinkageError e) {
reportError(bs, e, listener, phase);
r = false;
}
}
return r;
}
private void reportError(BuildStep bs, Throwable e, BuildListener listener, boolean phase) {
String msg = "Publisher " + bs.getClass().getName() + " aborted due to exception";
e.printStackTrace(listener.error(msg));
LOGGER.log(WARNING, msg, e);
final String publisher = ((Publisher) bs).getDescriptor().getDisplayName();
if (e instanceof AbortException) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, publisher});
listener.error("Publisher '" + publisher + "' failed: " + e.getMessage());
} else {
String msg = "Publisher '" + publisher + "' aborted due to exception: ";
e.printStackTrace(listener.error(msg));
LOGGER.log(WARNING, msg, e);
}
if (phase) {
setResult(Result.FAILURE);
}
@@ -1051,6 +1069,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
/**
* @deprecated Use {@link #getAction(Class)} on {@link AbstractTestResultAction}.
*/
@Deprecated
public Action getTestResultAction() {
try {
return getAction(Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass("hudson.tasks.test.AbstractTestResultAction").asSubclass(Action.class));
@@ -1062,6 +1081,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
/**
* @deprecated Use {@link #getAction(Class)} on {@link AggregatedTestResultAction}.
*/
@Deprecated
public Action getAggregatedTestResultAction() {
try {
return getAction(Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass("hudson.tasks.test.AggregatedTestResultAction").asSubclass(Action.class));
@@ -1340,6 +1360,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @deprecated as of 1.489
* Use {@link #doStop()}
*/
@Deprecated
public void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
doStop().generateResponse(req,rsp,this);
}
@@ -34,7 +34,6 @@ import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;
@@ -48,8 +47,6 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
private static final Logger LOGGER = Logger.getLogger(AbstractCIBase.class.getName());
private final transient Object updateComputerLock = new Object();
/**
* If you are calling this on Hudson something is wrong.
*
@@ -64,8 +61,9 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
/**
* @deprecated
* Why are you calling a method that always returns ""?
* You probably want o call {@link Jenkins#getRootUrl()}
* You probably want to call {@link Jenkins#getRootUrl()}
*/
@Deprecated
public String getUrl() {
return "";
}
@@ -137,15 +135,20 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
used.add(c);
}
/*package*/ void removeComputer(Computer computer) {
Map<Node,Computer> computers = getComputerMap();
for (Map.Entry<Node, Computer> e : computers.entrySet()) {
if (e.getValue() == computer) {
computers.remove(e.getKey());
computer.onRemoved();
return;
/*package*/ void removeComputer(final Computer computer) {
Queue.withLock(new Runnable() {
@Override
public void run() {
Map<Node,Computer> computers = getComputerMap();
for (Map.Entry<Node, Computer> e : computers.entrySet()) {
if (e.getValue() == computer) {
computers.remove(e.getKey());
computer.onRemoved();
return;
}
}
}
}
});
}
/*package*/ @CheckForNull Computer getComputer(Node n) {
@@ -160,36 +163,46 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
* This method tries to reuse existing {@link Computer} objects
* so that we won't upset {@link Executor}s running in it.
*/
protected void updateComputerList(boolean automaticSlaveLaunch) throws IOException {
Map<Node,Computer> computers = getComputerMap();
synchronized(updateComputerLock) {// just so that we don't have two code updating computer list at the same time
Map<String,Computer> byName = new HashMap<String,Computer>();
for (Computer c : computers.values()) {
Node node = c.getNode();
if (node == null)
continue; // this computer is gone
byName.put(node.getNodeName(),c);
}
protected void updateComputerList(final boolean automaticSlaveLaunch) {
final Map<Node,Computer> computers = getComputerMap();
final Set<Computer> old = new HashSet<Computer>(computers.size());
Queue.withLock(new Runnable() {
@Override
public void run() {
Map<String,Computer> byName = new HashMap<String,Computer>();
for (Computer c : computers.values()) {
old.add(c);
Node node = c.getNode();
if (node == null)
continue; // this computer is gone
byName.put(node.getNodeName(),c);
}
final Set<Computer> old = new HashSet<Computer>(computers.values());
Set<Computer> used = new HashSet<Computer>();
Set<Computer> used = new HashSet<Computer>(old.size());
updateComputer(this, byName, used, automaticSlaveLaunch);
for (Node s : getNodes()) {
long start = System.currentTimeMillis();
updateComputer(s, byName, used, automaticSlaveLaunch);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms to update node %s",
System.currentTimeMillis()-start, s.getNodeName()));
}
updateComputer(AbstractCIBase.this, byName, used, automaticSlaveLaunch);
for (Node s : getNodes()) {
long start = System.currentTimeMillis();
updateComputer(s, byName, used, automaticSlaveLaunch);
if(LOG_STARTUP_PERFORMANCE)
LOGGER.info(String.format("Took %dms to update node %s",
System.currentTimeMillis()-start, s.getNodeName()));
}
// find out what computers are removed, and kill off all executors.
// when all executors exit, it will be removed from the computers map.
// so don't remove too quickly
old.removeAll(used);
for (Computer c : old) {
killComputer(c);
// find out what computers are removed, and kill off all executors.
// when all executors exit, it will be removed from the computers map.
// so don't remove too quickly
old.removeAll(used);
// we need to start the process of reducing the executors on all computers as distinct
// from the killing action which should not excessively use the Queue lock.
for (Computer c : old) {
c.inflictMortalWound();
}
}
});
for (Computer c : old) {
// when we get to here, the number of executors should be zero so this call should not need the Queue.lock
killComputer(c);
}
getQueue().scheduleMaintenance();
for (ComputerListener cl : ComputerListener.all())
@@ -216,6 +216,8 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
protected void renameTo(final String newName) throws IOException {
// always synchronize from bigger objects first
final ItemGroup parent = getParent();
String oldName = this.name;
String oldFullName = getFullName();
synchronized (parent) {
synchronized (this) {
// sanity check
@@ -248,9 +250,6 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
}
});
String oldName = this.name;
String oldFullName = getFullName();
File oldRoot = this.getRootDir();
doSetName(newName);
@@ -324,10 +323,9 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
} catch (AbstractMethodError _) {
// ignore
}
ItemListener.fireLocationChange(this, oldFullName);
}
}
ItemListener.fireLocationChange(this, oldFullName);
}
@@ -623,6 +621,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
* @deprecated as of 1.473
* Use {@link #updateByXml(Source)}
*/
@Deprecated
public void updateByXml(StreamSource source) throws IOException {
updateByXml((Source)source);
}
@@ -81,6 +81,7 @@ public abstract class AbstractModelObject implements SearchableModelObject {
* @deprecated
* Use {@link RequirePOST} on your method.
*/
@Deprecated
protected final void requirePOST() throws ServletException {
StaplerRequest req = Stapler.getCurrentRequest();
if (req==null) return; // invoked outside the context of servlet
@@ -505,6 +505,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
@Deprecated
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
@@ -586,6 +587,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
@Deprecated
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
@@ -601,6 +603,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
@Deprecated
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
@@ -797,6 +800,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
@Deprecated
public boolean scheduleBuild() {
return getParameterizedJobMixIn().scheduleBuild();
}
@@ -805,6 +809,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
@Deprecated
public boolean scheduleBuild(int quietPeriod) {
return getParameterizedJobMixIn().scheduleBuild(quietPeriod);
}
@@ -1226,6 +1231,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
@Deprecated
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
@@ -1299,6 +1305,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
@Deprecated
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
@@ -1756,6 +1763,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated as of 1.489
* Inject {@link TimeDuration}.
*/
@Deprecated
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
@@ -1872,6 +1880,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
@Deprecated
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
@@ -2219,6 +2228,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
/**
* @deprecated Just use {@link #CANCEL}.
*/
@Deprecated
public static final Permission ABORT = CANCEL;
/**
+1 -1
View File
@@ -208,7 +208,7 @@ public class Api extends AbstractModelObject {
public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if (req.getParameter("jsonp") == null || permit(req)) {
setHeaders(rsp);
rsp.serveExposedBean(req,bean, Flavor.JSON);
rsp.serveExposedBean(req,bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP);
} else {
rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester");
}
+3 -1
View File
@@ -119,6 +119,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
* proper execution object.
*/
@Restricted(NoExternalUse.class)
@Deprecated
protected Runner createRunner() {
return new BuildExecution();
}
@@ -127,6 +128,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
* @deprecated as of 1.467
* Please use {@link BuildExecution}
*/
@Deprecated
protected class RunnerImpl extends BuildExecution {
}
@@ -193,7 +195,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
performAllBuildSteps(listener, project.getPublishersList(), false);
performAllBuildSteps(listener, project.getProperties(), false);
} catch (Exception x) {
x.printStackTrace(listener.error("Post-build steps failed"));
x.printStackTrace(listener.error(Messages.Build_post_build_steps_failed()));
}
super.cleanUp(listener);
}
@@ -45,6 +45,7 @@ import org.kohsuke.stapler.HttpResponses;
* Use {@link ACL} and {@link Item#BUILD}. This code is only here
* for the backward compatibility.
*/
@Deprecated
public final class BuildAuthorizationToken {
private final String token;
@@ -39,12 +39,14 @@ public interface BuildableItem extends Item, Task {
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
@Deprecated
boolean scheduleBuild();
boolean scheduleBuild(Cause c);
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
@Deprecated
boolean scheduleBuild(int quietPeriod);
boolean scheduleBuild(int quietPeriod, Cause c);
}
@@ -124,6 +124,7 @@ public abstract class Cause {
* Fall back implementation when no other type is available.
* @deprecated since 2009-02-08
*/
@Deprecated
public static class LegacyCodeCause extends Cause {
private StackTraceElement [] stackTrace;
public LegacyCodeCause() {
@@ -162,6 +163,7 @@ public abstract class Cause {
* @deprecated since 2009-02-28
*/
// for backward bytecode compatibility
@Deprecated
public UpstreamCause(AbstractBuild<?,?> up) {
this((Run<?,?>)up);
}
@@ -361,6 +363,7 @@ public abstract class Cause {
* @deprecated 1.428
* use {@link UserIdCause}
*/
@Deprecated
public static class UserCause extends Cause {
private String authenticationName;
public UserCause() {
@@ -113,6 +113,7 @@ public class CauseAction implements FoldableAction, RunAction2 {
* @deprecated as of 1.288
* but left here for backward compatibility.
*/
@Deprecated
public String getShortDescription() {
if(causes.isEmpty()) return "N/A";
return causes.get(0).getShortDescription();
+252 -23
View File
@@ -45,6 +45,7 @@ import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.ComputerListener;
import hudson.slaves.NodeProperty;
@@ -61,10 +62,14 @@ import hudson.util.RunList;
import hudson.util.Futures;
import hudson.util.NamingThreadFactory;
import jenkins.model.Jenkins;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.util.ContextResettingExecutorService;
import jenkins.security.MasterToSlaveCallable;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.QueryParameter;
@@ -77,6 +82,7 @@ import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.args4j.Option;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FilenameFilter;
@@ -176,6 +182,58 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
protected final Object statusChangeLock = new Object();
/**
* Keeps track of stack traces to track the tremination requests for this computer.
*
* @since 1.607
* @see Executor#resetWorkUnit(String)
*/
private transient final List<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
/**
* This method captures the information of a request to terminate a computer instance. Method is public as
* it needs to be called from {@link AbstractCloudSlave} and {@link jenkins.model.Nodes}. In general you should
* not need to call this method directly, however if implementing a custom node type or a different path
* for removing nodes, it may make sense to call this method in order to capture the originating request.
*
* @since 1.607
*/
public void recordTermination() {
StaplerRequest request = Stapler.getCurrentRequest();
if (request != null) {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId(),
request.getRequestURL()
)
));
} else {
terminatedBy.add(new TerminationRequest(
String.format("Termination requested at %s by %s [id=%d]",
new Date(),
Thread.currentThread(),
Thread.currentThread().getId()
)
));
}
}
/**
* Returns the list of captured termination requests for this Computer. This method is used by {@link Executor}
* to provide details on why a Computer was removed in-between work being scheduled against the {@link Executor}
* and the {@link Executor} starting to execute the task.
*
* @return the (possibly empty) list of termination requests.
* @see Executor#resetWorkUnit(String)
* @since 1.607
*/
public List<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(terminatedBy);
}
public Computer(Node node) {
setNode(node);
}
@@ -320,6 +378,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* @deprecated since 2009-01-06. Use {@link #connect(boolean)}
*/
@Deprecated
public final void launch() {
connect(true);
}
@@ -404,6 +463,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @since 1.320
*/
public Future<?> disconnect(OfflineCause cause) {
recordTermination();
offlineCause = cause;
if (Util.isOverridden(Computer.class,getClass(),"disconnect"))
return disconnect(); // legacy subtypes that extend disconnect().
@@ -418,7 +478,9 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @deprecated as of 1.320.
* Use {@link #disconnect(OfflineCause)} and specify the cause.
*/
@Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
@@ -442,7 +504,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
@CLIMethod(name="offline-node")
public void cliOffline(@Option(name="-m",usage="Record the note about why you are disconnecting this node") String cause) throws ExecutionException, InterruptedException {
checkPermission(DISCONNECT);
setTemporarilyOffline(true,new ByCLI(cause));
setTemporarilyOffline(true, new ByCLI(cause));
}
@CLIMethod(name="online-node")
@@ -580,6 +642,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* accidentally call this method.
*/
@Exported
@Deprecated
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
@@ -588,6 +651,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @deprecated as of 1.320.
* Use {@link #setTemporarilyOffline(boolean, OfflineCause)}
*/
@Deprecated
public void setTemporarilyOffline(boolean temporarilyOffline) {
setTemporarilyOffline(temporarilyOffline,null);
}
@@ -698,6 +762,26 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @see #onRemoved()
*/
protected void kill() {
// On most code paths, this should already be zero, and thus this next call becomes a no-op... and more
// importantly it will not acquire a lock on the Queue... not that the lock is bad, more that the lock
// may delay unnecessarily
setNumExecutors(0);
}
/**
* Called by {@link Jenkins#updateComputerList()} to notify {@link Computer} that it will be discarded.
*
* <p>
* Note that at this point {@link #getNode()} returns null.
*
* <p>
* Note that the Queue lock is already held when this method is called.
*
* @see #onRemoved()
*/
@Restricted(NoExternalUse.class)
@GuardedBy("hudson.model.Queue.lock")
/*package*/ void inflictMortalWound() {
setNumExecutors(0);
}
@@ -808,6 +892,32 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
return new ArrayList<OneOffExecutor>(oneOffExecutors);
}
/**
* Used to render the list of executors.
* @return a snapshot of the executor display information
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
int index = 0;
for (Executor e: executors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e));
}
index++;
}
index = 0;
for (OneOffExecutor e: oneOffExecutors) {
if (e.isDisplayCell()) {
result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e));
}
index++;
}
return result;
}
/**
* Returns true if all the executors of this computer are idle.
*/
@@ -867,18 +977,25 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ synchronized void removeExecutor(Executor e) {
executors.remove(e);
addNewExecutorIfNecessary();
if(!isAlive())
{
AbstractCIBase ciBase = Jenkins.getInstance();
ciBase.removeComputer(this);
}
/*package*/ void removeExecutor(final Executor e) {
Queue.withLock(new Runnable() {
@Override
public void run() {
synchronized (Computer.this) {
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) // TODO except from interrupt/doYank this is called while the executor still isActive(), so how could !this.isAlive()?
{
AbstractCIBase ciBase = Jenkins.getInstance();
ciBase.removeComputer(Computer.this);
}
}
}
});
}
/**
* Returns true if any of the executors are functioning.
* Returns true if any of the executors are {@linkplain Executor#isActive active}.
*
* Note that if an executor dies, we'll leave it in {@link #executors} until
* the administrator yanks it out, so that we can see why it died.
@@ -894,10 +1011,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Interrupt all {@link Executor}s.
* Called from {@link Jenkins#cleanUp}.
*/
public void interrupt() {
for (Executor e : executors) {
e.interrupt();
e.interruptForShutdown();
}
}
@@ -937,6 +1055,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @deprecated as of 1.292
* Use {@link #getEnvironment()} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
return getEnvironment();
}
@@ -1036,11 +1155,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
try {
InetAddress ia = InetAddress.getByName(address);
if(!(ia instanceof Inet4Address)) {
LOGGER.fine(address+" is not an IPv4 address");
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
continue;
}
if(!ComputerPinger.checkIsReachable(ia, 3)) {
LOGGER.fine(address+" didn't respond to ping");
LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
continue;
}
cachedHostName = ia.getCanonicalHostName();
@@ -1048,7 +1167,10 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
return cachedHostName;
} catch (IOException e) {
// if a given name fails to parse on this host, we get this error
LOGGER.log(Level.FINE, "Failed to parse "+address,e);
LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
lr.setThrown(e);
lr.setParameters(new Object[]{address});
LOGGER.log(lr);
}
}
@@ -1072,27 +1194,38 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
private static class ListPossibleNames extends MasterToSlaveCallable<List<String>,IOException> {
/**
* In the normal case we would use {@link Computer} as the logger's name, however to
* do that we would have to send the {@link Computer} class over to the remote classloader
* and then it would need to be loaded, which pulls in {@link Jenkins} and loads that
* and then that fails to load as you are not supposed to do that. Another option
* would be to export the logger over remoting, with increased complexity as a result.
* Instead we just use a loger based on this class name and prevent any references to
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<String>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
LOGGER.fine("Listing up IP addresses for "+ni.getDisplayName());
LOGGER.log(Level.FINE, "Listing up IP addresses for {0}", ni.getDisplayName());
Enumeration<InetAddress> e = ni.getInetAddresses();
while (e.hasMoreElements()) {
InetAddress ia = e.nextElement();
if(ia.isLoopbackAddress()) {
LOGGER.fine(ia+" is a loopback address");
LOGGER.log(Level.FINE, "{0} is a loopback address", ia);
continue;
}
if(!(ia instanceof Inet4Address)) {
LOGGER.fine(ia+" is not an IPv4 address");
LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia);
continue;
}
LOGGER.fine(ia+" is a viable candidate");
LOGGER.log(Level.FINE, "{0} is a viable candidate", ia);
names.add(ia.getHostAddress());
}
}
@@ -1121,12 +1254,13 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", getBuilds());
}
public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", getBuilds().failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp );
RSS.forwardToRss(getDisplayName() + suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp);
}
@RequirePOST
@@ -1204,7 +1338,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
_doScript(req, rsp, "_scriptText.jelly");
}
protected void _doScript( StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) throws IOException, ServletException {
Jenkins._doScript(req, rsp, req.getView(this, view), getChannel(), getACL());
}
@@ -1328,7 +1462,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* Handles incremental log.
*/
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req,rsp);
getLogText().doProgressText(req, rsp);
}
/**
@@ -1413,6 +1547,101 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
}
/**
* A value class to provide a consistent snapshot view of the state of an executor to avoid race conditions
* during rendering of the executors list.
*
* @since 1.607
*/
@Restricted(NoExternalUse.class)
public static class DisplayExecutor implements ModelObject {
@Nonnull
private final String displayName;
@Nonnull
private final String url;
@Nonnull
private final Executor executor;
public DisplayExecutor(@Nonnull String displayName, @Nonnull String url, @Nonnull Executor executor) {
this.displayName = displayName;
this.url = url;
this.executor = executor;
}
@Override
@Nonnull
public String getDisplayName() {
return displayName;
}
@Nonnull
public String getUrl() {
return url;
}
@Nonnull
public Executor getExecutor() {
return executor;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DisplayExecutor that = (DisplayExecutor) o;
if (!executor.equals(that.executor)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return executor.hashCode();
}
}
/**
* Used to trace requests to terminate a computer.
*
* @since 1.607
*/
public static class TerminationRequest extends RuntimeException {
private final long when;
public TerminationRequest(String message) {
super(message);
this.when = System.currentTimeMillis();
}
/**
* Returns the when the termination request was created.
*
* @return the difference, measured in milliseconds, between
* the time of the termination request and midnight, January 1, 1970 UTC.
*/
public long getWhen() {
return when;
}
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title());
public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._Computer_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.COMPUTER);
/**
@@ -95,6 +95,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl
* @deprecated as of 1.301
* Use {@link #getMonitors()}.
*/
@Deprecated
public static List<NodeMonitor> get_monitors() {
return monitors.toList();
}
@@ -290,6 +291,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl
JSONObject formData = req.getSubmittedForm();
formData.put("name", fixedName);
// TODO type is probably NodeDescriptor.id but confirm
Node result = NodeDescriptor.all().find(type).newInstance(req, formData);
app.addNode(result);
@@ -30,4 +30,5 @@ import jenkins.model.DependencyDeclarer;
* @deprecated Use {@link DependencyDeclarer} instead.
* @since 1.160
*/
@Deprecated
public interface DependecyDeclarer extends DependencyDeclarer {}
+74 -14
View File
@@ -366,6 +366,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable {
* @deprecated since 1.528
* Use {@link #getCheckMethod(String)}
*/
@Deprecated
public String getCheckUrl(String fieldName) {
return getCheckMethod(fieldName).toCheckUrl();
}
@@ -512,6 +513,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable {
* Implement {@link #newInstance(StaplerRequest, JSONObject)} method instead.
* Deprecated as of 1.145.
*/
@Deprecated
public T newInstance(StaplerRequest req) throws FormException {
throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)");
}
@@ -684,6 +686,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable {
* @deprecated
* As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}.
*/
@Deprecated
public boolean configure( StaplerRequest req ) throws FormException {
return true;
}
@@ -909,14 +912,35 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable {
if (formData!=null) {
for (Object o : JSONArray.fromObject(formData)) {
JSONObject jo = (JSONObject)o;
String kind = jo.optString("$class", null);
if (kind == null) {
// Legacy: Remove once plugins have been staged onto $class
kind = jo.getString("kind");
Descriptor<T> d = null;
// 'kind' and '$class' are mutually exclusive (see class-entry.jelly), but to be more lenient on the reader side,
// we check them both anyway. 'kind' (which maps to ID) is more unique than '$class', which can have multiple matching
// Descriptors, so we prefer 'kind' if it's present.
String kind = jo.optString("kind", null);
if (kind != null) {
// Only applies when Descriptor.getId is overridden.
// Note that kind is only supported here,
// *not* inside the StaplerRequest.bindJSON which is normally called by newInstance
// (since Descriptor.newInstance is not itself available to Stapler).
// If you merely override getId for some reason, but use @DataBoundConstructor on your Describable,
// there is no problem; but you can only rely on newInstance being called at top level.
d = findById(descriptors, kind);
}
if (d == null) {
kind = jo.optString("$class");
if (kind != null) { // else we will fall through to the warning
// This is the normal case.
d = findByDescribableClassName(descriptors, kind);
if (d == null) {
// Deprecated system where stapler-class was the Descriptor class name (rather than Describable class name).
d = findByClassName(descriptors, kind);
}
}
}
Descriptor<T> d = find(descriptors, kind);
if (d != null) {
items.add(d.newInstance(req, jo));
} else {
LOGGER.log(Level.WARNING, "Received unexpected form data element: {0}", jo);
}
}
}
@@ -925,22 +949,58 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable {
}
/**
* Finds a descriptor from a collection by its class name.
* Finds a descriptor from a collection by its ID.
* @param id should match {@link #getId}
* @since 1.610
*/
public static @CheckForNull <T extends Descriptor> T find(Collection<? extends T> list, String className) {
public static @CheckForNull <T extends Descriptor> T findById(Collection<? extends T> list, String id) {
for (T d : list) {
if(d.getClass().getName().equals(className))
return d;
}
// Since we introduced Descriptor.getId(), it is a preferred method of identifying descriptor by a string.
// To make that migration easier without breaking compatibility, let's also match up with the id.
for (T d : list) {
if(d.getId().equals(className))
if(d.getId().equals(id))
return d;
}
return null;
}
/**
* Finds a descriptor from a collection by the class name of the {@link Descriptor}.
* This is useless as of the introduction of {@link #getId} and so only very old compatibility code needs it.
*/
private static @CheckForNull <T extends Descriptor> T findByClassName(Collection<? extends T> list, String className) {
for (T d : list) {
if(d.getClass().getName().equals(className))
return d;
}
return null;
}
/**
* Finds a descriptor from a collection by the class name of the {@link Describable} it describes.
* @param className should match {@link Class#getName} of a {@link #clazz}
* @since 1.610
*/
public static @CheckForNull <T extends Descriptor> T findByDescribableClassName(Collection<? extends T> list, String className) {
for (T d : list) {
if(d.clazz.getName().equals(className))
return d;
}
return null;
}
/**
* Finds a descriptor from a collection by its class name or ID.
* @deprecated choose between {@link #findById} or {@link #findByDescribableClassName}
*/
public static @CheckForNull <T extends Descriptor> T find(Collection<? extends T> list, String string) {
T d = findByClassName(list, string);
if (d != null) {
return d;
}
return findById(list, string);
}
/**
* @deprecated choose between {@link #findById} or {@link #findByDescribableClassName}
*/
public static @CheckForNull Descriptor find(String className) {
return find(ExtensionList.lookup(Descriptor.class),className);
}
@@ -75,6 +75,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
* @deprecated as of 1.297
* Use {@link #DirectoryBrowserSupport(ModelObject, FilePath, String, String, boolean)}
*/
@Deprecated
public DirectoryBrowserSupport(ModelObject owner, String title) {
this(owner, (VirtualFile) null, title, null, false);
}
@@ -147,6 +148,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
* Instead of calling this method explicitly, just return the {@link DirectoryBrowserSupport} object
* from the {@code doXYZ} method and let Stapler generate a response for you.
*/
@Deprecated
public void serveFile(StaplerRequest req, StaplerResponse rsp, FilePath root, String icon, boolean serveDirIndex) throws IOException, ServletException, InterruptedException {
serveFile(req, rsp, root.toVirtualFile(), icon, serveDirIndex);
}
+441 -103
View File
@@ -46,13 +46,18 @@ import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -60,20 +65,24 @@ import static hudson.model.queue.Executables.*;
import static java.util.logging.Level.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.queue.AsynchronousExecution;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* Thread that executes builds.
* Since 1.536, {@link Executor}s start threads on-demand.
* The entire logic should use {@link #isActive()} instead of {@link #isAlive()}
* in order to check if the {@link Executor} it ready to take tasks.
* <p>Callers should use {@link #isActive()} instead of {@link #isAlive()}.
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final @Nonnull Computer owner;
private final Queue queue;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
@GuardedBy("lock")
private long startTime;
/**
* Used to track when a job was last executed.
@@ -87,29 +96,41 @@ public class Executor extends Thread implements ModelObject {
/**
* {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle.
*/
private volatile Queue.Executable executable;
@GuardedBy("lock")
private Queue.Executable executable;
/**
* Used to mark that the execution is continuing asynchronously even though {@link Executor} as {@link Thread}
* has finished.
*/
@GuardedBy("lock")
private AsynchronousExecution asynchronousExecution;
/**
* When {@link Queue} allocates a work for this executor, this field is set
* and the executor is {@linkplain Thread#start() started}.
*/
private volatile WorkUnit workUnit;
@GuardedBy("lock")
private WorkUnit workUnit;
private Throwable causeOfDeath;
private boolean induceDeath;
private volatile boolean started;
@GuardedBy("lock")
private boolean started;
/**
* When the executor is interrupted, we allow the code that interrupted the thread to override the
* result code it prefers.
*/
@GuardedBy("lock")
private Result interruptStatus;
/**
* Cause of interruption. Access needs to be synchronized.
*/
@GuardedBy("lock")
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
public Executor(@Nonnull Computer owner, int n) {
@@ -124,6 +145,9 @@ public class Executor extends Thread implements ModelObject {
interrupt(Result.ABORTED);
}
void interruptForShutdown() {
interrupt(Result.ABORTED, true);
}
/**
* Interrupt the execution,
* but instead of marking the build as aborted, mark it as specified result.
@@ -131,13 +155,17 @@ public class Executor extends Thread implements ModelObject {
* @since 1.417
*/
public void interrupt(Result result) {
interrupt(result, false);
}
private void interrupt(Result result, boolean forShutdown) {
Authentication a = Jenkins.getAuthentication();
if (a == ACL.SYSTEM)
interrupt(result, new CauseOfInterruption[0]);
interrupt(result, forShutdown, new CauseOfInterruption[0]);
else {
// worth recording who did it
// avoid using User.get() to avoid deadlock.
interrupt(result, new UserInterruption(a.getName()));
interrupt(result, forShutdown, new UserInterruption(a.getName()));
}
}
@@ -145,31 +173,48 @@ public class Executor extends Thread implements ModelObject {
* Interrupt the execution. Mark the cause and the status accordingly.
*/
public void interrupt(Result result, CauseOfInterruption... causes) {
interrupt(result, false, causes);
}
private void interrupt(Result result, boolean forShutdown, CauseOfInterruption... causes) {
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, String.format("%s is interrupted(%s): %s", getDisplayName(), result, Util.join(Arrays.asList(causes),",")), new InterruptedException());
synchronized (this) {
lock.writeLock().lock();
try {
if (!started) {
// not yet started, so simply dispose this
owner.removeExecutor(this);
return;
}
}
interruptStatus = result;
synchronized (this.causes) {
interruptStatus = result;
for (CauseOfInterruption c : causes) {
if (!this.causes.contains(c))
this.causes.add(c);
}
if (asynchronousExecution != null) {
asynchronousExecution.interrupt(forShutdown);
} else {
super.interrupt();
}
} finally {
lock.writeLock().unlock();
}
super.interrupt();
}
public Result abortResult() {
Result r = interruptStatus;
if (r==null) r = Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method.
return r;
lock.readLock().lock();
try {
Result r = interruptStatus;
if (r == null) r =
Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method.
return r;
} finally {
lock.readLock().unlock();
}
}
/**
@@ -180,11 +225,14 @@ public class Executor extends Thread implements ModelObject {
public void recordCauseOfInterruption(Run<?,?> build, TaskListener listener) {
List<CauseOfInterruption> r;
// atomically get&clear causes, and minimize the lock.
synchronized (causes) {
// atomically get&clear causes.
lock.writeLock().lock();
try {
if (causes.isEmpty()) return;
r = new ArrayList<CauseOfInterruption>(causes);
causes.clear();
} finally {
lock.writeLock().unlock();
}
build.addAction(new InterruptedBuildAction(r));
@@ -192,9 +240,64 @@ public class Executor extends Thread implements ModelObject {
c.print(listener);
}
/**
* There are some cases where an executor is started but the node is removed or goes off-line before we are ready
* to start executing the assigned work unit. This method is called to clear the assigned work unit so that
* the {@link Queue#maintain()} method can return the item to the buildable state.
*
* Note: once we create the {@link Executable} we cannot unwind the state and the build will have to end up being
* marked as a failure.
*/
private void resetWorkUnit(String reason) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
try {
pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason);
if (owner.getTerminatedBy().isEmpty()) {
pw.print("No termination trace available.");
} else {
pw.println("Termination trace follows:");
for (Computer.TerminationRequest request: owner.getTerminatedBy()) {
request.printStackTrace(pw);
}
}
} finally {
pw.close();
}
LOGGER.log(WARNING, writer.toString());
lock.writeLock().lock();
try {
if (executable != null) {
throw new IllegalStateException("Cannot reset the work unit after the executable has been created");
}
workUnit = null;
} finally {
lock.writeLock().unlock();
}
}
@Override
public void run() {
startTime = System.currentTimeMillis();
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
final WorkUnit workUnit;
lock.writeLock().lock();
try {
startTime = System.currentTimeMillis();
workUnit = this.workUnit;
} finally {
lock.writeLock().unlock();
}
ACL.impersonate(ACL.SYSTEM);
@@ -204,14 +307,45 @@ public class Executor extends Thread implements ModelObject {
SubTask task;
// transition from idle to building.
// perform this state change as an atomic operation wrt other queue operations
synchronized (queue) {
workUnit.setExecutor(this);
queue.onStartExecuting(this);
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue");
task = workUnit.work;
executable = task.createExecutable();
workUnit.setExecutable(executable);
task = Queue.withLock(new java.util.concurrent.Callable<SubTask>() {
@Override
public SubTask call() throws Exception {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread was ready to execute");
return null;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread was ready to execute");
return null;
}
// after this point we cannot unwind the assignment of the work unit, if the owner
// is removed or goes off-line then the build will just have to fail.
workUnit.setExecutor(Executor.this);
queue.onStartExecuting(Executor.this);
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue");
SubTask task = workUnit.work;
Executable executable = task.createExecutable();
lock.writeLock().lock();
try {
Executor.this.executable = executable;
} finally {
lock.writeLock().unlock();
}
workUnit.setExecutable(executable);
return task;
}
});
Executable executable;
lock.readLock().lock();
try {
if (this.workUnit == null) {
// we called resetWorkUnit, so bail. Outer finally will remove this and schedule queue maintenance
return;
}
executable = this.executable;
} finally {
lock.readLock().unlock();
}
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is going to execute "+executable);
@@ -238,23 +372,26 @@ public class Executor extends Thread implements ModelObject {
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is now executing "+executable);
queue.execute(executable, task);
} catch (AsynchronousExecution x) {
lock.writeLock().lock();
try {
x.setExecutor(this);
this.asynchronousExecution = x;
} finally {
lock.writeLock().unlock();
}
} catch (Throwable e) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", e);
workUnit.context.abort(e);
problems = e;
} finally {
long time = System.currentTimeMillis()-startTime;
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" completed "+executable+" in "+time+"ms");
boolean needFinish1;
lock.readLock().lock();
try {
workUnit.context.synchronizeEnd(executable,problems,time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
needFinish1 = asynchronousExecution == null;
} finally {
workUnit.setExecutor(null);
lock.readLock().unlock();
}
if (needFinish1) {
finish1(problems);
}
}
} catch (InterruptedException e) {
@@ -267,14 +404,52 @@ public class Executor extends Thread implements ModelObject {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} finally {
if (causeOfDeath==null)
// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
queue.scheduleMaintenance();
if (asynchronousExecution == null) {
finish2();
}
}
}
private void finish1(@CheckForNull Throwable problems) {
if (problems != null) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", problems);
workUnit.context.abort(problems);
}
long time = System.currentTimeMillis() - startTime;
LOGGER.log(FINE, "{0} completed {1} in {2}ms", new Object[]{getName(), executable, time});
try {
workUnit.context.synchronizeEnd(this, executable, problems, time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
private void finish2() {
for (RuntimeException e1: owner.getTerminatedBy()) LOGGER.log(Level.WARNING, String.format("%s termination trace", getName()), e1);
if (causeOfDeath == null) {// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
}
if (this instanceof OneOffExecutor) {
owner.remove((OneOffExecutor) this);
}
queue.scheduleMaintenance();
}
@Restricted(NoExternalUse.class)
public void completedAsynchronous(@CheckForNull Throwable error) {
try {
finish1(error);
} finally {
finish2();
}
asynchronousExecution = null;
}
/**
* For testing only. Simulate a fatal unexpected failure.
*/
@@ -290,7 +465,12 @@ public class Executor extends Thread implements ModelObject {
*/
@Exported
public @CheckForNull Queue.Executable getCurrentExecutable() {
return executable;
lock.readLock().lock();
try {
return executable;
} finally {
lock.readLock().unlock();
}
}
/**
@@ -302,7 +482,12 @@ public class Executor extends Thread implements ModelObject {
*/
@Exported
public WorkUnit getCurrentWorkUnit() {
return workUnit;
lock.readLock().lock();
try {
return workUnit;
} finally {
lock.readLock().unlock();
}
}
/**
@@ -311,13 +496,19 @@ public class Executor extends Thread implements ModelObject {
* to that point yet.
*/
public FilePath getCurrentWorkspace() {
Executable e = executable;
if(e==null) return null;
if (e instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) e;
return ab.getWorkspace();
lock.readLock().lock();
try {
if (executable == null) {
return null;
}
if (executable instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) executable;
return ab.getWorkspace();
}
return null;
} finally {
lock.readLock().unlock();
}
return null;
}
/**
@@ -344,40 +535,89 @@ public class Executor extends Thread implements ModelObject {
*/
@Exported
public boolean isIdle() {
return executable==null;
lock.readLock().lock();
try {
return workUnit == null && executable == null;
} finally {
lock.readLock().unlock();
}
}
/**
* The opposite of {@link #isIdle()} &mdash; the executor is doing some work.
*/
public boolean isBusy() {
return executable!=null;
lock.readLock().lock();
try {
return workUnit != null || executable != null;
} finally {
lock.readLock().unlock();
}
}
/**
* Check if executor is ready to accept tasks.
* This method becomes the critical one since 1.536, which introduces the
* on-demand creation of executor threads. The entire logic should use
* this method instead of {@link #isAlive()}, because it provides wrong
* information for non-started threads.
* on-demand creation of executor threads. Callers should use
* this method instead of {@link #isAlive()}, which would be incorrect for
* non-started threads or running {@link AsynchronousExecution}.
* @return True if the executor is available for tasks
* @since 1.536
*/
public boolean isActive() {
return !started || isAlive();
lock.readLock().lock();
try {
return !started || asynchronousExecution != null || isAlive();
} finally {
lock.readLock().unlock();
}
}
/**
* If currently running in asynchronous mode, returns that handle.
* @since 1.607
*/
public @CheckForNull AsynchronousExecution getAsynchronousExecution() {
lock.readLock().lock();
try {
return asynchronousExecution;
} finally {
lock.readLock().unlock();
}
}
/**
* If this executor is running an {@link AsynchronousExecution} and that execution wants to hide the display
* cell for the executor (because there is another executor displaying the job progress and we don't want to
* confuse the user) then this method will return {@code false} to indicate to {@code executors.jelly} that
* the executor cell should be hidden.
*
* @return {@code true} iff the {@code executorCell.jelly} for this {@link Executor} should be displayed in
* {@code executors.jelly}.
* @since 1.607
* @see AsynchronousExecution#displayCell()
*/
public boolean isDisplayCell() {
AsynchronousExecution asynchronousExecution = getAsynchronousExecution();
return asynchronousExecution == null || asynchronousExecution.displayCell();
}
/**
* Returns true if this executor is waiting for a task to execute.
*/
public boolean isParking() {
return !started;
lock.readLock().lock();
try {
return !started;
} finally {
lock.readLock().unlock();
}
}
/**
* If this thread dies unexpectedly, obtain the cause of the failure.
*
* @return null if the death is expected death or the thread is {@link #isAlive() still alive}.
* @return null if the death is expected death or the thread {@link #isActive}.
* @since 1.142
*/
public Throwable getCauseOfDeath() {
@@ -392,13 +632,24 @@ public class Executor extends Thread implements ModelObject {
*/
@Exported
public int getProgress() {
Queue.Executable e = executable;
if(e==null) return -1;
long d = Executables.getEstimatedDurationFor(e);
if(d<0) return -1;
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d <= 0) {
return -1;
}
int num = (int)(getElapsedTime()*100/d);
if(num>=100) num=99;
int num = (int) (getElapsedTime() * 100 / d);
if (num >= 100) {
num = 99;
}
return num;
}
@@ -411,22 +662,35 @@ public class Executor extends Thread implements ModelObject {
*/
@Exported
public boolean isLikelyStuck() {
Queue.Executable e = executable;
if(e==null) return false;
long d;
long elapsed;
lock.readLock().lock();
try {
if (executable == null) {
return false;
}
long elapsed = getElapsedTime();
long d = Executables.getEstimatedDurationFor(e);
if(d>=0) {
elapsed = getElapsedTime();
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d >= 0) {
// if it's taking 10 times longer than ETA, consider it stuck
return d*10 < elapsed;
return d * 10 < elapsed;
} else {
// if no ETA is available, a build taking longer than a day is considered stuck
return TimeUnit2.MILLISECONDS.toHours(elapsed)>24;
return TimeUnit2.MILLISECONDS.toHours(elapsed) > 24;
}
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
lock.readLock().lock();
try {
return System.currentTimeMillis() - startTime;
} finally {
lock.readLock().unlock();
}
}
/**
@@ -435,7 +699,12 @@ public class Executor extends Thread implements ModelObject {
* @since 1.440
*/
public long getTimeSpentInQueue() {
return startTime - workUnit.context.item.buildableStartMilliseconds;
lock.readLock().lock();
try {
return startTime - workUnit.context.item.buildableStartMilliseconds;
} finally {
lock.readLock().unlock();
}
}
/**
@@ -453,14 +722,25 @@ public class Executor extends Thread implements ModelObject {
* until the build completes.
*/
public String getEstimatedRemainingTime() {
Queue.Executable e = executable;
if(e==null) return Messages.Executor_NotAvailable();
long d;
lock.readLock().lock();
try {
if (executable == null) {
return Messages.Executor_NotAvailable();
}
long d = Executables.getEstimatedDurationFor(e);
if(d<0) return Messages.Executor_NotAvailable();
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return Messages.Executor_NotAvailable();
}
long eta = d-getElapsedTime();
if(eta<=0) return Messages.Executor_NotAvailable();
long eta = d - getElapsedTime();
if (eta <= 0) {
return Messages.Executor_NotAvailable();
}
return Util.getTimeSpanString(eta);
}
@@ -470,14 +750,25 @@ public class Executor extends Thread implements ModelObject {
* it as a number of milli-seconds.
*/
public long getEstimatedRemainingTimeMillis() {
Queue.Executable e = executable;
if(e==null) return -1;
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
long d = Executables.getEstimatedDurationFor(e);
if(d<0) return -1;
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
long eta = d-getElapsedTime();
if(eta<=0) return -1;
long eta = d - getElapsedTime();
if (eta <= 0) {
return -1;
}
return eta;
}
@@ -488,14 +779,19 @@ public class Executor extends Thread implements ModelObject {
* @see #start(WorkUnit)
*/
@Override
public synchronized void start() {
public void start() {
throw new UnsupportedOperationException();
}
/*protected*/ synchronized void start(WorkUnit task) {
this.workUnit = task;
super.start();
started = true;
/*protected*/ void start(WorkUnit task) {
lock.writeLock().lock();
try {
this.workUnit = task;
super.start();
started = true;
} finally {
lock.writeLock().unlock();
}
}
@@ -504,6 +800,7 @@ public class Executor extends Thread implements ModelObject {
* Use {@link #doStop()}.
*/
@RequirePOST
@Deprecated
public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
doStop().generateResponse(req,rsp,this);
}
@@ -515,10 +812,14 @@ public class Executor extends Thread implements ModelObject {
*/
@RequirePOST
public HttpResponse doStop() {
Queue.Executable e = executable;
if(e!=null) {
Tasks.getOwnerTaskOf(getParentOf(e)).checkAbortPermission();
interrupt();
lock.writeLock().lock(); // need write lock as interrupt will change the field
try {
if (executable != null) {
Tasks.getOwnerTaskOf(getParentOf(executable)).checkAbortPermission();
interrupt();
}
} finally {
lock.writeLock().unlock();
}
return HttpResponses.forwardToPreviousPage();
}
@@ -529,7 +830,7 @@ public class Executor extends Thread implements ModelObject {
@RequirePOST
public HttpResponse doYank() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
if (isAlive())
if (isActive())
throw new Failure("Can't yank a live executor");
owner.removeExecutor(this);
return HttpResponses.redirectViaContextPath("/");
@@ -539,8 +840,12 @@ public class Executor extends Thread implements ModelObject {
* Checks if the current user has a permission to stop this build.
*/
public boolean hasStopPermission() {
Queue.Executable e = executable;
return e!=null && Tasks.getOwnerTaskOf(getParentOf(e)).hasAbortPermission();
lock.readLock().lock();
try {
return executable != null && Tasks.getOwnerTaskOf(getParentOf(executable)).hasAbortPermission();
} finally {
lock.readLock().unlock();
}
}
public @Nonnull Computer getOwner() {
@@ -551,11 +856,16 @@ public class Executor extends Thread implements ModelObject {
* Returns when this executor started or should start being idle.
*/
public long getIdleStartMilliseconds() {
if (isIdle())
return Math.max(creationTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, Executables.getEstimatedDurationFor(executable)),
System.currentTimeMillis() + 15000);
lock.readLock().lock();
try {
if (isIdle())
return Math.max(creationTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, Executables.getEstimatedDurationFor(executable)),
System.currentTimeMillis() + 15000);
}
} finally {
lock.readLock().unlock();
}
}
@@ -593,6 +903,33 @@ public class Executor extends Thread implements ModelObject {
return IMPERSONATION.get();
}
/**
* Finds the executor currently running a given process.
* @param executable a possibly running executable
* @return the executor (possibly a {@link OneOffExecutor}) whose {@link Executor#getCurrentExecutable} matches that,
* or null if it could not be found (for example because the execution has already completed)
* @since 1.607
*/
public static @CheckForNull Executor of(Executable executable) {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
return null;
}
for (Computer computer : jenkins.getComputers()) {
for (Executor executor : computer.getExecutors()) {
if (executor.getCurrentExecutable() == executable) {
return executor;
}
}
for (Executor executor : computer.getOneOffExecutors()) {
if (executor.getCurrentExecutable() == executable) {
return executor;
}
}
}
return null;
}
/**
* Returns the estimated duration for the executable.
* Protects against {@link AbstractMethodError}s if the {@link Executable} implementation
@@ -601,6 +938,7 @@ public class Executor extends Thread implements ModelObject {
* @deprecated as of 1.388
* Use {@link Executables#getEstimatedDurationFor(Queue.Executable)}
*/
@Deprecated
public static long getEstimatedDurationFor(Executable e) {
return Executables.getEstimatedDurationFor(e);
}
@@ -38,6 +38,7 @@ public class FreeStyleProject extends Project<FreeStyleProject,FreeStyleBuild> i
/**
* @deprecated as of 1.390
*/
@Deprecated
public FreeStyleProject(Jenkins parent, String name) {
super(parent, name);
}
+22 -1
View File
@@ -60,12 +60,14 @@ public class Hudson extends Jenkins {
* List of registered {@link hudson.model.listeners.ItemListener}s.
* @deprecated as of 1.286
*/
@Deprecated
private transient final CopyOnWriteList<ItemListener> itemListeners = ExtensionListView.createCopyOnWriteList(ItemListener.class);
/**
* List of registered {@link hudson.slaves.ComputerListener}s.
* @deprecated as of 1.286
*/
@Deprecated
private transient final CopyOnWriteList<ComputerListener> computerListeners = ExtensionListView.createCopyOnWriteList(ComputerListener.class);
/** @deprecated Here only for compatibility. Use {@link Jenkins#getInstance} instead. */
@@ -89,6 +91,7 @@ public class Hudson extends Jenkins {
* @deprecated as of 1.286.
* Use {@link ItemListener#all()}.
*/
@Deprecated
public CopyOnWriteList<ItemListener> getJobListeners() {
return itemListeners;
}
@@ -99,6 +102,7 @@ public class Hudson extends Jenkins {
* @deprecated as of 1.286.
* Use {@link ComputerListener#all()}.
*/
@Deprecated
public CopyOnWriteList<ComputerListener> getComputerListeners() {
return computerListeners;
}
@@ -109,6 +113,7 @@ public class Hudson extends Jenkins {
* @deprecated
* Use {@link #getNode(String)}. Since 1.252.
*/
@Deprecated
public Slave getSlave(String name) {
Node n = getNode(name);
if (n instanceof Slave)
@@ -120,8 +125,9 @@ public class Hudson extends Jenkins {
* @deprecated
* Use {@link #getNodes()}. Since 1.252.
*/
@Deprecated
public List<Slave> getSlaves() {
return (List)slaves;
return (List)getNodes();
}
/**
@@ -130,6 +136,7 @@ public class Hudson extends Jenkins {
* @deprecated
* Use {@link #setNodes(List)}. Since 1.252.
*/
@Deprecated
public void setSlaves(List<Slave> slaves) throws IOException {
setNodes(slaves);
}
@@ -139,6 +146,7 @@ public class Hudson extends Jenkins {
* Left only for the compatibility of URLs.
* Should not be invoked for any other purpose.
*/
@Deprecated
public TopLevelItem getJob(String name) {
return getItem(name);
}
@@ -147,6 +155,7 @@ public class Hudson extends Jenkins {
* @deprecated
* Used only for mapping jobs to URL in a case-insensitive fashion.
*/
@Deprecated
public TopLevelItem getJobCaseInsensitive(String name) {
String match = Functions.toEmailSafeString(name);
for(TopLevelItem item : getItems()) {
@@ -161,6 +170,7 @@ public class Hudson extends Jenkins {
* @deprecated as of 1.317
* Use {@link #doQuietDown()} instead.
*/
@Deprecated
public synchronized void doQuietDown(StaplerResponse rsp) throws IOException, ServletException {
doQuietDown().generateResponse(null, rsp, this);
}
@@ -171,6 +181,7 @@ public class Hudson extends Jenkins {
* @deprecated
* As on 1.267, moved to "/log/rss..."
*/
@Deprecated
public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs));
@@ -180,6 +191,7 @@ public class Hudson extends Jenkins {
* @deprecated as of 1.294
* Define your own check method, instead of relying on this generic one.
*/
@Deprecated
public void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
doFieldCheck(
fixEmpty(req.getParameter("value")),
@@ -201,6 +213,7 @@ public class Hudson extends Jenkins {
* Either use client-side validation (e.g. class="required number")
* or define your own check method, instead of relying on this generic one.
*/
@Deprecated
public FormValidation doFieldCheck(@QueryParameter(fixEmpty=true) String value,
@QueryParameter(fixEmpty=true) String type,
@QueryParameter(fixEmpty=true) String errorText,
@@ -236,6 +249,7 @@ public class Hudson extends Jenkins {
* @deprecated
* Use {@link Functions#isWindows()}.
*/
@Deprecated
public static boolean isWindows() {
return File.pathSeparatorChar==';';
}
@@ -244,6 +258,7 @@ public class Hudson extends Jenkins {
* @deprecated
* Use {@link hudson.Platform#isDarwin()}
*/
@Deprecated
public static boolean isDarwin() {
return Platform.isDarwin();
}
@@ -252,6 +267,7 @@ public class Hudson extends Jenkins {
* @deprecated since 2007-12-18.
* Use {@link #checkPermission(hudson.security.Permission)}
*/
@Deprecated
public static boolean adminCheck() throws IOException {
return adminCheck(Stapler.getCurrentRequest(), Stapler.getCurrentResponse());
}
@@ -260,6 +276,7 @@ public class Hudson extends Jenkins {
* @deprecated since 2007-12-18.
* Use {@link #checkPermission(hudson.security.Permission)}
*/
@Deprecated
public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException {
if (isAdmin(req)) return true;
@@ -285,6 +302,7 @@ public class Hudson extends Jenkins {
* if appropriate), then identify a suitable {@link hudson.security.AccessControlled} object to check its permission
* against.
*/
@Deprecated
public static boolean isAdmin() {
return Jenkins.getInstance().getACL().hasPermission(ADMINISTER);
}
@@ -294,6 +312,7 @@ public class Hudson extends Jenkins {
* Define a custom {@link hudson.security.Permission} and check against ACL.
* See {@link #isAdmin()} for more instructions.
*/
@Deprecated
public static boolean isAdmin(StaplerRequest req) {
return isAdmin();
}
@@ -305,6 +324,7 @@ public class Hudson extends Jenkins {
/**
* @deprecated only here for backward comp
*/
@Deprecated
public static final class MasterComputer extends Jenkins.MasterComputer {
// no op
}
@@ -312,6 +332,7 @@ public class Hudson extends Jenkins {
/**
* @deprecated only here for backward comp
*/
@Deprecated
public static class CloudList extends Jenkins.CloudList {
public CloudList(Jenkins h) {
super(h);
@@ -176,6 +176,7 @@ public interface Item extends PersistenceRoot, SearchableModelObject, AccessCont
* This method is only intended for the remote API clients who cannot resolve relative references
* (even this won't work for the same reason, which should be fixed.)
*/
@Deprecated
String getAbsoluteUrl();
/**
@@ -31,6 +31,7 @@ import hudson.util.CopyOnWriteMap;
import hudson.util.Function1;
import hudson.util.IOUtils;
import jenkins.model.Jenkins;
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
@@ -190,6 +191,8 @@ public abstract class ItemGroupMixIn {
if (descriptor == null) {
throw new Failure("No item type ‘" + mode + "’ is known");
}
descriptor.checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, descriptor);
// create empty job and redirect to the project config screen
result = createProject(descriptor, name, true);
@@ -214,6 +217,8 @@ public abstract class ItemGroupMixIn {
public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException {
acl.checkPermission(Item.CREATE);
src.checkPermission(Item.EXTENDED_READ);
src.getDescriptor().checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, src.getDescriptor());
T result = (T)createProject(src.getDescriptor(),name,false);
@@ -249,6 +254,7 @@ public abstract class ItemGroupMixIn {
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
final File dir = configXml.getParentFile();
dir.mkdirs();
boolean success = false;
try {
IOUtils.copy(xml,configXml);
@@ -258,6 +264,10 @@ public abstract class ItemGroupMixIn {
return (TopLevelItem) Items.load(parent, dir);
}
});
success = acl.getACL().hasCreatePermission(Jenkins.getAuthentication(), parent, result.getDescriptor())
&& result.getDescriptor().isApplicableIn(parent);
add(result);
ItemListener.fireOnCreated(result);
@@ -265,15 +275,24 @@ public abstract class ItemGroupMixIn {
return result;
} catch (IOException e) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(dir);
success = false;
throw e;
} catch (RuntimeException e) {
success = false;
throw e;
} finally {
if (!success) {
// if anything fails, delete the config file to avoid further confusion
Util.deleteRecursive(dir);
}
}
}
public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify )
throws IOException {
acl.checkPermission(Item.CREATE);
type.checkApplicableIn(parent);
acl.getACL().checkCreatePermission(parent, type);
Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
if(parent.getItem(name)!=null)
@@ -29,11 +29,14 @@ import hudson.Extension;
import hudson.XmlFile;
import hudson.model.listeners.ItemListener;
import hudson.remoting.Callable;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.triggers.Trigger;
import hudson.util.DescriptorList;
import hudson.util.EditDistance;
import hudson.util.XStream2;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.apache.commons.lang.StringUtils;
import java.io.File;
@@ -63,6 +66,7 @@ public class Items {
* @deprecated as of 1.286
* Use {@link #all()} for read access and {@link Extension} for registration.
*/
@Deprecated
public static final List<TopLevelItemDescriptor> LIST = (List)new DescriptorList<TopLevelItem>(TopLevelItem.class);
/**
@@ -112,6 +116,42 @@ public class Items {
return Jenkins.getInstance().<TopLevelItem,TopLevelItemDescriptor>getDescriptorList(TopLevelItem.class);
}
/**
* Returns all the registered {@link TopLevelItemDescriptor}s that the current security principal is allowed to
* create within the specified item group.
*
* @since TODO
*/
public static List<TopLevelItemDescriptor> all(ItemGroup c) {
return all(Jenkins.getAuthentication(), c);
}
/**
* Returns all the registered {@link TopLevelItemDescriptor}s that the specified security principal is allowed to
* create within the specified item group.
*
* @since TODO
*/
public static List<TopLevelItemDescriptor> all(Authentication a, ItemGroup c) {
List<TopLevelItemDescriptor> result = new ArrayList<TopLevelItemDescriptor>();
ACL acl;
if (c instanceof AccessControlled) {
acl = ((AccessControlled) c).getACL();
} else {
// fall back to root
acl = Jenkins.getInstance().getACL();
}
for (TopLevelItemDescriptor d: all()) {
if (acl.hasCreatePermission(a, c, d) && d.isApplicableIn(c)) {
result.add(d);
}
}
return result;
}
/**
* @deprecated Underspecified what the parameter is. {@link Descriptor#getId}? A {@link Describable} class name?
*/
public static TopLevelItemDescriptor getDescriptor(String fqcn) {
return Descriptor.find(all(), fqcn);
}
@@ -133,6 +173,7 @@ public class Items {
* @deprecated as of 1.406
* Use {@link #fromNameList(ItemGroup, String, Class)}
*/
@Deprecated
public static <T extends Item> List<T> fromNameList(String list, Class<T> type) {
return fromNameList(null,list,type);
}
+2
View File
@@ -80,6 +80,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific<JDK>, En
* @deprecated as of 1.304
* Use {@link #getHome()}
*/
@Deprecated
public String getJavaHome() {
return getHome();
}
@@ -108,6 +109,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific<JDK>, En
/**
* @deprecated as of 1.460. Use {@link #buildEnvVars(EnvVars)}
*/
@Deprecated
public void buildEnvVars(Map<String,String> env) {
String home = getHome();
if (home == null) {
+3
View File
@@ -442,6 +442,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* @deprecated as of 1.503
* Use {@link #getBuildDiscarder()}.
*/
@Deprecated
public LogRotator getLogRotator() {
if (logRotator instanceof LogRotator)
return (LogRotator) logRotator;
@@ -452,6 +453,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* @deprecated as of 1.503
* Use {@link #setBuildDiscarder(BuildDiscarder)}
*/
@Deprecated
public void setLogRotator(LogRotator logRotator) throws IOException {
setBuildDiscarder(logRotator);
}
@@ -744,6 +746,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* as of 1.372. Should just do {@code getBuilds().byTimestamp(s,e)} to avoid code bloat in {@link Job}.
*/
@WithBridgeMethods(List.class)
@Deprecated
public RunList<RunT> getBuildsByTimestamp(long start, long end) {
return getBuilds().byTimestamp(start,end);
}
@@ -104,6 +104,7 @@ public abstract class JobProperty<J extends Job<?,?>> implements ReconfigurableD
* @deprecated
* as of 1.341. Override {@link #getJobActions(Job)} instead.
*/
@Deprecated
public Action getJobAction(J job) {
return null;
}
@@ -34,6 +34,7 @@ import java.util.List;
* @author Kohsuke Kawaguchi
* @deprecated since 1.281
*/
@Deprecated
public class Jobs {
/**
* List of all installed {@link JobPropertyDescriptor} types.
@@ -47,6 +48,7 @@ public class Jobs {
* Use {@link JobPropertyDescriptor#all()} for read access,
* and {@link Extension} for registration.
*/
@Deprecated
public static final List<JobPropertyDescriptor> PROPERTIES = (List)
new DescriptorList<JobProperty<?>>((Class)JobProperty.class);
}
+27 -6
View File
@@ -39,6 +39,7 @@ import hudson.model.labels.LabelExpressionLexer;
import hudson.model.labels.LabelExpressionParser;
import hudson.model.labels.LabelOperatorPrecedence;
import hudson.model.labels.LabelVisitor;
import hudson.model.queue.SubTask;
import hudson.security.ACL;
import hudson.slaves.NodeProvisioner;
import hudson.slaves.Cloud;
@@ -107,6 +108,17 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
public int computeQueueLength() {
return Jenkins.getInstance().getQueue().countBuildableItemsFor(Label.this);
}
@Override
protected Set<Node> getNodes() {
return Label.this.getNodes();
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
final Label l = item.getAssignedLabelFor(subTask);
return l != null && Label.this.matches(l.name);
}
};
this.nodeProvisioner = new NodeProvisioner(this, loadStatistics);
}
@@ -374,7 +386,7 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
for (TopLevelItem topLevelItem : Jenkins.getInstance().getItemMap().values()) {
if (topLevelItem instanceof AbstractProject) {
final AbstractProject project = (AbstractProject) topLevelItem;
if (this.equals(project.getAssignedLabel())) {
if (matches(project.getAssignedLabelString())) {
result++;
}
}
@@ -389,7 +401,7 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
for (Item i : parent.getItems()) {
if (i instanceof AbstractProject) {
final AbstractProject project = (AbstractProject) i;
if (this.equals(project.getAssignedLabel())) {
if (matches(project.getAssignedLabelString())) {
result++;
}
}
@@ -497,23 +509,32 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
@Override
public boolean equals(Object that) {
public final boolean equals(Object that) {
if (this == that) return true;
if (that == null || getClass() != that.getClass()) return false;
return name.equals(((Label)that).name);
return matches(((Label)that).name);
}
@Override
public int hashCode() {
public final int hashCode() {
return name.hashCode();
}
public int compareTo(Label that) {
public final int compareTo(Label that) {
return this.name.compareTo(that.name);
}
/**
* Evaluates whether the current label name is equal to the name parameter.
*
*/
private final boolean matches(String name) {
return this.name.equals(name);
}
@Override
public String toString() {
return name;
@@ -50,6 +50,7 @@ import java.io.InputStreamReader;
* @author Kohsuke Kawaguchi
* @deprecated moved to stapler, as of Hudson 1.220
*/
@Deprecated
public class LargeText {
/**
* Represents the data source of this text.
@@ -128,6 +128,7 @@ public abstract class LoadBalancer implements ExtensionPoint {
* @deprecated as of 1.377
* The only implementation in the core now is the one based on consistent hash.
*/
@Deprecated
public static final LoadBalancer DEFAULT = CONSISTENT_HASH;
@@ -47,6 +47,9 @@ import org.kohsuke.stapler.export.Exported;
import java.awt.*;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
/**
@@ -66,6 +69,33 @@ import java.util.List;
*/
@ExportedBean
public abstract class LoadStatistics {
/**
* {@code true} if and only if the new way of building statistics has been implemented by this class.
* @since 1.607
*/
private final boolean modern;
/**
* Number of executors defined for Jenkins and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries definedExecutors;
/**
* Number of executors on-line and how it changes over time. Replaces {@link #totalExecutors}
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries onlineExecutors;
/**
* Number of executors in the process of coming on-line and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries connectingExecutors;
/**
* Number of busy executors and how it changes over time.
*/
@@ -73,9 +103,27 @@ public abstract class LoadStatistics {
public final MultiStageTimeSeries busyExecutors;
/**
* Number of total executors and how it changes over time.
* Number of executors not executing and how it changes over time. Note the these executors may not be able to
* take work, see {@link #availableExecutors}.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries idleExecutors;
/**
* Number of executors not executing and available to take work and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries availableExecutors;
/**
* Number of total executors and how it changes over time.
* @deprecated use {@link #onlineExecutors}. Note {@code totalExecutors==onlineExecutors} for backward
* compatibility support.
*/
@Exported
@Deprecated
public final MultiStageTimeSeries totalExecutors;
/**
@@ -84,32 +132,81 @@ public abstract class LoadStatistics {
@Exported
public final MultiStageTimeSeries queueLength;
protected LoadStatistics(int initialTotalExecutors, int initialBusyExecutors) {
this.totalExecutors = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_TotalExecutors(), ColorPalette.BLUE, initialTotalExecutors,DECAY);
protected LoadStatistics(int initialOnlineExecutors, int initialBusyExecutors) {
this.definedExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_DefinedExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors, DECAY);
this.onlineExecutors = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_OnlineExecutors(), ColorPalette.BLUE, initialOnlineExecutors,DECAY);
this.connectingExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_ConnectingExecutors(),
ColorPalette.YELLOW, 0, DECAY);
this.busyExecutors = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_BusyExecutors(), ColorPalette.RED, initialBusyExecutors,DECAY);
this.idleExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_IdleExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors - initialBusyExecutors, DECAY);
this.availableExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_AvailableExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors - initialBusyExecutors, DECAY);
this.queueLength = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_QueueLength(),ColorPalette.GREY, 0, DECAY);
this.totalExecutors = onlineExecutors;
modern = isModern(getClass());
}
/*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) {
// cannot use Util.isOverridden as these are protected methods.
boolean hasGetNodes = false;
boolean hasMatches = false;
while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) {
if (!hasGetNodes) {
try {
final Method getNodes = clazz.getDeclaredMethod("getNodes");
hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers());
} catch (NoSuchMethodException e) {
// ignore
}
}
if (!hasMatches) {
try {
final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class);
hasMatches = !Modifier.isAbstract(getNodes.getModifiers());
} catch (NoSuchMethodException e) {
// ignore
}
}
if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) {
clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass();
}
}
return hasGetNodes && hasMatches;
}
/**
* @deprecated use {@link #idleExecutors} directly.
*/
@Deprecated
public float getLatestIdleExecutors(TimeScale timeScale) {
return totalExecutors.pick(timeScale).getLatest() - busyExecutors.pick(timeScale).getLatest();
return idleExecutors.pick(timeScale).getLatest();
}
/**
* Computes the # of idle executors right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getIdleExecutors()}
*/
@Deprecated
public abstract int computeIdleExecutors();
/**
* Computes the # of total executors right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getOnlineExecutors()}
*/
@Deprecated
public abstract int computeTotalExecutors();
/**
* Computes the # of queue length right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getQueueLength()}
*/
@Deprecated
public abstract int computeQueueLength();
/**
@@ -155,9 +252,10 @@ public abstract class LoadStatistics {
}
protected void configureRenderer(LineAndShapeRenderer renderer) {
renderer.setSeriesPaint(0, ColorPalette.BLUE); // total
renderer.setSeriesPaint(0, ColorPalette.BLUE); // online
renderer.setSeriesPaint(1, ColorPalette.RED); // busy
renderer.setSeriesPaint(2, ColorPalette.GREY); // queue
renderer.setSeriesPaint(3, ColorPalette.YELLOW);// available
}
/**
@@ -165,7 +263,7 @@ public abstract class LoadStatistics {
* of the load statistics graph.
*/
public TrendChart createTrendChart(TimeScale timeScale) {
return MultiStageTimeSeries.createTrendChart(timeScale,totalExecutors,busyExecutors,queueLength);
return MultiStageTimeSeries.createTrendChart(timeScale,onlineExecutors,busyExecutors,queueLength,availableExecutors);
}
/**
@@ -180,27 +278,103 @@ public abstract class LoadStatistics {
}
/**
* Updates {@link #totalExecutors} and {@link #busyExecutors} by using
* the current snapshot value.
*
* {@link #queueLength} is updated separately via {@link LoadStatisticsUpdater} to
* improve the efficiency because we are counting this for all {@link LoadStatistics} at once.
* @deprecated use {@link #updateCounts(LoadStatisticsSnapshot)}
*/
@Deprecated
protected void updateExecutorCounts() {
int t = computeTotalExecutors();
int i = computeIdleExecutors();
totalExecutors.update(t);
busyExecutors.update(t-i);
updateCounts(computeSnapshot());
}
/**
* Updates all the series from the current snapshot.
* @param current the current snapshot.
* @since 1.607
*/
protected void updateCounts(LoadStatisticsSnapshot current) {
definedExecutors.update(current.getDefinedExecutors());
onlineExecutors.update(current.getOnlineExecutors());
connectingExecutors.update(current.getConnectingExecutors());
busyExecutors.update(current.getBusyExecutors());
idleExecutors.update(current.getIdleExecutors());
availableExecutors.update(current.getAvailableExecutors());
queueLength.update(current.getQueueLength());
}
/**
* Returns the {@link Node} instances that this statistic counts.
* @return the {@link Node}
* @since 1.607
*/
protected abstract Iterable<Node> getNodes();
/**
* Returns {@code true} is the specified {@link SubTask} from the {@link Queue} should be counted.
* @param item the {@link Queue.Item} that the {@link SubTask belongs to}
* @param subTask the {@link SubTask}
* @return {@code true} IFF the specified {@link SubTask} from the {@link Queue} should be counted.
* @since 1.607
*/
protected abstract boolean matches(Queue.Item item, SubTask subTask);
/**
* Computes a self-consistent snapshot of the load statistics.
*
* Note: The original method of computing load statistics would compute the total and idle counts independently
* which could lead to counting errors while jobs started in between the different state counting operations.
* By returning a {@link LoadStatisticsSnapshot} we get a single consistent view of the counts which was valid
* for at least one point in time during the execution of this method.
*
* @return a self-consistent snapshot of the load statistics.
* @since 1.607
*/
public LoadStatisticsSnapshot computeSnapshot() {
if (modern) {
return computeSnapshot(Jenkins.getInstance().getQueue().getBuildableItems());
} else {
int t = computeTotalExecutors();
int i = computeIdleExecutors();
return new LoadStatisticsSnapshot(t, t, Math.max(i-t,0), Math.max(t-i,0), i, i, computeQueueLength());
}
}
/**
* Computes the self-consistent snapshot with the specified queue items.
* @param queue the queue items.
* @return a self-consistent snapshot of the load statistics.
* @since 1.607
*/
protected LoadStatisticsSnapshot computeSnapshot(Iterable<Queue.BuildableItem> queue) {
final LoadStatisticsSnapshot.Builder builder = LoadStatisticsSnapshot.builder();
final Iterable<Node> nodes = getNodes();
if (nodes != null) {
for (Node node : nodes) {
builder.with(node);
}
}
int q = 0;
if (queue != null) {
for (Queue.BuildableItem item : queue) {
for (SubTask st : item.task.getSubTasks()) {
if (matches(item, st))
q++;
}
}
}
return builder.withQueueLength(q).build();
}
/**
* With 0.90 decay ratio for every 10sec, half reduction is about 1 min.
*
* Put differently, the half reduction time is {@code CLOCK*log(0.5)/log(DECAY)}
*/
public static final float DECAY = Float.parseFloat(System.getProperty(LoadStatistics.class.getName()+".decay","0.9"));
/**
* Load statistics clock cycle in milliseconds. Specify a small value for quickly debugging this feature and node provisioning through cloud.
*/
public static int CLOCK = Integer.getInteger(LoadStatistics.class.getName()+".clock",10*1000);
public static int CLOCK = Integer.getInteger(LoadStatistics.class.getName() + ".clock", 10 * 1000);
/**
* Periodically update the load statistics average.
@@ -217,16 +391,13 @@ public abstract class LoadStatistics {
// update statistics on slaves
for( Label l : j.getLabels() ) {
l.loadStatistics.updateExecutorCounts();
l.loadStatistics.queueLength.update(count(bis, l));
l.loadStatistics.updateCounts(l.loadStatistics.computeSnapshot(bis));
}
// update statistics of the entire system
j.unlabeledLoad.updateExecutorCounts();
j.unlabeledLoad.queueLength.update(count(bis, null));
j.unlabeledLoad.updateCounts(j.unlabeledLoad.computeSnapshot(bis));
j.overallLoad.updateExecutorCounts();
j.overallLoad.queueLength.update(bis.size());
j.overallLoad.updateCounts(j.overallLoad.computeSnapshot(bis));
}
private int count(List<Queue.BuildableItem> bis, Label l) {
@@ -239,4 +410,245 @@ public abstract class LoadStatistics {
return q;
}
}
/**
* Holds a snapshot of the current statistics.
* @since 1.607
*/
@ExportedBean
public static class LoadStatisticsSnapshot implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The total number of executors that Jenkins currently knows, this includes all off-line slaves.
*/
private final int definedExecutors;
/**
* The total number of executors that are currently on-line.
*/
private final int onlineExecutors;
/**
* The total number of executors that are currently in the process of connecting to Jenkins.
*/
private final int connectingExecutors;
/**
* The total number of executors that are currently busy running jobs.
*/
private final int busyExecutors;
/**
* The total number of executors that are currently on-line and idle. This includes executors that are
* not accepting tasks.
*/
private final int idleExecutors;
/**
* The total number of executors that are currently on-line, idle and accepting tasks.
*/
private final int availableExecutors;
/**
* The number of items in the queue.
*/
private final int queueLength;
private LoadStatisticsSnapshot(
int definedExecutors, int onlineExecutors, int connectingExecutors,
int busyExecutors, int idleExecutors, int availableExecutors,
int queueLength) {
this.definedExecutors = definedExecutors;
this.onlineExecutors = onlineExecutors;
this.connectingExecutors = connectingExecutors;
// assert definedExecutors == onlineExecutors + connectingExecutors;
this.busyExecutors = busyExecutors;
this.idleExecutors = idleExecutors;
// assert onlineExecutors == busyExecutors + idleExecutors;
this.availableExecutors = availableExecutors;
// assert availableExecutors <= idleExecutors;
this.queueLength = queueLength;
}
/**
* The total number of executors that Jenkins currently knows, this includes all off-line slaves.
*/
@Exported
public int getDefinedExecutors() {
return definedExecutors;
}
/**
* The total number of executors that are currently on-line.
*/
@Exported
public int getOnlineExecutors() {
return onlineExecutors;
}
/**
* The total number of executors that are currently in the process of connecting to Jenkins.
*/
@Exported
public int getConnectingExecutors() {
return connectingExecutors;
}
/**
* The total number of executors that are currently busy running jobs.
*/
@Exported
public int getBusyExecutors() {
return busyExecutors;
}
/**
* The total number of executors that are currently on-line and idle. This includes executors that are
* not accepting tasks.
*/
@Exported
public int getIdleExecutors() {
return idleExecutors;
}
/**
* The total number of executors that are currently on-line, idle and accepting tasks.
*/
@Exported
public int getAvailableExecutors() {
return availableExecutors;
}
/**
* The number of items in the queue.
*/
@Exported
public int getQueueLength() {
return queueLength;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadStatisticsSnapshot that = (LoadStatisticsSnapshot) o;
if (availableExecutors != that.availableExecutors) {
return false;
}
if (busyExecutors != that.busyExecutors) {
return false;
}
if (connectingExecutors != that.connectingExecutors) {
return false;
}
if (definedExecutors != that.definedExecutors) {
return false;
}
if (idleExecutors != that.idleExecutors) {
return false;
}
if (onlineExecutors != that.onlineExecutors) {
return false;
}
if (queueLength != that.queueLength) {
return false;
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int result = definedExecutors;
result = 31 * result + onlineExecutors;
result = 31 * result + connectingExecutors;
result = 31 * result + busyExecutors;
result = 31 * result + idleExecutors;
result = 31 * result + availableExecutors;
result = 31 * result + queueLength;
return result;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("LoadStatisticsSnapshot{");
sb.append("definedExecutors=").append(definedExecutors);
sb.append(", onlineExecutors=").append(onlineExecutors);
sb.append(", connectingExecutors=").append(connectingExecutors);
sb.append(", busyExecutors=").append(busyExecutors);
sb.append(", idleExecutors=").append(idleExecutors);
sb.append(", availableExecutors=").append(availableExecutors);
sb.append(", queueLength=").append(queueLength);
sb.append('}');
return sb.toString();
}
/**
* Use a builder so we can add more stats if needed.
* Not thread safe
* @since 1.607
*/
public static class Builder {
private int definedExecutors;
private int onlineExecutors;
private int connectingExecutors;
private int busyExecutors;
private int idleExecutors;
private int availableExecutors;
private int queueLength;
public LoadStatisticsSnapshot build() {
return new LoadStatisticsSnapshot(
definedExecutors, onlineExecutors, connectingExecutors,
busyExecutors, idleExecutors, availableExecutors,
queueLength
);
}
public Builder withQueueLength(int queueLength) {
this.queueLength = queueLength;
return this;
}
public Builder with(Node node) {
if (node != null)
return with(node.toComputer());
return this;
}
public Builder with(Computer computer) {
if (computer.isOnline()) {
final List<Executor> executors = computer.getExecutors();
final boolean acceptingTasks = computer.isAcceptingTasks();
for (Executor e : executors) {
definedExecutors++;
onlineExecutors++;
if (e.getCurrentWorkUnit() != null) {
busyExecutors++;
} else {
idleExecutors++;
if (acceptingTasks) availableExecutors++;
}
}
} else {
final int numExecutors = computer.getNumExecutors();
definedExecutors += numExecutors;
if (computer.isConnecting()) {
connectingExecutors += numExecutors;
}
}
return this;
}
}
public static Builder builder() {
return new Builder();
}
}
}
@@ -97,6 +97,7 @@ public abstract class ManagementLink implements ExtensionPoint, Action {
* @deprecated as of 1.286
* Use {@link #all()} for read access and put {@link Extension} for registration.
*/
@Deprecated
public static final List<ManagementLink> LIST = ExtensionListView.createList(ManagementLink.class);
/**
@@ -117,7 +118,7 @@ public abstract class ManagementLink implements ExtensionPoint, Action {
* Define if the rendered link will use the default GET method or POST.
* @return true if POST must be used
* @see RequirePOST
* @since TODO
* @since 1.584
*/
public boolean getRequiresPOST() {
return false;
@@ -110,6 +110,7 @@ public class MultiStageTimeSeries implements Serializable {
* @deprecated since 2009-04-05.
* Use {@link #MultiStageTimeSeries(Localizable, Color, float, float)}
*/
@Deprecated
public MultiStageTimeSeries(float initialValue, float decay) {
this(Messages._MultiStageTimeSeries_EMPTY_STRING(), Color.WHITE, initialValue,decay);
}
@@ -133,6 +133,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
*
* @deprecated to indicate that this method isn't really meant to be called by random code.
*/
@Deprecated
public abstract void setNodeName(String name);
/**
@@ -330,6 +331,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* @deprecated as of 1.413
* Use {@link #canTake(Queue.BuildableItem)}
*/
@Deprecated
public CauseOfBlockage canTake(Task task) {
return null;
}
@@ -373,6 +375,10 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
if (c!=null) return c;
}
if (!isAcceptingTasks()) {
return CauseOfBlockage.fromMessage(Messages._Node_BecauseNodeIsNotAcceptingTasks(getNodeName()));
}
// Looks like we can take the task
return null;
}
@@ -36,13 +36,4 @@ public class OneOffExecutor extends Executor {
public OneOffExecutor(Computer owner) {
super(owner,-1);
}
@Override
public void run() {
try {
super.run();
} finally {
owner.remove(this);
}
}
}
@@ -25,6 +25,7 @@ package hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.MultiStageTimeSeries.TrendChart;
import hudson.model.queue.SubTask;
import jenkins.model.Jenkins;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
@@ -47,6 +48,7 @@ public class OverallLoadStatistics extends LoadStatistics {
*/
@Exported
@Restricted(NoExternalUse.class)
@Deprecated
public final MultiStageTimeSeries totalQueueLength = queueLength;
public OverallLoadStatistics() {
@@ -68,11 +70,21 @@ public class OverallLoadStatistics extends LoadStatistics {
return Jenkins.getInstance().getQueue().countBuildableItems();
}
@Override
protected Iterable<Node> getNodes() {
return Jenkins.getActiveInstance().getNodes();
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
return true;
}
/**
* When drawing the overall load statistics, use the total queue length,
* not {@link #queueLength}, which just shows jobs that are to be run on the master.
*/
protected TrendChart createOverallTrendChart(TimeScale timeScale) {
return MultiStageTimeSeries.createTrendChart(timeScale,busyExecutors,totalExecutors,queueLength);
return MultiStageTimeSeries.createTrendChart(timeScale,busyExecutors,onlineExecutors,queueLength,availableExecutors);
}
}
@@ -79,6 +79,7 @@ public abstract class PageDecorator extends Descriptor<PageDecorator> implements
* @deprecated as of 1.425
* Use the default constructor that's less error prone
*/
@Deprecated
protected PageDecorator(Class<? extends PageDecorator> yourClass) {
super(yourClass);
}
@@ -119,6 +120,7 @@ public abstract class PageDecorator extends Descriptor<PageDecorator> implements
* @deprecated as of 1.286
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
@Deprecated
public static final List<PageDecorator> ALL = (List)new DescriptorList<PageDecorator>(PageDecorator.class);
/**
@@ -232,6 +232,7 @@ public abstract class ParameterDefinition implements
* @deprecated as of 1.286
* Use {@link #all()} for read access, and {@link Extension} for registration.
*/
@Deprecated
public static final DescriptorList<ParameterDefinition> LIST = new DescriptorList<ParameterDefinition>(ParameterDefinition.class);
public abstract static class ParameterDescriptor extends
@@ -127,6 +127,7 @@ public abstract class ParameterValue implements Serializable {
* @deprecated as of 1.344
* Use {@link #buildEnvironment(Run, EnvVars)} instead.
*/
@Deprecated
public void buildEnvVars(AbstractBuild<?,?> build, Map<String,String> env) {
if (env instanceof EnvVars) {
if (Util.isOverridden(ParameterValue.class, getClass(), "buildEnvironment", Run.class, EnvVars.class)) {
@@ -222,6 +223,7 @@ public abstract class ParameterValue implements Serializable {
* instead copy them in {@link ParameterDefinition#createValue(StaplerRequest, JSONObject)}
* into {@link ParameterValue}.
*/
@Deprecated
public ParameterDefinition getDefinition() {
throw new UnsupportedOperationException();
}
@@ -64,6 +64,7 @@ public class ParametersAction implements Action, Iterable<ParameterValue>, Queue
/**
* @deprecated since 1.283; kept to avoid warnings loading old build data, but now transient.
*/
@Deprecated
private transient AbstractBuild<?, ?> build;
public ParametersAction(List<ParameterValue> parameters) {
@@ -60,6 +60,7 @@ public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoi
/** @deprecated Use your own logger, or send messages to the logger in {@link AsyncPeriodicWork#execute}. */
@SuppressWarnings("NonConstantLogger")
@Deprecated
protected final Logger logger = Logger.getLogger(getClass().getName());
/**
@@ -130,6 +130,7 @@ public abstract class Project<P extends Project<P,B>,B extends Build<P,B>>
* We will be soon removing the restriction that only one instance of publisher is allowed per type.
* Use {@link #getPublishersList()} instead.
*/
@Deprecated
public Map<Descriptor<Publisher>,Publisher> getPublishers() {
return getPublishersList().toMap();
}
@@ -177,6 +178,7 @@ public abstract class Project<P extends Project<P,B>,B extends Build<P,B>>
* @deprecated as of 1.290
* Use {@code getPublishersList().add(x)}
*/
@Deprecated
public void addPublisher(Publisher buildStep) throws IOException {
getPublishersList().add(buildStep);
}
@@ -187,6 +189,7 @@ public abstract class Project<P extends Project<P,B>,B extends Build<P,B>>
* @deprecated as of 1.290
* Use {@code getPublishersList().remove(x)}
*/
@Deprecated
public void removePublisher(Descriptor<Publisher> descriptor) throws IOException {
getPublishersList().remove(descriptor);
}
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,18 @@
/*
* The MIT License
*
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
*
* 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
@@ -29,6 +29,7 @@ import java.util.Set;
import java.util.Collection;
import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.Nonnull;
@@ -61,7 +62,7 @@ public class ResourceController {
/**
* Union of all {@link Resource}s that are currently in use.
* Updated as a task starts/completes executing.
* Updated as a task starts/completes executing.
*/
private ResourceList inUse = ResourceList.EMPTY;
@@ -74,25 +75,37 @@ public class ResourceController {
* @throws InterruptedException
* the thread can be interrupted while waiting for the available resources.
*/
public void execute(@Nonnull Runnable task, ResourceActivity activity ) throws InterruptedException {
ResourceList resources = activity.getResourceList();
synchronized(this) {
while(inUse.isCollidingWith(resources))
wait();
public void execute(@Nonnull Runnable task, final ResourceActivity activity ) throws InterruptedException {
final ResourceList resources = activity.getResourceList();
_withLock(new Runnable() {
@Override
public void run() {
while(inUse.isCollidingWith(resources))
try {
// TODO revalidate the resource list after re-acquiring lock, for now we just let the build fail
_await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// we have a go
inProgress.add(activity);
inUse = ResourceList.union(inUse,resources);
}
// we have a go
inProgress.add(activity);
inUse = ResourceList.union(inUse,resources);
}
});
try {
task.run();
} finally {
synchronized(this) {
inProgress.remove(activity);
inUse = ResourceList.union(resourceView);
notifyAll();
}
// TODO if AsynchronousExecution, do that later
_withLock(new Runnable() {
@Override
public void run() {
inProgress.remove(activity);
inUse = ResourceList.union(resourceView);
_signalAll();
}
});
}
}
@@ -105,8 +118,17 @@ public class ResourceController {
* another activity might acquire resources before the caller
* gets to call {@link #execute(Runnable, ResourceActivity)}.
*/
public synchronized boolean canRun(ResourceList resources) {
return !inUse.isCollidingWith(resources);
public boolean canRun(final ResourceList resources) {
try {
return _withLock(new Callable<Boolean>() {
@Override
public Boolean call() {
return !inUse.isCollidingWith(resources);
}
});
} catch (Exception e) {
throw new IllegalStateException("Inner callable does not throw exception");
}
}
/**
@@ -117,8 +139,17 @@ public class ResourceController {
* If more than one such resource exists, one is chosen and returned.
* This method is used for reporting what's causing the blockage.
*/
public synchronized Resource getMissingResource(ResourceList resources) {
return resources.getConflict(inUse);
public Resource getMissingResource(final ResourceList resources) {
try {
return _withLock(new Callable<Resource>() {
@Override
public Resource call() {
return resources.getConflict(inUse);
}
});
} catch (Exception e) {
throw new IllegalStateException("Inner callable does not throw exception");
}
}
/**
@@ -133,5 +164,25 @@ public class ResourceController {
return a;
return null;
}
protected void _await() throws InterruptedException {
wait();
}
protected void _signalAll() {
notifyAll();
}
protected void _withLock(Runnable runnable) {
synchronized (this) {
runnable.run();
}
}
protected <V> V _withLock(java.util.concurrent.Callable<V> callable) throws Exception {
synchronized (this) {
return callable.call();
}
}
}
@@ -6,6 +6,7 @@ import hudson.ExtensionPoint;
import jenkins.model.Jenkins;
import java.io.IOException;
import jenkins.model.queue.AsynchronousExecution;
/**
* Extension point that allows plugins to veto the restart.
@@ -46,12 +47,39 @@ public abstract class RestartListener implements ExtensionPoint {
/**
* Default logic. Wait for all the executors to become idle.
* @see AsynchronousExecution#blocksRestart
*/
@Extension
public static class Default extends RestartListener {
@Override
public boolean isReadyToRestart() throws IOException, InterruptedException {
return new ComputerSet().getBusyExecutors() == 0;
for (Computer c : Jenkins.getInstance().getComputers()) {
if (c.isOnline()) {
for (Executor e : c.getExecutors()) {
if (blocksRestart(e)) {
return false;
}
}
for (Executor e : c.getOneOffExecutors()) {
if (blocksRestart(e)) {
return false;
}
}
}
}
return true;
}
private static boolean blocksRestart(Executor e) {
if (e.isBusy()) {
AsynchronousExecution execution = e.getAsynchronousExecution();
if (execution != null) {
return execution.blocksRestart();
} else {
return true;
}
} else {
return false;
}
}
}
}
+14 -18
View File
@@ -47,6 +47,7 @@ import hudson.model.Descriptor.FormException;
import hudson.model.Run.RunExecution;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SaveableListener;
import hudson.model.queue.Executables;
import hudson.model.queue.SubTask;
import hudson.search.SearchIndexBuilder;
import hudson.security.ACL;
@@ -512,25 +513,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* and because of that this might not be necessarily in sync with the return value of {@link #isBuilding()} &mdash;
* an executor holds on to {@link Run} some more time even after the build is finished (for example to
* perform {@linkplain Run.State#POST_PRODUCTION post-production processing}.)
* @see Executables#getExecutor
*/
@Exported
public @CheckForNull Executor getExecutor() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
return null;
}
for (Computer c : j.getComputers()) {
for (Executor e : c.getExecutors()) {
if(e.getCurrentExecutable()==this)
return e;
}
for (Executor e : c.getOneOffExecutors()) {
if(e.getCurrentExecutable()==this) {
return e;
}
}
}
return null;
return this instanceof Queue.Executable ? Executor.of((Queue.Executable) this) : null;
}
/**
@@ -730,9 +717,12 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Gets the string that says how long the build took to run.
*/
public @Nonnull String getDurationString() {
if(isBuilding())
if (hasntStartedYet()) {
return Messages.Run_NotStartedYet();
} else if (isBuilding()) {
return Messages.Run_InProgressDuration(
Util.getTimeSpanString(System.currentTimeMillis()-startTime));
}
return Util.getTimeSpanString(duration);
}
@@ -994,6 +984,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* This method is only intended for the remote API clients who cannot resolve relative references.
*/
@Exported(visibility=2,name="url")
@Deprecated
public final @Nonnull String getAbsoluteUrl() {
return project.getAbsoluteUrl()+getNumber()+'/';
}
@@ -1564,6 +1555,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated as of 1.467
* Please use {@link RunExecution}
*/
@Deprecated
protected abstract class Runner extends RunExecution {}
/**
@@ -1685,6 +1677,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated as of 1.467
* Use {@link #execute(RunExecution)}
*/
@Deprecated
protected final void run(@Nonnull Runner job) {
execute(job);
}
@@ -1793,13 +1786,13 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
state = State.POST_PRODUCTION;
if (listener != null) {
RunListener.fireCompleted(this,listener);
try {
job.cleanUp(listener);
} catch (Exception e) {
handleFatalBuildProblem(listener,e);
// too late to update the result now
}
RunListener.fireCompleted(this,listener);
listener.finished(result);
listener.closeQuietly();
}
@@ -2115,6 +2108,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated as of 1.352
* Use {@code getLogText().doProgressiveText(req,rsp)}
*/
@Deprecated
public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(req,rsp);
}
@@ -2202,6 +2196,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated as of 1.292
* Use {@link #getEnvironment(TaskListener)} instead.
*/
@Deprecated
public Map<String,String> getEnvVars() {
LOGGER.log(WARNING, "deprecated call to Run.getEnvVars\n\tat {0}", new Throwable().getStackTrace()[1]);
try {
@@ -2216,6 +2211,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* @deprecated as of 1.305 use {@link #getEnvironment(TaskListener)}
*/
@Deprecated
public EnvVars getEnvironment() throws IOException, InterruptedException {
LOGGER.log(WARNING, "deprecated call to Run.getEnvironment\n\tat {0}", new Throwable().getStackTrace()[1]);
return getEnvironment(new LogTaskListener(LOGGER, Level.INFO));
@@ -74,6 +74,7 @@ public final class RunMap<R extends Run<?,R>> extends AbstractLazyLoadRunMap<R>
* @deprecated as of 1.485
* Use {@link #RunMap(File, Constructor)}.
*/
@Deprecated
public RunMap() {
super(null); // will be set later
}
@@ -152,6 +153,7 @@ public final class RunMap<R extends Run<?,R>> extends AbstractLazyLoadRunMap<R>
* @deprecated as of 1.485
* Use {@link ReverseComparator}
*/
@Deprecated
public static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() {
public int compare(Comparable o1, Comparable o2) {
return -o1.compareTo(o2);
@@ -247,6 +249,7 @@ public final class RunMap<R extends Run<?,R>> extends AbstractLazyLoadRunMap<R>
* @deprecated as of 1.485
* Use {@link #RunMap(File, Constructor)}
*/
@Deprecated
public void load(Job job, Constructor<R> cons) {
this.cons = cons;
initBaseDir(job.getBuildDir());
@@ -74,6 +74,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition {
/**
* @deprecated as of 1.517
*/
@Deprecated
public RunParameterDefinition(String name, String projectName, String description) {
// delegate to updated constructor with additional RunParameterFilter parameter defaulted to ALL.
this(name, projectName, description, RunParameterFilter.ALL);
@@ -30,6 +30,7 @@ import jenkins.triggers.SCMTriggerItem;
/**
* @deprecated Implement {@link SCMTriggerItem} instead.
*/
@Deprecated
public interface SCMedItem extends BuildableItem {
/**
* Gets the {@link SCM} for this item.
@@ -55,6 +56,7 @@ public interface SCMedItem extends BuildableItem {
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
@Deprecated
boolean pollSCMChanges( TaskListener listener );
/**
+33 -22
View File
@@ -1,19 +1,19 @@
/*
* The MIT License
*
*
* Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Martin Eigenbrodt, Stephen Connolly, Tom Huybrechts
*
*
* 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
@@ -63,6 +63,7 @@ import jenkins.security.MasterToSlaveCallable;
import jenkins.slaves.WorkspaceLocator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
@@ -92,8 +93,12 @@ public abstract class Slave extends Node implements Serializable {
private final String description;
/**
* Absolute path to the root of the workspace
* from the view point of this node, such as "/hudson"
* Path to the root of the workspace from the view point of this node, such as "/hudson", this need not
* be absolute provided that the launcher establishes a consistent working directory, such as "./.jenkins-slave"
* when used with an SSH launcher.
*
* NOTE: if the administrator is using a relative path they are responsible for ensuring that the launcher used
* provides a consistent working directory
*/
protected final String remoteFS;
@@ -121,14 +126,14 @@ public abstract class Slave extends Node implements Serializable {
* Whitespace-separated labels.
*/
private String label="";
private /*almost final*/ DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance());
/**
* Lazily computed set of labels from {@link #label}.
*/
private transient volatile Set<Label> labels;
/**
* Id of user which creates this slave {@link User}.
*/
@@ -147,7 +152,7 @@ public abstract class Slave extends Node implements Serializable {
Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy) throws FormException, IOException {
this(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, new ArrayList());
}
public Slave(@Nonnull String name, String nodeDescription, String remoteFS, int numExecutors,
Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws FormException, IOException {
this.name = name;
@@ -159,7 +164,7 @@ public abstract class Slave extends Node implements Serializable {
this.launcher = launcher;
this.retentionStrategy = retentionStrategy;
getAssignedLabels(); // compute labels now
this.nodeProperties.replaceBy(nodeProperties);
Slave node = (Slave) Jenkins.getInstance().getNode(name);
@@ -168,7 +173,7 @@ public abstract class Slave extends Node implements Serializable {
}
else{
User user = User.current();
userId = user!=null ? user.getId() : "anonymous";
userId = user!=null ? user.getId() : "anonymous";
}
if (name.equals(""))
throw new FormException(Messages.Slave_InvalidConfig_NoName(), null);
@@ -179,10 +184,10 @@ public abstract class Slave extends Node implements Serializable {
if (this.numExecutors<=0)
throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
}
/**
* Return id of user which created this slave
*
*
* @return id of user
*/
public String getUserId() {
@@ -192,7 +197,7 @@ public abstract class Slave extends Node implements Serializable {
public void setUserId(String userId){
this.userId = userId;
}
public ComputerLauncher getLauncher() {
return launcher == null ? new JNLPLauncher() : launcher;
}
@@ -214,7 +219,7 @@ public abstract class Slave extends Node implements Serializable {
}
public void setNodeName(String name) {
this.name = name;
this.name = name;
}
public String getNodeDescription() {
@@ -237,7 +242,7 @@ public abstract class Slave extends Node implements Serializable {
assert nodeProperties != null;
return nodeProperties;
}
public RetentionStrategy getRetentionStrategy() {
return retentionStrategy == null ? RetentionStrategy.Always.INSTANCE : retentionStrategy;
}
@@ -273,14 +278,21 @@ public abstract class Slave extends Node implements Serializable {
return workspace;
}
}
FilePath r = getWorkspaceRoot();
if(r==null) return null; // offline
return r.child(item.getFullName());
}
@CheckForNull
public FilePath getRootPath() {
return createPath(remoteFS);
final SlaveComputer computer = getComputer();
if (computer == null) {
// if computer is null then channel is null and thus we were going to return null anyway
return null;
} else {
return createPath(StringUtils.defaultString(computer.getAbsoluteRemoteFs(), remoteFS));
}
}
/**
@@ -422,10 +434,8 @@ public abstract class Slave extends Node implements Serializable {
if(value.startsWith("\\\\") || value.startsWith("/net/"))
return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning());
if (!value.contains("\\") && !value.startsWith("/")) {
// Unix-looking path that doesn't start with '/'
// TODO: detect Windows-looking relative path
return FormValidation.error(Messages.Slave_the_remote_root_must_be_an_absolute_path());
if (Util.isRelativePath(value)) {
return FormValidation.warning(Messages.Slave_Remote_Relative_Path_Warning());
}
return FormValidation.ok();
@@ -441,6 +451,7 @@ public abstract class Slave extends Node implements Serializable {
* "ssh myslave java -jar /path/to/hudson-remoting.jar"
* @deprecated in 1.216
*/
@Deprecated
private transient String agentCommand;
/**
@@ -57,6 +57,7 @@ public class StreamBuildListener extends StreamTaskListener implements BuildList
* The caller should use {@link #StreamBuildListener(OutputStream, Charset)} to pass in
* the charset and output stream separately, so that this class can handle encoding correctly.
*/
@Deprecated
public StreamBuildListener(PrintStream w) {
super(w);
}
@@ -80,6 +80,7 @@ public abstract class TaskAction extends AbstractModelObject implements Action {
* @deprecated as of 1.350
* Use {@link #obtainLog()}, which returns the same object in a more type-safe signature.
*/
@Deprecated
public LargeText getLog() {
return obtainLog();
}
@@ -51,6 +51,7 @@ public abstract class TaskThread extends Thread {
* @deprecated as of Hudson 1.350
* Use {@link #log}. It's the same object, in a better type.
*/
@Deprecated
private final LargeText text;
/**
@@ -163,6 +164,7 @@ public abstract class TaskThread extends Thread {
* @deprecated as of Hudson 1.350
* Use {@link #forMemory(TaskAction)} and pass in the calling {@link TaskAction}
*/
@Deprecated
public static ListenerAndText forMemory() {
return forMemory(null);
}
@@ -171,6 +173,7 @@ public abstract class TaskThread extends Thread {
* @deprecated as of Hudson 1.350
* Use {@link #forFile(File, TaskAction)} and pass in the calling {@link TaskAction}
*/
@Deprecated
public static ListenerAndText forFile(File f) throws IOException {
return forFile(f,null);
}
@@ -25,6 +25,7 @@ package hudson.model;
import hudson.ExtensionList;
import jenkins.model.Jenkins;
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.StaplerRequest;
/**
@@ -61,6 +62,29 @@ public abstract class TopLevelItemDescriptor extends Descriptor<TopLevelItem> {
return true;
}
/**
* {@link TopLevelItemDescriptor}s often may want to limit the scope within which they can be created.
* This method allows the subtype of {@link TopLevelItemDescriptor}s to filter them out.
*
* @since TODO
*/
public boolean isApplicableIn(ItemGroup parent) {
return true;
}
/**
* Checks if this top level item is applicable within the specified item group.
* <p>
* This is just a convenience function.
* @since TODO
*/
public final void checkApplicableIn(ItemGroup parent) {
if (!isApplicableIn(parent)) {
throw new AccessDeniedException(
Messages.TopLevelItemDescriptor_NotApplicableIn(getDisplayName(), parent.getFullDisplayName()));
}
}
/**
* Tests if the given instance belongs to this descriptor, in the sense
* that this descriptor can produce items like the given one.
@@ -101,6 +125,7 @@ public abstract class TopLevelItemDescriptor extends Descriptor<TopLevelItem> {
* @deprecated as of 1.390
* Use {@link #newInstance(ItemGroup, String)}
*/
@Deprecated
public TopLevelItem newInstance(String name) {
return newInstance(Jenkins.getInstance(), name);
}
@@ -37,6 +37,7 @@ public abstract class TransientBuildActionFactory implements ExtensionPoint {
* @deprecated as of 1.461
* Override and call {@link #createFor(Run)} instead.
*/
@Deprecated
public Collection<? extends Action> createFor(AbstractBuild target) {
return Collections.emptyList();
}
@@ -47,4 +48,4 @@ public abstract class TransientBuildActionFactory implements ExtensionPoint {
public static ExtensionList<TransientBuildActionFactory> all() {
return ExtensionList.lookup(TransientBuildActionFactory.class);
}
}
}
@@ -320,6 +320,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* TODO: revisit tool update mechanism, as that should be de-centralized, too. In the mean time,
* please try not to use this method, and instead ping us to get this part completed.
*/
@Deprecated
public String getDefaultBaseUrl() {
return config.getUpdateCenterUrl();
}
@@ -842,6 +843,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* is now a part of the <tt>update-center.json</tt> file. See
* <tt>http://jenkins-ci.org/update-center.json</tt> as an example.
*/
@Deprecated
public String getConnectionCheckUrl() {
return "http://www.google.com";
}
@@ -856,6 +858,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* @return
* Absolute URL that ends with '/'.
*/
@Deprecated
public String getUpdateCenterUrl() {
return UPDATE_CENTER_URL;
}
@@ -867,6 +870,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* <tt>update-center.json</tt> is now signed, so we don't have to further make sure that
* we aren't downloading from anywhere unsecure.
*/
@Deprecated
public String getPluginRepositoryBaseUrl() {
return "http://jenkins-ci.org/";
}
@@ -920,6 +924,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* @deprecated as of 1.326
* Use {@link #submit()} instead.
*/
@Deprecated
public void schedule() {
submit();
}
@@ -1270,6 +1275,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
/**
* @deprecated as of 1.442
*/
@Deprecated
public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth) {
this(plugin,site,auth,false);
}
@@ -1565,6 +1571,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* @deprecated as of 1.333
* Use {@link UpdateSite#neverUpdate}
*/
@Deprecated
public static boolean neverUpdate = Boolean.getBoolean(UpdateCenter.class.getName()+".never");
public static final XStream2 XSTREAM = new XStream2();
@@ -406,6 +406,7 @@ public class UpdateSite {
* @deprecated
* Exposed only for UI.
*/
@Deprecated
public String getDownloadUrl() {
/*
HACKISH:
@@ -768,6 +769,7 @@ public class UpdateSite {
* @deprecated as of 1.326
* Use {@link #deploy()}.
*/
@Deprecated
public void install() {
deploy();
}
+34 -3
View File
@@ -243,6 +243,15 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
return description;
}
/**
* Sets the description of the user.
* @since 1.609
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the user properties configured for this user.
*/
@@ -304,7 +313,8 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
// backend can't load information about other users. so use the stored information if available
} catch (UsernameNotFoundException e) {
// if the user no longer exists in the backend, we need to refuse impersonating this user
throw e;
if (!ALLOW_NON_EXISTENT_USER_TO_LOGIN)
throw e;
} catch (DataAccessException e) {
// seems like it's in the same boat as UserMayOrMayNotExistException
}
@@ -347,6 +357,7 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
* {@code create} is false.
* @deprecated use {@link User#get(String, boolean, java.util.Map)}
*/
@Deprecated
public static @Nullable User get(String idOrFullName, boolean create) {
return get(idOrFullName, create, Collections.emptyMap());
}
@@ -476,8 +487,18 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
* @since 1.172
*/
public static @CheckForNull User current() {
Authentication a = Jenkins.getAuthentication();
if(a instanceof AnonymousAuthenticationToken)
return get(Jenkins.getAuthentication());
}
/**
* Gets the {@link User} object representing the supplied {@link Authentication} or
* {@code null} if the supplied {@link Authentication} is either anonymous or {@code null}
* @param a the supplied {@link Authentication} .
* @return a {@link User} object for the supplied {@link Authentication} or {@code null}
* @since 1.609
*/
public static @CheckForNull User get(@CheckForNull Authentication a) {
if(a == null || a instanceof AnonymousAuthenticationToken)
return null;
// Since we already know this is a name, we can just call getOrCreate with the name directly.
@@ -976,5 +997,15 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
}
}
/**
* Jenkins now refuses to let the user login if he/she doesn't exist in {@link SecurityRealm},
* which was necessary to make sure users removed from the backend will get removed from the frontend.
* <p>
* Unfortunately this infringed some legitimate use cases of creating Jenkins-local users for
* automation purposes. This escape hatch switch can be enabled to resurrect that behaviour.
*
* JENKINS-22346.
*/
public static boolean ALLOW_NON_EXISTENT_USER_TO_LOGIN = Boolean.getBoolean(User.class.getName()+".allowNonExistentUserToLogin");
}
@@ -33,10 +33,12 @@ import java.util.List;
* @author Kohsuke Kawaguchi
* @deprecated as of 1.286
*/
@Deprecated
public class UserProperties {
/**
* @deprecated as of 1.286
* Use {@link UserProperty#all()} for read access and {@link Extension} for auto-registration.
*/
@Deprecated
public static final List<UserPropertyDescriptor> LIST = (List)new DescriptorList<UserProperty>(UserProperty.class);
}
@@ -655,6 +655,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
* Does this {@link View} has any associated user information recorded?
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public boolean hasPeople() {
return People.isApplicable(getItems());
}
@@ -738,6 +739,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
/**
* @deprecated Potentially very expensive call; do not use from Jelly views.
*/
@Deprecated
public static boolean isApplicable(Collection<? extends Item> items) {
for (Item item : items) {
for (Job job : item.getAllJobs()) {
@@ -1116,6 +1118,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
* @deprecated as of 1.286
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
@Deprecated
public static final DescriptorList<View> LIST = new DescriptorList<View>(View.class);
/**
@@ -79,6 +79,7 @@ public abstract class ViewJob<JobT extends ViewJob<JobT,RunT>, RunT extends Run<
/**
* @deprecated as of 1.390
*/
@Deprecated
protected ViewJob(Jenkins parent, String name) {
super(parent,name);
}
@@ -49,7 +49,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
}
@Override public long getRecurrencePeriod() {
return DAY;
return recurrencePeriodHours * HOUR;
}
public static void invoke() {
@@ -99,7 +99,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
}
}
private boolean shouldBeDeleted(@Nonnull TopLevelItem item, FilePath dir, Node n) throws IOException, InterruptedException {
private boolean shouldBeDeleted(@Nonnull TopLevelItem item, FilePath dir, @Nonnull Node n) throws IOException, InterruptedException {
// TODO: the use of remoting is not optimal.
// One remoting can execute "exists", "lastModified", and "delete" all at once.
// (Could even invert master loop so that one FileCallable takes care of all known items.)
@@ -110,7 +110,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
// if younger than a month, keep it
long now = new Date().getTime();
if(dir.lastModified() + 30 * DAY > now) {
if(dir.lastModified() + retainForDays * DAY > now) {
LOGGER.log(Level.FINE, "Directory {0} is only {1} old, so not deleting", new Object[] {dir, Util.getTimeSpanString(now-dir.lastModified())});
return false;
}
@@ -128,7 +128,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
return false;
}
if(!p.getScm().processWorkspaceBeforeDeletion(p,dir,n)) {
if(!p.getScm().processWorkspaceBeforeDeletion((Job<?, ?>) p,dir,n)) {
LOGGER.log(Level.FINE, "Directory deletion of {0} is vetoed by SCM", dir);
return false;
}
@@ -143,5 +143,15 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
/**
* Can be used to disable workspace clean up.
*/
public static final boolean disabled = Boolean.getBoolean(WorkspaceCleanupThread.class.getName()+".disabled");
public static boolean disabled = Boolean.getBoolean(WorkspaceCleanupThread.class.getName()+".disabled");
/**
* How often the clean up should run. This is final as Jenkins will not reflect changes anyway.
*/
public static final int recurrencePeriodHours = Integer.getInteger(WorkspaceCleanupThread.class.getName()+".recurrencePeriodHours", 24);
/**
* Number of days workspaces should be retained.
*/
public static int retainForDays = Integer.getInteger(WorkspaceCleanupThread.class.getName()+".retainForDays", 30);
}
@@ -116,7 +116,7 @@ public class LabelAtom extends Label implements Saveable {
}
/**
* @since TODO
* @since 1.580
*/
public String getDescription() {
return description;
@@ -148,6 +148,7 @@ public class ItemListener implements ExtensionPoint {
* @deprecated as of 1.286
* put {@link Extension} on your class to have it auto-registered.
*/
@Deprecated
public void register() {
all().add(this);
}
@@ -171,6 +171,7 @@ public abstract class RunListener<R extends Run> implements ExtensionPoint {
* @deprecated as of 1.281
* Put {@link Extension} on your class to get it auto-registered.
*/
@Deprecated
public void register() {
all().add(this);
}
@@ -187,6 +188,7 @@ public abstract class RunListener<R extends Run> implements ExtensionPoint {
* @deprecated as of 1.281
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
@Deprecated
public static final CopyOnWriteList<RunListener> LISTENERS = ExtensionListView.createCopyOnWriteList(RunListener.class);
/**
@@ -60,6 +60,7 @@ public abstract class SaveableListener implements ExtensionPoint {
* @deprecated as of 1.281
* Put {@link Extension} on your class to get it auto-registered.
*/
@Deprecated
public void register() {
all().add(this);
}
@@ -51,6 +51,6 @@ public abstract class AbstractSubTask implements SubTask {
}
public ResourceList getResourceList() {
return new ResourceList();
return ResourceList.EMPTY;
}
}
@@ -73,6 +73,7 @@ public abstract class LoadPredictor implements ExtensionPoint {
* @deprecated as of 1.380
* Use {@link #predict(MappingWorksheet, Computer, long, long)}
*/
@Deprecated
public Iterable<FutureLoad> predict(Computer computer, long start, long end) {
return Collections.emptyList();
}
@@ -68,6 +68,7 @@ public abstract class QueueTaskDispatcher implements ExtensionPoint {
* @deprecated since 1.413
* Use {@link #canTake(Node, Queue.BuildableItem)}
*/
@Deprecated
public @CheckForNull CauseOfBlockage canTake(Node node, Task task) {
return null;
}
@@ -76,6 +76,7 @@ public final class WorkUnitContext {
protected void onCriteriaMet() {
// on behalf of the member Executors,
// the one that executes the main thing will send notifications
// Unclear if this will work with AsynchronousExecution; it *seems* this is only called from synchronize which is only called from synchronizeStart which is only called from an executor thread.
Executor e = Executor.currentExecutor();
if (e.getCurrentWorkUnit().isMainWork()) {
e.getOwner().taskAccepted(e,task);
@@ -121,6 +122,11 @@ public final class WorkUnitContext {
}
}
@Deprecated
public void synchronizeEnd(Queue.Executable executable, Throwable problems, long duration) throws InterruptedException {
synchronizeEnd(Executor.currentExecutor(), executable, problems, duration);
}
/**
* All the {@link Executor}s that jointly execute a {@link Task} call this method to synchronize on the end of the task.
*
@@ -128,11 +134,10 @@ public final class WorkUnitContext {
* If any of the member thread is interrupted while waiting for other threads to join, all
* the member threads will report {@link InterruptedException}.
*/
public void synchronizeEnd(Queue.Executable executable, Throwable problems, long duration) throws InterruptedException {
public void synchronizeEnd(Executor e, Queue.Executable executable, Throwable problems, long duration) throws InterruptedException {
endLatch.synchronize();
// the main thread will send a notification
Executor e = Executor.currentExecutor();
WorkUnit wu = e.getCurrentWorkUnit();
if (wu.isMainWork()) {
if (problems == null) {
@@ -58,6 +58,7 @@ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMo
* @deprecated as of 1.522
* Extend from {@link AbstractAsyncNodeMonitorDescriptor}
*/
@Deprecated
protected AbstractNodeMonitorDescriptor() {
this(HOUR);
}
@@ -66,6 +67,7 @@ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMo
* @deprecated as of 1.522
* Extend from {@link AbstractAsyncNodeMonitorDescriptor}
*/
@Deprecated
protected AbstractNodeMonitorDescriptor(long interval) {
schedule(interval);
}
@@ -74,6 +76,7 @@ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMo
* @deprecated as of 1.522
* Extend from {@link AbstractAsyncNodeMonitorDescriptor}
*/
@Deprecated
protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz) {
this(clazz,HOUR);
}
@@ -82,6 +85,7 @@ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMo
* @deprecated as of 1.522
* Extend from {@link AbstractAsyncNodeMonitorDescriptor}
*/
@Deprecated
protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz, long interval) {
super(clazz);
@@ -243,6 +247,7 @@ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMo
* @deprecated as of 1.320
* Use {@link #markOffline(Computer, OfflineCause)} to specify the cause.
*/
@Deprecated
protected boolean markOffline(Computer c) {
return markOffline(c,null);
}
@@ -139,6 +139,7 @@ public abstract class NodeMonitor implements ExtensionPoint, Describable<NodeMon
* @deprecated as of 1.286.
* Use {@link #all()} for read access and {@link Extension} for registration.
*/
@Deprecated
public static final DescriptorList<NodeMonitor> LIST = new DescriptorList<NodeMonitor>(NodeMonitor.class);
/**
@@ -102,6 +102,7 @@ public class ZFSProvisioner extends FileSystemProvisioner implements Serializabl
/**
* @deprecated as of 1.350
*/
@Deprecated
public WorkspaceSnapshot snapshot(AbstractBuild<?, ?> build, FilePath ws, TaskListener listener) throws IOException, InterruptedException {
throw new UnsupportedOperationException();
}
@@ -70,6 +70,7 @@ public final class CronTab {
* @deprecated as of 1.448
* Use {@link #CronTab(String, int, Hash)}
*/
@Deprecated
public CronTab(String format, int line) throws ANTLRException {
set(format, line, null);
}
@@ -98,6 +98,7 @@ public abstract class ChangeLogAnnotator implements ExtensionPoint {
* @deprecated as of 1.286
* Prefer automatic registration via {@link Extension}
*/
@Deprecated
public final void register() {
all().add(this);
}
@@ -115,6 +116,7 @@ public abstract class ChangeLogAnnotator implements ExtensionPoint {
* @deprecated as of 1.286
* Use {@link #all()} for read access, and {@link Extension} for registration.
*/
@Deprecated
public static final CopyOnWriteList<ChangeLogAnnotator> annotators = ExtensionListView.createCopyOnWriteList(ChangeLogAnnotator.class);
/**
Loaded 100 of 345 files, more files were not shown because too many files have changed in this diff. Show more