From 48cc7e03d4b88c9cd74990ef703f48b5eb6dbc36 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Sun, 4 May 2014 12:39:02 +0400 Subject: [PATCH 01/26] Annotate hudson.Util methods. The change adds annotations for all methods inside the class. The initial idea - enforce checks of symlink methods to prevent NPEs on Windows platforms. Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/Util.java | 186 ++++++++++++++++++---------- 1 file changed, 120 insertions(+), 66 deletions(-) diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index 2934a79a4f..7462da9585 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -73,6 +73,8 @@ import hudson.util.jna.Kernel32Utils; import static hudson.util.jna.GNUCLibrary.LIBC; import java.security.DigestInputStream; +import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; import org.apache.commons.codec.digest.DigestUtils; /** @@ -94,7 +96,8 @@ public class Util { * Creates a filtered sublist. * @since 1.176 */ - public static List filter( Iterable base, Class type ) { + @Nonnull + public static List filter( @Nonnull Iterable base, @Nonnull Class type ) { List r = new ArrayList(); for (Object i : base) { if(type.isInstance(i)) @@ -106,7 +109,8 @@ public class Util { /** * Creates a filtered sublist. */ - public static List filter( List base, Class type ) { + @Nonnull + public static List filter( @Nonnull List base, @Nonnull Class type ) { return filter((Iterable)base,type); } @@ -122,7 +126,8 @@ public class Util { * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.) * */ - public static String replaceMacro(String s, Map properties) { + @CheckForNull + public static String replaceMacro( @CheckForNull String s, @Nonnull Map properties) { return replaceMacro(s,new VariableResolver.ByMap(properties)); } @@ -132,7 +137,8 @@ public class Util { *

* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.) */ - public static String replaceMacro(String s, VariableResolver resolver) { + @CheckForNull + public static String replaceMacro(@CheckForNull String s, @Nonnull VariableResolver resolver) { if (s == null) { return null; } @@ -165,11 +171,13 @@ public class Util { /** * Loads the contents of a file into a string. */ - public static String loadFile(File logfile) throws IOException { + @Nonnull + public static String loadFile(@Nonnull File logfile) throws IOException { return loadFile(logfile, Charset.defaultCharset()); } - public static String loadFile(File logfile,Charset charset) throws IOException { + @Nonnull + public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException { if(!logfile.exists()) return ""; @@ -195,7 +203,7 @@ public class Util { * @throws IOException * if the operation fails. */ - public static void deleteContentsRecursive(File file) throws IOException { + public static void deleteContentsRecursive(@Nonnull File file) throws IOException { File[] files = file.listFiles(); if(files==null) return; // the directory didn't exist in the first place @@ -208,7 +216,7 @@ public class Util { * @param f a file to delete * @throws IOException if it exists but could not be successfully deleted */ - public static void deleteFile(File f) throws IOException { + public static void deleteFile(@Nonnull File f) throws IOException { if (!f.delete()) { if(!f.exists()) // we are trying to delete a file that no longer exists, so this is not an error @@ -259,7 +267,7 @@ public class Util { /** * Makes the given file writable by any means possible. */ - private static void makeWritable(File f) { + private static void makeWritable(@Nonnull File f) { if (f.setWritable(true)) { return; } @@ -287,7 +295,7 @@ public class Util { } - public static void deleteRecursive(File dir) throws IOException { + public static void deleteRecursive(@Nonnull File dir) throws IOException { if(!isSymlink(dir)) deleteContentsRecursive(dir); try { @@ -321,7 +329,7 @@ public class Util { * Checks if the given file represents a symlink. */ //Taken from http://svn.apache.org/viewvc/maven/shared/trunk/file-management/src/main/java/org/apache/maven/shared/model/fileset/util/FileSetManager.java?view=markup - public static boolean isSymlink(File file) throws IOException { + public static boolean isSymlink(@Nonnull File file) throws IOException { Boolean r = isSymlinkJava7(file); if (r != null) { return r; @@ -350,7 +358,7 @@ public class Util { } @SuppressWarnings("NP_BOOLEAN_RETURN_NULL") - private static Boolean isSymlinkJava7(File file) throws IOException { + private static Boolean isSymlinkJava7(@Nonnull File file) throws IOException { try { Object path = File.class.getMethod("toPath").invoke(file); return (Boolean) Class.forName("java.nio.file.Files").getMethod("isSymbolicLink", Class.forName("java.nio.file.Path")).invoke(null, path); @@ -379,13 +387,14 @@ public class Util { * On Windows, error messages for IOException aren't very helpful. * This method generates additional user-friendly error message to the listener */ - public static void displayIOException( IOException e, TaskListener listener ) { + public static void displayIOException(@Nonnull IOException e, @Nonnull TaskListener listener ) { String msg = getWin32ErrorMessage(e); if(msg!=null) listener.getLogger().println(msg); } - public static String getWin32ErrorMessage(IOException e) { + @CheckForNull + public static String getWin32ErrorMessage(@Nonnull IOException e) { return getWin32ErrorMessage((Throwable)e); } @@ -395,6 +404,7 @@ public class Util { * @return * null if there seems to be no error code or if the platform is not Win32. */ + @CheckForNull public static String getWin32ErrorMessage(Throwable e) { String msg = e.getMessage(); if(msg!=null) { @@ -420,6 +430,7 @@ public class Util { * @return * null if no such message is available. */ + @CheckForNull public static String getWin32ErrorMessage(int n) { try { ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors"); @@ -433,6 +444,7 @@ public class Util { /** * Guesses the current host name. */ + @Nonnull public static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); @@ -441,21 +453,21 @@ public class Util { } } - public static void copyStream(InputStream in,OutputStream out) throws IOException { + public static void copyStream(@Nonnull InputStream in,@Nonnull OutputStream out) throws IOException { byte[] buf = new byte[8192]; int len; while((len=in.read(buf))>=0) out.write(buf,0,len); } - public static void copyStream(Reader in, Writer out) throws IOException { + public static void copyStream(@Nonnull Reader in, @Nonnull Writer out) throws IOException { char[] buf = new char[8192]; int len; while((len=in.read(buf))>0) out.write(buf,0,len); } - public static void copyStreamAndClose(InputStream in,OutputStream out) throws IOException { + public static void copyStreamAndClose(@Nonnull InputStream in, @Nonnull OutputStream out) throws IOException { try { copyStream(in,out); } finally { @@ -464,7 +476,7 @@ public class Util { } } - public static void copyStreamAndClose(Reader in,Writer out) throws IOException { + public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException { try { copyStream(in,out); } finally { @@ -483,18 +495,21 @@ public class Util { * @since 1.145 * @see QuotedStringTokenizer */ - public static String[] tokenize(String s,String delimiter) { + @Nonnull + public static String[] tokenize(@Nonnull String s, @CheckForNull String delimiter) { return QuotedStringTokenizer.tokenize(s,delimiter); } - public static String[] tokenize(String s) { + @Nonnull + public static String[] tokenize(@Nonnull String s) { return tokenize(s," \t\n\r\f"); } /** * Converts the map format of the environment variables to the K=V format in the array. */ - public static String[] mapToEnv(Map m) { + @Nonnull + public static String[] mapToEnv(@Nonnull Map m) { String[] r = new String[m.size()]; int idx=0; @@ -504,7 +519,7 @@ public class Util { return r; } - public static int min(int x, int... values) { + public static int min(int x, @Nonnull int... values) { for (int i : values) { if(i List createSubList( Collection source, Class type ) { + @Nonnull + public static List createSubList(@Nonnull Collection source, @Nonnull Class type ) { List r = new ArrayList(); for (Object item : source) { if(type.isInstance(item)) @@ -749,7 +779,8 @@ 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). */ - public static String encode(String s) { + @Nonnull + public static String encode(@Nonnull String s) { try { boolean escaped = false; @@ -806,7 +837,8 @@ public class Util { * single path component used in constructing a URL. * Method name inspired by PHP's rawurlencode. */ - public static String rawEncode(String s) { + @Nonnull + public static String rawEncode(@Nonnull String s) { boolean escaped = false; StringBuilder out = null; CharsetEncoder enc = null; @@ -855,7 +887,8 @@ public class Util { /** * Escapes HTML unsafe characters like <, & to the respective character entities. */ - public static String escape(String text) { + @Nonnull + public static String escape(@Nonnull String text) { if (text==null) return null; StringBuilder buf = new StringBuilder(text.length()+64); for( int i=0; i List fixNull(List l) { + @Nonnull + public static List fixNull(@CheckForNull List l) { return l!=null ? l : Collections.emptyList(); } - public static Set fixNull(Set l) { + @Nonnull + public static Set fixNull(@CheckForNull Set l) { return l!=null ? l : Collections.emptySet(); } - public static Collection fixNull(Collection l) { + @Nonnull + public static Collection fixNull(@CheckForNull Collection l) { return l!=null ? l : Collections.emptySet(); } - public static Iterable fixNull(Iterable l) { + @Nonnull + public static Iterable fixNull(@CheckForNull Iterable l) { return l!=null ? l : Collections.emptySet(); } /** * Cuts all the leading path portion and get just the file name. */ - public static String getFileName(String filePath) { + @Nonnull + public static String getFileName(@Nonnull String filePath) { int idx = filePath.lastIndexOf('\\'); if(idx>=0) return getFileName(filePath.substring(idx+1)); @@ -980,7 +1022,8 @@ public class Util { /** * Concatenate multiple strings by inserting a separator. */ - public static String join(Collection strings, String separator) { + @Nonnull + public static String join(@Nonnull Collection strings, @Nonnull String separator) { StringBuilder buf = new StringBuilder(); boolean first=true; for (Object s : strings) { @@ -994,7 +1037,8 @@ public class Util { /** * Combines all the given collections into a single list. */ - public static List join(Collection... items) { + @Nonnull + public static List join(@Nonnull Collection... items) { int size = 0; for (Collection item : items) size += item.size(); @@ -1021,7 +1065,8 @@ public class Util { * Can be null. * @since 1.172 */ - public static FileSet createFileSet(File baseDir, String includes, String excludes) { + @Nonnull + public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes, @CheckForNull String excludes) { FileSet fs = new FileSet(); fs.setDir(baseDir); fs.setProject(new Project()); @@ -1043,7 +1088,8 @@ public class Util { return fs; } - public static FileSet createFileSet(File baseDir, String includes) { + @Nonnull + public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes) { return createFileSet(baseDir,includes,null); } @@ -1059,7 +1105,8 @@ public class Util { * @param symlinkPath * Where to create a symlink in (relative to {@code baseDir}) */ - public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException { + public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath, + @Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException { try { if (createSymlinkJava7(baseDir, targetPath, symlinkPath)) { return; @@ -1131,7 +1178,7 @@ public class Util { } } - private static boolean createSymlinkJava7(File baseDir, String targetPath, String symlinkPath) throws IOException { + private static boolean createSymlinkJava7(@Nonnull File baseDir, @Nonnull String targetPath, @Nonnull String symlinkPath) throws IOException { try { Object path = File.class.getMethod("toPath").invoke(new File(baseDir, symlinkPath)); Object target = Class.forName("java.nio.file.Paths").getMethod("get", String.class, String[].class).invoke(null, targetPath, new String[0]); @@ -1201,7 +1248,8 @@ public class Util { * @return null * if the specified file is not a symlink. */ - public static File resolveSymlinkToFile(File link) throws InterruptedException, IOException { + @CheckForNull + public static File resolveSymlinkToFile(@Nonnull File link) throws InterruptedException, IOException { String target = resolveSymlink(link); if (target==null) return null; @@ -1221,7 +1269,8 @@ public class Util { * If the symlink is relative, the returned string is that relative representation. * The relative path is meant to be resolved from the location of the symlink. */ - public static String resolveSymlink(File link) throws InterruptedException, IOException { + @CheckForNull + public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException { try { // Java 7 Object path = File.class.getMethod("toPath").invoke(link); return Class.forName("java.nio.file.Files").getMethod("readSymbolicLink", Class.forName("java.nio.file.Path")).invoke(null, path).toString(); @@ -1306,7 +1355,8 @@ public class Util { * Wraps with the error icon and the CSS class to render error message. * @since 1.173 */ - public static String wrapToErrorSpan(String s) { + @Nonnull + public static String wrapToErrorSpan(@Nonnull String s) { s = ""+s+""; return s; } @@ -1319,7 +1369,8 @@ public class Util { * @param defaultNumber number to return if the string can not be parsed * @return returns the parsed string; otherwise the default number */ - public static Number tryParseNumber(String numberStr, Number defaultNumber) { + @CheckForNull + public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) { if ((numberStr == null) || (numberStr.length() == 0)) { return defaultNumber; } @@ -1334,7 +1385,7 @@ public class Util { * Checks if the public method defined on the base type with the given arguments * are overridden in the given derived type. */ - public static boolean isOverridden(Class base, Class derived, String methodName, Class... types) { + public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) { try { return !base.getMethod(methodName, types).equals( derived.getMethod(methodName,types)); @@ -1349,7 +1400,8 @@ public class Util { * @param ext * For example, ".zip" */ - public static File changeExtension(File dst, String ext) { + @Nonnull + public static File changeExtension(@Nonnull File dst, @Nonnull String ext) { String p = dst.getPath(); int pos = p.lastIndexOf('.'); if (pos<0) return new File(p+ext); @@ -1359,7 +1411,8 @@ public class Util { /** * Null-safe String intern method. */ - public static String intern(String s) { + @CheckForNull + public static String intern(@CheckForNull String s) { return s==null ? s : s.intern(); } @@ -1370,7 +1423,7 @@ public class Util { * implementing this by ourselves allow it to be more lenient about * escaping of URI. */ - public static boolean isAbsoluteUri(String uri) { + public static boolean isAbsoluteUri(@Nonnull String uri) { int idx = uri.indexOf(':'); if (idx<0) return false; // no ':'. can't be absolute @@ -1382,7 +1435,7 @@ public class Util { * Works like {@link String#indexOf(int)} but 'not found' is returned as s.length(), not -1. * This enables more straight-forward comparison. */ - private static int _indexOf(String s, char ch) { + private static int _indexOf(@Nonnull String s, char ch) { int idx = s.indexOf(ch); if (idx<0) return s.length(); return idx; @@ -1392,7 +1445,8 @@ public class Util { * Loads a key/value pair string as {@link Properties} * @since 1.392 */ - public static Properties loadProperties(String properties) throws IOException { + @Nonnull + public static Properties loadProperties(@Nonnull String properties) throws IOException { Properties p = new Properties(); p.load(new StringReader(properties)); return p; From 6c2fffb24843324fc3f01da692bff6f4d8b6cd71 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Mon, 5 May 2014 22:26:12 +0400 Subject: [PATCH 02/26] Fixed annotations in hudson/Util.java according to the discussion with @jglick and @kutzi Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/Util.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index 7462da9585..b7725aa68f 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -75,6 +75,7 @@ import static hudson.util.jna.GNUCLibrary.LIBC; import java.security.DigestInputStream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import org.apache.commons.codec.digest.DigestUtils; /** @@ -126,7 +127,7 @@ public class Util { * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.) * */ - @CheckForNull + @Nullable public static String replaceMacro( @CheckForNull String s, @Nonnull Map properties) { return replaceMacro(s,new VariableResolver.ByMap(properties)); } @@ -137,7 +138,7 @@ public class Util { *

* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.) */ - @CheckForNull + @Nullable public static String replaceMacro(@CheckForNull String s, @Nonnull VariableResolver resolver) { if (s == null) { return null; @@ -548,7 +549,7 @@ public class Util { * case subject was null and subject + suffix otherwise. * @since 1.505 */ - @CheckForNull + @Nullable public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) { if (subject == null) return null; @@ -1410,8 +1411,9 @@ public class Util { /** * Null-safe String intern method. + * @return A canonical representation for the string object. Null for null input strings */ - @CheckForNull + @Nullable public static String intern(@CheckForNull String s) { return s==null ? s : s.intern(); } From b401cf1fbafe50b67d1ed4aebef5bf2909e662e3 Mon Sep 17 00:00:00 2001 From: Daniel Beck Date: Sat, 31 May 2014 21:42:31 +0200 Subject: [PATCH 03/26] [FIX JENKINS-16827] Don't try to guess the build number The confusion resulting from a wrongly guessed build number isn't worth the minimal use this information provides. --- core/src/main/java/hudson/tasks/BuildTrigger.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/core/src/main/java/hudson/tasks/BuildTrigger.java b/core/src/main/java/hudson/tasks/BuildTrigger.java index 7f4bfbeed4..40533373fd 100644 --- a/core/src/main/java/hudson/tasks/BuildTrigger.java +++ b/core/src/main/java/hudson/tasks/BuildTrigger.java @@ -247,11 +247,9 @@ public class BuildTrigger extends Recorder implements DependencyDeclarer { logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p))); continue; } - // this is not completely accurate, as a new build might be triggered - // between these calls boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build), buildActions.toArray(new Action[buildActions.size()])); if (Jenkins.getInstance().getItemByFullName(p.getFullName()) == p) { - String name = ModelHyperlinkNote.encodeTo(p) + " #" + p.getNextBuildNumber(); + String name = ModelHyperlinkNote.encodeTo(p); if (scheduled) { logger.println(Messages.BuildTrigger_Triggering(name)); } else { From 0a241aafdbdf3ad15d34efa3077658c5770b9195 Mon Sep 17 00:00:00 2001 From: Daniel Beck Date: Sun, 1 Jun 2014 00:51:00 +0200 Subject: [PATCH 04/26] [JENKINS-17374 JENKINS-18116] Don't set gzip header for error --- core/src/main/java/hudson/model/Api.java | 25 ++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/core/src/main/java/hudson/model/Api.java b/core/src/main/java/hudson/model/Api.java index 71b617e46f..ff84f4b66d 100644 --- a/core/src/main/java/hudson/model/Api.java +++ b/core/src/main/java/hudson/model/Api.java @@ -154,16 +154,21 @@ public class Api extends AbstractModelObject { throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.",e); } + + if (isSimpleOutput(result) && !permit(req)) { + // simple output prohibited + rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester"); + return; + } + + // switch to gzipped output OutputStream o = rsp.getCompressedOutputStream(req); try { - if (result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean) { - if (permit(req)) { - rsp.setContentType("text/plain;charset=UTF-8"); - String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString(); - o.write(text.getBytes("UTF-8")); - } else { - rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester"); - } + if (isSimpleOutput(result)) { + // simple output allowed + rsp.setContentType("text/plain;charset=UTF-8"); + String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString(); + o.write(text.getBytes("UTF-8")); return; } @@ -175,6 +180,10 @@ public class Api extends AbstractModelObject { } } + private boolean isSimpleOutput(Object result) { + return result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean; + } + /** * Generate schema. */ From a865a52562a7f29ff065e3c86e67013cf606f9d5 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Wed, 13 Nov 2013 16:07:24 +0400 Subject: [PATCH 05/26] [FIXED JENKINS-19454] - Added DecoratedLauncher implementation to the core. This launcher Allows subclasses to only implement methods they want to override. Originally, this launcher has been implemented in Custom Tools Plugin, but there are many duplicates in other plugins => it would be useful to have it in Jenkins core. Resolves https://issues.jenkins-ci.org/browse/JENKINS-19454 Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/Launcher.java | 82 +++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java index 39d1a56b13..fbd6dc530b 100644 --- a/core/src/main/java/hudson/Launcher.java +++ b/core/src/main/java/hudson/Launcher.java @@ -972,6 +972,88 @@ public abstract class Launcher { } } } + + /** + * A launcher which delegates to a provided inner launcher. + * Allows subclasses to only implement methods they want to override. + * Originally, this launcher has been implemented in + * + * Custom Tools Plugin. + * + * @author rcampbell + * @author Oleg Nenashev, Synopsys Inc. + * @since TODO: define version + */ + public static class DecoratedLauncher extends Launcher { + + private Launcher inner = null; + + public DecoratedLauncher(Launcher inner) { + super(inner); + this.inner = inner; + } + + @Override + public Proc launch(ProcStarter starter) throws IOException { + return inner.launch(starter); + } + + @Override + public Channel launchChannel(String[] cmd, OutputStream out, + FilePath workDir, Map envVars) throws IOException, + InterruptedException { + return inner.launchChannel(cmd, out, workDir, envVars); + } + + @Override + public void kill(Map modelEnvVars) throws IOException, + InterruptedException { + inner.kill(modelEnvVars); + } + + @Override + public boolean isUnix() { + return inner.isUnix(); + } + + @Override + public Proc launch(String[] cmd, boolean[] mask, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException { + return inner.launch(cmd, mask, env, in, out, workDir); + } + + @Override + public Computer getComputer() { + return inner.getComputer(); + } + + @Override + public TaskListener getListener() { + return inner.getListener(); + } + + @Override + public String toString() { + return super.toString() + "; decorates " + inner.toString(); + } + + @Override + public VirtualChannel getChannel() { + return inner.getChannel(); + } + + @Override + public Proc launch(String[] cmd, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException { + return inner.launch(cmd, env, in, out, workDir); + } + + /** + * Gets nested launcher. + * @return Inner launcher + */ + public Launcher getInner() { + return inner; + } + } public static class IOTriplet implements Serializable { InputStream stdout,stderr; From ef943a3ee69529a9f41353f134043ed3363f12e0 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Wed, 13 Nov 2013 16:14:45 +0400 Subject: [PATCH 06/26] [FIXED JENKINS-20559] - ProcStarter: Check for null before cloning of environment variables list Resolves https://issues.jenkins-ci.org/browse/JENKINS-20559 BTW, I also need to add some tests to "Test Harness" in order to improve coverage of nested operations. These test require a fix for https://issues.jenkins-ci.org/browse/JENKINS-19454 Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/Launcher.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java index fbd6dc530b..b08dfaf0f1 100644 --- a/core/src/main/java/hudson/Launcher.java +++ b/core/src/main/java/hudson/Launcher.java @@ -300,8 +300,13 @@ public abstract class Launcher { return this; } + /** + * Gets a list of environment variables to be set. + * Returns an empty array if envs field has not been initialized. + * @return If initialized, returns a copy of internal envs array. Otherwise - a new empty array. + */ public String[] envs() { - return envs.clone(); + return envs != null ? envs.clone() : new String[0]; } /** From c5d01b0645a12e64e2a256641b18989c2f68eeea Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Sun, 1 Jun 2014 18:21:43 +0400 Subject: [PATCH 07/26] [JENKINS-20559] - A direct test for the bug Signed-off-by: Oleg Nenashev --- .../src/test/java/hudson/ProcStarterTest.java | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 test/src/test/java/hudson/ProcStarterTest.java diff --git a/test/src/test/java/hudson/ProcStarterTest.java b/test/src/test/java/hudson/ProcStarterTest.java new file mode 100644 index 0000000000..49ab5b6b5c --- /dev/null +++ b/test/src/test/java/hudson/ProcStarterTest.java @@ -0,0 +1,129 @@ +/* + * The MIT License + * + * Copyright 2013 Oleg Nenashev , Synopsys Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson; + +import hudson.model.AbstractBuild; +import hudson.model.AbstractProject; +import hudson.model.BuildListener; +import hudson.model.FreeStyleProject; +import hudson.model.Run; +import hudson.tasks.BuildWrapper; +import hudson.tasks.BuildWrapperDescriptor; +import java.io.IOException; +import org.jvnet.hudson.test.Bug; +import hudson.Launcher.DecoratedLauncher; +import org.junit.Rule; +import org.junit.Test; +import org.jvnet.hudson.test.JenkinsRule; + +/** + * Contains tests for {@link ProcStarter} class. + * @author Oleg Nenashev , Synopsys Inc. + * @since TODO: define a version + */ +public class ProcStarterTest { + + @Rule + public JenkinsRule rule = new JenkinsRule(); + + @Test + @Bug(20559) + public void testNonInitializedEnvsNPE() throws Exception { + // Create nodes and other test stuff + rule.hudson.setNumExecutors(0); + rule.createSlave(); + + // Create a job with test build wrappers + FreeStyleProject project = rule.createFreeStyleProject(); + project.getBuildWrappersList().add(new DecoratedWrapper()); + project.getBuildWrappersList().add(new EchoWrapper()); + + // Run the build. If NPE occurs, the test will fail + rule.buildAndAssertSuccess(project); + } + + /** + * A stub descriptor for {@link BuildWrapper}s. + */ + public abstract static class TestWrapperDescriptor extends BuildWrapperDescriptor { + + @Override + public boolean isApplicable(AbstractProject ap) { + return true; + } + + @Override + public String getDisplayName() { + return "testStub"; + } + } + + /** + * A wrapper, which contains a nested launch. + */ + public static class EchoWrapper extends BuildWrapper { + + @Override + public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { + Launcher.ProcStarter starter = launcher.launch().cmds("echo", "Hello"); + starter.start(); + starter.join(); + return new Environment() { + }; + } + + @Extension + public static class DescriptorImpl extends TestWrapperDescriptor { + } + }; + + /** + * A wrapper, which decorates launchers. + */ + public static class DecoratedWrapper extends BuildWrapper { + + @Override + public Launcher decorateLauncher(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException { + final BuildListener l = listener; + return new DecoratedLauncher(launcher) { + @Override + public Proc launch(Launcher.ProcStarter starter) throws IOException { + String[] envs = starter.envs(); // Finally, call envs() + l.getLogger().println("[DecoratedWrapper]: Number of environment variables is "+envs.length); // Fail on null + return super.launch(starter); + } + }; + } + + @Override + public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { + return new Environment() { + }; + } + + @Extension + public static class DescriptorImpl extends TestWrapperDescriptor { + } + }; +} From 128408eb50ded688fbeb423db1e2a0da0c6f5aa0 Mon Sep 17 00:00:00 2001 From: Daniel Beck Date: Sun, 1 Jun 2014 16:49:48 +0200 Subject: [PATCH 08/26] Add logging to PeepholePermalink's RunListener --- .../main/java/jenkins/model/PeepholePermalink.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/jenkins/model/PeepholePermalink.java b/core/src/main/java/jenkins/model/PeepholePermalink.java index d4cb1a39ed..c09644de0f 100644 --- a/core/src/main/java/jenkins/model/PeepholePermalink.java +++ b/core/src/main/java/jenkins/model/PeepholePermalink.java @@ -190,10 +190,11 @@ public abstract class PeepholePermalink extends Permalink implements Predicate j = run.getParent(); for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) { - if (pp.apply(run)) { - if (pp.resolve(j)==run) { - pp.updateCache(j,pp.find(run.getPreviousBuild())); - } + if (pp.resolve(j)==run) { + Run r = pp.find(run.getPreviousBuild()); + if (LOGGER.isLoggable(Level.FINE)) + LOGGER.fine("Updating "+pp.getPermalinkFile(j).getName()+" permalink from deleted "+run.getNumber()+" to "+(r == null ? -1 : r.getNumber())); + pp.updateCache(j,r); } } } @@ -207,8 +208,11 @@ public abstract class PeepholePermalink extends Permalink implements Predicate cur = pp.resolve(j); - if (cur==null || cur.getNumber() Date: Sun, 1 Jun 2014 22:19:33 -0700 Subject: [PATCH 09/26] [maven-release-plugin] prepare release jenkins-1.566 --- cli/pom.xml | 2 +- core/pom.xml | 2 +- plugins/pom.xml | 8 ++++---- pom.xml | 2 +- test/pom.xml | 2 +- war/pom.xml | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cli/pom.xml b/cli/pom.xml index df58c99ed8..b6f46e3634 100644 --- a/cli/pom.xml +++ b/cli/pom.xml @@ -5,7 +5,7 @@ pom org.jenkins-ci.main - 1.566-SNAPSHOT + 1.566 cli diff --git a/core/pom.xml b/core/pom.xml index f352e65084..2ee75afbf8 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -29,7 +29,7 @@ THE SOFTWARE. org.jenkins-ci.main pom - 1.566-SNAPSHOT + 1.566 ../pom.xml diff --git a/plugins/pom.xml b/plugins/pom.xml index dc03050273..64b409a73d 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -11,7 +11,7 @@ org.jenkins-ci.plugins plugin Jenkins plugin POM - 1.566-SNAPSHOT + 1.566 pom

+

What's new in 1.566 (2014/06/01)

  • Configurable case sensitivity mode for user IDs. @@ -76,7 +79,6 @@ Upcoming changes Jenkins cannot restart Windows service (issue 22685)
-

What's new in 1.565 (2014/05/26)

  • From be040c90aab02930d0255bf5205d308d13e48f07 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Mon, 2 Jun 2014 08:39:21 -0700 Subject: [PATCH 12/26] updated changelog as a part of the release --- debian/debian/changelog | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/debian/debian/changelog b/debian/debian/changelog index 3fc5042e33..2df5a03194 100644 --- a/debian/debian/changelog +++ b/debian/debian/changelog @@ -1,3 +1,9 @@ +jenkins (1.566) unstable; urgency=low + + * See http://jenkins-ci.org/changelog for more details. + + -- Kohsuke Kawaguchi Mon, 02 Jun 2014 08:18:10 -0700 + jenkins (1.565) unstable; urgency=low * See http://jenkins-ci.org/changelog for more details. From 3f8fc4e2ec5b1b421e1551a2a2fc2a284be330d1 Mon Sep 17 00:00:00 2001 From: Jesse Glick Date: Mon, 2 Jun 2014 13:55:21 -0400 Subject: [PATCH 13/26] [FIXED JENKINS-23277] Better diagnosis for an NPE probably involving cloud slaves. --- .../src/main/java/hudson/model/AbstractBuild.java | 15 +++++++++++++-- core/src/main/java/hudson/model/Executor.java | 7 ++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index 62a44b1870..cc304ea38e 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -87,6 +87,7 @@ import javax.annotation.CheckForNull; import org.kohsuke.stapler.interceptor.RequirePOST; import static java.util.logging.Level.WARNING; +import javax.annotation.Nonnull; import jenkins.model.lazy.BuildReference; import jenkins.model.lazy.LazyBuildMixIn; @@ -435,9 +436,19 @@ public abstract class AbstractBuild

    ,R extends Abs /** * Returns the current {@link Node} on which we are building. + * @throws IllegalStateException if that cannot be determined */ - protected final Node getCurrentNode() { - return Executor.currentExecutor().getOwner().getNode(); + protected final @Nonnull Node getCurrentNode() throws IllegalStateException { + Executor exec = Executor.currentExecutor(); + if (exec == null) { + throw new IllegalStateException("not being called from an executor thread"); + } + Computer c = exec.getOwner(); + Node node = c.getNode(); + if (node == null) { + throw new IllegalStateException("no longer a configured node for " + c.getName()); + } + return node; } public Launcher getLauncher() { diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index e0cfe64ed7..4353ad7546 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -59,6 +59,7 @@ import java.util.logging.Logger; import static hudson.model.queue.Executables.*; import static java.util.logging.Level.*; import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; /** @@ -70,7 +71,7 @@ import javax.annotation.CheckForNull; */ @ExportedBean public class Executor extends Thread implements ModelObject { - protected final Computer owner; + protected final @Nonnull Computer owner; private final Queue queue; private long startTime; @@ -111,7 +112,7 @@ public class Executor extends Thread implements ModelObject { */ private final List causes = new Vector(); - public Executor(Computer owner, int n) { + public Executor(@Nonnull Computer owner, int n) { super("Executor #"+n+" for "+owner.getDisplayName()); this.owner = owner; this.queue = Jenkins.getInstance().getQueue(); @@ -534,7 +535,7 @@ public class Executor extends Thread implements ModelObject { return e!=null && Tasks.getOwnerTaskOf(getParentOf(e)).hasAbortPermission(); } - public Computer getOwner() { + public @Nonnull Computer getOwner() { return owner; } From d3cbc2524ee32b7021f27a70bbfb1348de298515 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Tue, 22 Apr 2014 12:58:11 +0400 Subject: [PATCH 14/26] Minor improvements in Jenkins Node-related classes. The change adds some missing null checks Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/model/Computer.java | 9 +++++++-- core/src/main/java/hudson/model/Node.java | 2 +- .../java/hudson/slaves/CloudRetentionStrategy.java | 10 +++++++--- .../src/main/java/hudson/slaves/RetentionStrategy.java | 8 ++++++-- core/src/main/java/hudson/slaves/SlaveComputer.java | 2 +- 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index 86fbb6c0ea..99728d9a42 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -204,7 +204,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * This is where the log from the remote agent goes. - * + * The method also creates a log directory if required. * @see #relocateOldLogs() */ protected File getLogFile() { @@ -1348,7 +1348,12 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces if (m.matches()) { File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2))); newLocation.getParentFile().mkdirs(); - f.renameTo(newLocation); + boolean relocationSuccessfull=f.renameTo(newLocation); + if (relocationSuccessfull) { // The operation will fail if mkdir fails + LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()}); + } else { + LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()}); + } } else { assert false; } diff --git a/core/src/main/java/hudson/model/Node.java b/core/src/main/java/hudson/model/Node.java index fe9fbe0841..e78b2cd5e8 100644 --- a/core/src/main/java/hudson/model/Node.java +++ b/core/src/main/java/hudson/model/Node.java @@ -202,7 +202,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable // At startup, we need to restore any previously in-effect temp offline cause. // We wait until the computer is started rather than getting the data to it sooner // so that the normal computer start up processing works as expected. - if (node.temporaryOfflineCause != null && node.temporaryOfflineCause != c.getOfflineCause()) { + if (node!= null && node.temporaryOfflineCause != null && node.temporaryOfflineCause != c.getOfflineCause()) { c.setTemporarilyOffline(true, node.temporaryOfflineCause); } } diff --git a/core/src/main/java/hudson/slaves/CloudRetentionStrategy.java b/core/src/main/java/hudson/slaves/CloudRetentionStrategy.java index d15180fa95..562a39331e 100644 --- a/core/src/main/java/hudson/slaves/CloudRetentionStrategy.java +++ b/core/src/main/java/hudson/slaves/CloudRetentionStrategy.java @@ -23,10 +23,12 @@ */ package hudson.slaves; +import hudson.model.Node; import java.io.IOException; import java.util.logging.Logger; import static hudson.util.TimeUnit2.*; +import java.util.logging.Level; import static java.util.logging.Level.*; /** @@ -43,13 +45,15 @@ public class CloudRetentionStrategy extends RetentionStrategy MINUTES.toMillis(idleMinutes)) { - LOGGER.info("Disconnecting "+c.getName()); + LOGGER.log(Level.INFO, "Disconnecting {0}",c.getName()); try { - c.getNode().terminate(); + computerNode.terminate(); } catch (InterruptedException e) { LOGGER.log(WARNING,"Failed to terminate "+c.getName(),e); } catch (IOException e) { diff --git a/core/src/main/java/hudson/slaves/RetentionStrategy.java b/core/src/main/java/hudson/slaves/RetentionStrategy.java index bb595954a4..95cb99b375 100644 --- a/core/src/main/java/hudson/slaves/RetentionStrategy.java +++ b/core/src/main/java/hudson/slaves/RetentionStrategy.java @@ -193,6 +193,7 @@ public abstract class RetentionStrategy extends AbstractDesc return idleDelay; } + @Override public synchronized long check(SlaveComputer c) { if (c.isOffline() && c.isLaunchSupported()) { final HashMap availableComputers = new HashMap(); @@ -211,7 +212,8 @@ public abstract class RetentionStrategy extends AbstractDesc // assume the answer is no until we can find such an executor boolean needExecutor = true; for (Computer o : Collections.unmodifiableSet(availableComputers.keySet())) { - if (o.getNode().canTake(item) == null) { + Node otherNode = o.getNode(); + if (otherNode != null && otherNode.canTake(item) == null) { needExecutor = false; final int availableExecutors = availableComputers.remove(o); if (availableExecutors > 1) { @@ -224,7 +226,8 @@ public abstract class RetentionStrategy extends AbstractDesc } // this 'item' cannot be built by any of the existing idle nodes, but it can be built by 'c' - if (needExecutor && c.getNode().canTake(item) == null) { + Node checkedNode = c.getNode(); + if (needExecutor && checkedNode != null && checkedNode.canTake(item) == null) { demandMilliseconds = System.currentTimeMillis() - item.buildableStartMilliseconds; needComputer = demandMilliseconds > inDemandDelay * 1000 * 60 /*MINS->MILLIS*/; break; @@ -251,6 +254,7 @@ public abstract class RetentionStrategy extends AbstractDesc @Extension public static class DescriptorImpl extends Descriptor> { + @Override public String getDisplayName() { return Messages.RetentionStrategy_Demand_displayName(); } diff --git a/core/src/main/java/hudson/slaves/SlaveComputer.java b/core/src/main/java/hudson/slaves/SlaveComputer.java index 3a73b99829..3b04a61556 100644 --- a/core/src/main/java/hudson/slaves/SlaveComputer.java +++ b/core/src/main/java/hudson/slaves/SlaveComputer.java @@ -418,7 +418,7 @@ public class SlaveComputer extends Computer { } /** - * Sets up the connection through an exsting channel. + * Sets up the connection through an existing channel. * * @since 1.444 */ From abbde7745873cb34cee56d0fcafdd11d45acc6b8 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Sat, 26 Apr 2014 17:23:26 +0400 Subject: [PATCH 15/26] Added missing null checks for Computer::getNode(), SlaveComputer::getNode() and AbstractBuild::getCurrentNode() Signed-off-by: Oleg Nenashev Conflicts: core/src/main/java/hudson/model/AbstractBuild.java --- .../java/hudson/cli/InstallToolCommand.java | 3 +++ .../main/java/hudson/model/AbstractBuild.java | 23 ++++++++++++++----- .../java/hudson/model/AbstractCIBase.java | 5 ++-- core/src/main/java/hudson/model/Computer.java | 9 ++++++-- core/src/main/java/hudson/model/Queue.java | 3 +++ .../node_monitors/DiskSpaceMonitor.java | 6 ++++- .../node_monitors/TemporarySpaceMonitor.java | 6 ++++- .../hudson/slaves/AbstractCloudComputer.java | 7 +++++- .../java/hudson/slaves/CommandLauncher.java | 11 +++++++-- .../main/java/hudson/slaves/NodeSpecific.java | 3 ++- .../java/hudson/slaves/SlaveComputer.java | 13 +++++++++-- .../java/hudson/tools/ToolInstallation.java | 6 +++-- .../hudson/model/Messages.properties | 1 + 13 files changed, 76 insertions(+), 20 deletions(-) diff --git a/core/src/main/java/hudson/cli/InstallToolCommand.java b/core/src/main/java/hudson/cli/InstallToolCommand.java index fb30efd0c0..f5ad164f95 100644 --- a/core/src/main/java/hudson/cli/InstallToolCommand.java +++ b/core/src/main/java/hudson/cli/InstallToolCommand.java @@ -122,6 +122,9 @@ public class InstallToolCommand extends CLICommand { throw new AbortException(b.getFullDisplayName()+" is not building"); Node node = exec.getOwner().getNode(); + if (node == null) { + throw new AbortException("The node " + exec.getOwner().getDisplayName() + " has been deleted"); + } t = t.translate(node, EnvVars.getRemote(checkChannel()), new StreamTaskListener(stderr)); stdout.println(t.getHome()); diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index cc304ea38e..ff9c98f051 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -84,10 +84,11 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; import org.kohsuke.stapler.interceptor.RequirePOST; import static java.util.logging.Level.WARNING; -import javax.annotation.Nonnull; + import jenkins.model.lazy.BuildReference; import jenkins.model.lazy.LazyBuildMixIn; @@ -436,6 +437,7 @@ public abstract class AbstractBuild

    ,R extends Abs /** * Returns the current {@link Node} on which we are building. + * @return Returns the current {@link Node} or null if current thread is not an executor. * @throws IllegalStateException if that cannot be determined */ protected final @Nonnull Node getCurrentNode() throws IllegalStateException { @@ -477,8 +479,12 @@ public abstract class AbstractBuild

    ,R extends Abs return wsl.allocate(n.getWorkspaceFor((TopLevelItem)getProject()), getBuild()); } - public Result run(BuildListener listener) throws Exception { - Node node = getCurrentNode(); + public Result run(@Nonnull BuildListener listener) throws Exception { + final Node node = getCurrentNode(); + if (node == null) { + throw new AbortException(Messages.AbstractBuild_NoExecutorError()); + } + assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Jenkins.VERSION; @@ -566,8 +572,13 @@ public abstract class AbstractBuild

    ,R extends Abs * @param listener * Always non-null. Connected to the main build output. */ - protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException { - Launcher l = getCurrentNode().createLauncher(listener); + @Nonnull + protected Launcher createLauncher(@Nonnull BuildListener listener) throws IOException, InterruptedException { + final Node currentNode = getCurrentNode(); + if (currentNode == null) { + throw new AbortException(Messages.AbstractBuild_NoExecutorError()); + } + Launcher l = currentNode.createLauncher(listener); if (project instanceof BuildableItemWithBuildWrappers) { BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; @@ -591,7 +602,7 @@ public abstract class AbstractBuild

    ,R extends Abs } } - for (NodeProperty nodeProperty: Computer.currentComputer().getNode().getNodeProperties()) { + for (NodeProperty nodeProperty: currentNode.getNodeProperties()) { Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); diff --git a/core/src/main/java/hudson/model/AbstractCIBase.java b/core/src/main/java/hudson/model/AbstractCIBase.java index 11b1c7cff8..08254d7808 100644 --- a/core/src/main/java/hudson/model/AbstractCIBase.java +++ b/core/src/main/java/hudson/model/AbstractCIBase.java @@ -165,9 +165,10 @@ public abstract class AbstractCIBase extends Node implements ItemGroup byName = new HashMap(); for (Computer c : computers.values()) { - if(c.getNode()==null) + Node node = c.getNode(); + if (node == null) continue; // this computer is gone - byName.put(c.getNode().getNodeName(),c); + byName.put(node.getNodeName(),c); } Set old = new HashSet(computers.values()); diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index 99728d9a42..c29fe159f4 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -1196,7 +1196,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces // read checkPermission(EXTENDED_READ); rsp.setContentType("application/xml"); - Jenkins.XSTREAM2.toXMLUTF8(getNode(), rsp.getOutputStream()); + Node node = getNode(); + if (node == null) { + throw new ServletException("No such node " + nodeName); + } + Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream()); return; } if (req.getMethod().equals("POST")) { @@ -1218,7 +1222,8 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces // replace the old Node object by the new one synchronized (app) { List nodes = new ArrayList(app.getNodes()); - int i = nodes.indexOf(getNode()); + Node node = getNode(); + int i = (node != null) ? nodes.indexOf(node) : -1; if(i<0) { throw new IOException("This slave appears to be removed while you were editing the configuration"); } diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index 518be29e47..c1e4bfa0c8 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -283,6 +283,7 @@ public class Queue extends ResourceController implements Saveable { return workUnit == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks(); } + @CheckForNull public Node getNode() { return executor.getOwner().getNode(); } @@ -739,6 +740,8 @@ public class Queue extends ResourceController implements Saveable { private void _getBuildableItems(Computer c, ItemList col, List result) { Node node = c.getNode(); + if (node == null) // Deleted computers cannot take build items... + return; for (BuildableItem p : col.values()) { if (node.canTake(p) == null) result.add(p); diff --git a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java index 705675f035..9f185b5891 100644 --- a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java @@ -26,6 +26,7 @@ package hudson.node_monitors; import hudson.Extension; import hudson.FilePath; import hudson.model.Computer; +import hudson.model.Node; import hudson.remoting.Callable; import jenkins.model.Jenkins; import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace; @@ -66,7 +67,10 @@ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor { @Override protected Callable createCallable(Computer c) { - FilePath p = c.getNode().getRootPath(); + Node node = c.getNode(); + if (node == null) return null; + + FilePath p = node.getRootPath(); if(p==null) return null; return p.asCallableWith(new GetUsableSpace()); diff --git a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java index c43d63a509..e42951ff12 100644 --- a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java @@ -27,6 +27,7 @@ import hudson.Extension; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.model.Computer; +import hudson.model.Node; import hudson.remoting.Callable; import jenkins.model.Jenkins; import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace; @@ -67,7 +68,10 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor { @Override protected Callable createCallable(Computer c) { - FilePath p = c.getNode().getRootPath(); + Node node = c.getNode(); + if (node == null) return null; + + FilePath p = node.getRootPath(); if(p==null) return null; return p.asCallableWith(new GetTempSpace()); diff --git a/core/src/main/java/hudson/slaves/AbstractCloudComputer.java b/core/src/main/java/hudson/slaves/AbstractCloudComputer.java index 2719f438c0..a76f33e7e4 100644 --- a/core/src/main/java/hudson/slaves/AbstractCloudComputer.java +++ b/core/src/main/java/hudson/slaves/AbstractCloudComputer.java @@ -29,6 +29,7 @@ import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import java.io.IOException; +import javax.annotation.CheckForNull; /** * Partial implementation of {@link Computer} to be used in conjunction with @@ -42,6 +43,7 @@ public class AbstractCloudComputer extends SlaveCo super(slave); } + @CheckForNull @Override public T getNode() { return (T) super.getNode(); @@ -54,7 +56,10 @@ public class AbstractCloudComputer extends SlaveCo public HttpResponse doDoDelete() throws IOException { checkPermission(DELETE); try { - getNode().terminate(); + T node = getNode(); + if (node != null) { // Node need to terminate nodes again + node.terminate(); + } return new HttpRedirect(".."); } catch (InterruptedException e) { return HttpResponses.error(500,e); diff --git a/core/src/main/java/hudson/slaves/CommandLauncher.java b/core/src/main/java/hudson/slaves/CommandLauncher.java index 8c86abccad..8d08f9b39c 100644 --- a/core/src/main/java/hudson/slaves/CommandLauncher.java +++ b/core/src/main/java/hudson/slaves/CommandLauncher.java @@ -23,10 +23,12 @@ */ package hudson.slaves; +import hudson.AbortException; import hudson.EnvVars; import hudson.Util; import hudson.Extension; import hudson.model.Descriptor; +import hudson.model.Slave; import jenkins.model.Jenkins; import hudson.model.TaskListener; import hudson.remoting.Channel; @@ -87,6 +89,11 @@ public class CommandLauncher extends ComputerLauncher { EnvVars _cookie = null; Process _proc = null; try { + Slave node = computer.getNode(); + if (node == null) { + throw new AbortException("Cannot launch commands on deleted nodes"); + } + listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp())); if(getCommand().trim().length()==0) { listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand()); @@ -96,8 +103,8 @@ public class CommandLauncher extends ComputerLauncher { ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand())); final EnvVars cookie = _cookie = EnvVars.createCookie(); - pb.environment().putAll(cookie); - pb.environment().put("WORKSPACE", computer.getNode().getRemoteFS()); //path for local slave log + pb.environment().putAll(cookie); + pb.environment().put("WORKSPACE", node.getRemoteFS()); //path for local slave log {// system defined variables String rootUrl = Jenkins.getInstance().getRootUrl(); diff --git a/core/src/main/java/hudson/slaves/NodeSpecific.java b/core/src/main/java/hudson/slaves/NodeSpecific.java index d585ab3d04..59ee2ca217 100644 --- a/core/src/main/java/hudson/slaves/NodeSpecific.java +++ b/core/src/main/java/hudson/slaves/NodeSpecific.java @@ -24,6 +24,7 @@ package hudson.slaves; +import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Node; import hudson.model.EnvironmentSpecific; import hudson.model.TaskListener; @@ -44,5 +45,5 @@ public interface NodeSpecific> { /** * Returns a specialized copy of T for functioning in the given node. */ - T forNode(Node node, TaskListener log) throws IOException, InterruptedException; + T forNode(@NonNull Node node, TaskListener log) throws IOException, InterruptedException; } diff --git a/core/src/main/java/hudson/slaves/SlaveComputer.java b/core/src/main/java/hudson/slaves/SlaveComputer.java index 3b04a61556..8870d8e593 100644 --- a/core/src/main/java/hudson/slaves/SlaveComputer.java +++ b/core/src/main/java/hudson/slaves/SlaveComputer.java @@ -78,8 +78,11 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import javax.annotation.CheckForNull; +import jenkins.model.Jenkins; import static hudson.slaves.SlaveComputer.LogHolder.*; + /** * {@link Computer} for {@link Slave}s. * @@ -168,6 +171,7 @@ public class SlaveComputer extends Computer { return isUnix; } + @CheckForNull @Override public Slave getNode() { Node node = super.getNode(); @@ -454,10 +458,15 @@ public class SlaveComputer extends Computer { String defaultCharsetName = channel.call(new DetectDefaultCharset()); - String remoteFs = getNode().getRemoteFS(); + Slave node = getNode(); + if (node == null) { // Node has been disabled/removed during the connection + throw new IOException("Node "+nodeName+" has been deleted during the channel setup"); + } + + String remoteFs = node.getRemoteFS(); if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\")) log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?"); - FilePath root = new FilePath(channel,getNode().getRemoteFS()); + FilePath root = new FilePath(channel,node.getRemoteFS()); // reference counting problem is known to happen, such as JENKINS-9017, and so as a preventive measure // we pin the base classloader so that it'll never get GCed. When this classloader gets released, diff --git a/core/src/main/java/hudson/tools/ToolInstallation.java b/core/src/main/java/hudson/tools/ToolInstallation.java index 890d13e69b..4a0235ff0f 100644 --- a/core/src/main/java/hudson/tools/ToolInstallation.java +++ b/core/src/main/java/hudson/tools/ToolInstallation.java @@ -41,6 +41,8 @@ import java.util.List; import com.thoughtworks.xstream.annotations.XStreamSerializable; import com.thoughtworks.xstream.converters.UnmarshallingContext; import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import jenkins.model.Jenkins; /** @@ -152,7 +154,7 @@ public abstract class ToolInstallation extends AbstractDescribableImpl Date: Sat, 3 May 2014 00:27:15 +0400 Subject: [PATCH 16/26] [nodes handling] - Fixed code according to comments from @jglick Signed-off-by: Oleg Nenashev Conflicts: core/src/main/java/hudson/model/Job.java --- core/src/main/java/hudson/model/AbstractBuild.java | 6 +++--- core/src/main/java/hudson/model/Computer.java | 2 +- core/src/main/java/hudson/slaves/AbstractCloudComputer.java | 2 +- core/src/main/java/hudson/tools/ToolInstallation.java | 1 - 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index ff9c98f051..aca30a29d3 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -469,7 +469,7 @@ public abstract class AbstractBuild

    ,R extends Abs * @param wsl * Passed in for the convenience. The returned path must be registered to this object. */ - protected Lease decideWorkspace(Node n, WorkspaceList wsl) throws InterruptedException, IOException { + protected Lease decideWorkspace(@Nonnull Node n, WorkspaceList wsl) throws InterruptedException, IOException { String customWorkspace = getProject().getCustomWorkspace(); if (customWorkspace != null) { // we allow custom workspaces to be concurrently used between jobs. @@ -482,7 +482,7 @@ public abstract class AbstractBuild

    ,R extends Abs public Result run(@Nonnull BuildListener listener) throws Exception { final Node node = getCurrentNode(); if (node == null) { - throw new AbortException(Messages.AbstractBuild_NoExecutorError()); + throw new IllegalStateException("Cannot run the build outside executor threads"); } assert builtOn==null; @@ -576,7 +576,7 @@ public abstract class AbstractBuild

    ,R extends Abs protected Launcher createLauncher(@Nonnull BuildListener listener) throws IOException, InterruptedException { final Node currentNode = getCurrentNode(); if (currentNode == null) { - throw new AbortException(Messages.AbstractBuild_NoExecutorError()); + throw new IllegalStateException("Launchers can be created inside executor threads only"); } Launcher l = currentNode.createLauncher(listener); diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index c29fe159f4..201e08271f 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -1198,7 +1198,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces rsp.setContentType("application/xml"); Node node = getNode(); if (node == null) { - throw new ServletException("No such node " + nodeName); + HttpResponses.notFound(); } Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream()); return; diff --git a/core/src/main/java/hudson/slaves/AbstractCloudComputer.java b/core/src/main/java/hudson/slaves/AbstractCloudComputer.java index a76f33e7e4..32acc2030a 100644 --- a/core/src/main/java/hudson/slaves/AbstractCloudComputer.java +++ b/core/src/main/java/hudson/slaves/AbstractCloudComputer.java @@ -57,7 +57,7 @@ public class AbstractCloudComputer extends SlaveCo checkPermission(DELETE); try { T node = getNode(); - if (node != null) { // Node need to terminate nodes again + if (node != null) { // No need to terminate nodes again node.terminate(); } return new HttpRedirect(".."); diff --git a/core/src/main/java/hudson/tools/ToolInstallation.java b/core/src/main/java/hudson/tools/ToolInstallation.java index 4a0235ff0f..370c1119a2 100644 --- a/core/src/main/java/hudson/tools/ToolInstallation.java +++ b/core/src/main/java/hudson/tools/ToolInstallation.java @@ -42,7 +42,6 @@ import com.thoughtworks.xstream.annotations.XStreamSerializable; import com.thoughtworks.xstream.converters.UnmarshallingContext; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; -import javax.annotation.Nullable; import jenkins.model.Jenkins; /** From e1ffeec0f74da542652ed6bc7895f292fc88072b Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Sat, 3 May 2014 23:33:20 +0400 Subject: [PATCH 17/26] [node null checks] - Throw the HTTP "Not found exception" Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/model/Computer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index 201e08271f..33e2721712 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -1198,7 +1198,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces rsp.setContentType("application/xml"); Node node = getNode(); if (node == null) { - HttpResponses.notFound(); + throw HttpResponses.notFound(); } Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream()); return; From f56a3bdae5baa68a7427efdface0a04028e7d010 Mon Sep 17 00:00:00 2001 From: Jesse Glick Date: Mon, 2 Jun 2014 16:57:38 -0400 Subject: [PATCH 18/26] [JENKINS-17374] [JENKINS-18116] Noting merge of #1260. --- changelog.html | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/changelog.html b/changelog.html index e014b06885..f0611d2552 100644 --- a/changelog.html +++ b/changelog.html @@ -82,6 +82,10 @@ Upcoming changes

  • Process the items hierarchy when displaying the Show Poll Thread Count option (issue 22934) +
  • + Compressed output was turned on even before Access Denied errors were shown for disallowed Remote API requests, yielding a confusing error. + (issue 17374) + (issue 18116)
  • Properly close input streams in FileParameterValue (issue 22693) From 1a8a79dde14b76b77593a017a3874532a7b9dbb0 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Mon, 2 Jun 2014 21:33:29 -0700 Subject: [PATCH 19/26] creating an RC branch --- changelog.html | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/changelog.html b/changelog.html index f0611d2552..b3d3660dd5 100644 --- a/changelog.html +++ b/changelog.html @@ -54,6 +54,14 @@ Upcoming changes + + + - - -

    What's new in 1.566 (2014/06/01)

      From 4f41d2aa28d659753286635c5892fa0a9f6f9dc7 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Mon, 2 Jun 2014 21:33:41 -0700 Subject: [PATCH 20/26] the trunk is toward 1.568-SNAPSHOT --- cli/pom.xml | 2 +- core/pom.xml | 2 +- plugins/pom.xml | 8 ++++---- pom.xml | 2 +- test/pom.xml | 2 +- war/pom.xml | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cli/pom.xml b/cli/pom.xml index 711bcde229..d9b86906b0 100644 --- a/cli/pom.xml +++ b/cli/pom.xml @@ -5,7 +5,7 @@ pom org.jenkins-ci.main - 1.567-SNAPSHOT + 1.568-SNAPSHOT cli diff --git a/core/pom.xml b/core/pom.xml index cccf922c7d..e9be9512ed 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -29,7 +29,7 @@ THE SOFTWARE. org.jenkins-ci.main pom - 1.567-SNAPSHOT + 1.568-SNAPSHOT ../pom.xml diff --git a/plugins/pom.xml b/plugins/pom.xml index 2863a3e417..3230896b79 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -11,7 +11,7 @@ org.jenkins-ci.plugins plugin Jenkins plugin POM - 1.567-SNAPSHOT + 1.568-SNAPSHOT pom From 5d32d495d5c777c4f21c9ae57b26a98ea615f862 Mon Sep 17 00:00:00 2001 From: Jesse Glick Date: Tue, 3 Jun 2014 15:23:13 -0400 Subject: [PATCH 23/26] getTransientActions should defend against null members even when assertions are disabled. Cf.: https://github.com/jenkinsci/remote-terminal-access-plugin/commit/db24e2126b649689652ac8ddb100f3ef6680a422 --- core/src/main/java/hudson/model/Run.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index 9f7ef06c17..bb3873ecbf 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -359,8 +359,13 @@ public abstract class Run ,RunT extends Run getTransientActions() { List actions = new ArrayList(); for (TransientBuildActionFactory factory: TransientBuildActionFactory.all()) { - actions.addAll(factory.createFor(this)); - assert !actions.contains(null) : "null action added by " + factory; + for (Action created : factory.createFor(this)) { + if (created == null) { + LOGGER.log(WARNING, "null action added by {0}", factory); + continue; + } + actions.add(created); + } } return Collections.unmodifiableList(actions); } From e5cacd1780230fdd6056538d069978b3644295f6 Mon Sep 17 00:00:00 2001 From: Oleg Nenashev Date: Tue, 3 Jun 2014 23:37:05 +0400 Subject: [PATCH 24/26] Fixed node handling methods in order to comply with https://github.com/jenkinsci/jenkins/commit/3f8fc4e2ec5b1b421e1551a2a2fc2a284be330d1 Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/model/AbstractBuild.java | 8 +------- core/src/main/java/hudson/slaves/SlaveComputer.java | 2 +- core/src/main/java/hudson/tools/ToolInstallation.java | 2 +- core/src/main/resources/hudson/model/Messages.properties | 1 - 4 files changed, 3 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index aca30a29d3..77d08046b4 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -437,7 +437,7 @@ public abstract class AbstractBuild

      ,R extends Abs /** * Returns the current {@link Node} on which we are building. - * @return Returns the current {@link Node} or null if current thread is not an executor. + * @return Returns the current {@link Node} * @throws IllegalStateException if that cannot be determined */ protected final @Nonnull Node getCurrentNode() throws IllegalStateException { @@ -481,9 +481,6 @@ public abstract class AbstractBuild

      ,R extends Abs public Result run(@Nonnull BuildListener listener) throws Exception { final Node node = getCurrentNode(); - if (node == null) { - throw new IllegalStateException("Cannot run the build outside executor threads"); - } assert builtOn==null; builtOn = node.getNodeName(); @@ -575,9 +572,6 @@ public abstract class AbstractBuild

      ,R extends Abs @Nonnull protected Launcher createLauncher(@Nonnull BuildListener listener) throws IOException, InterruptedException { final Node currentNode = getCurrentNode(); - if (currentNode == null) { - throw new IllegalStateException("Launchers can be created inside executor threads only"); - } Launcher l = currentNode.createLauncher(listener); if (project instanceof BuildableItemWithBuildWrappers) { diff --git a/core/src/main/java/hudson/slaves/SlaveComputer.java b/core/src/main/java/hudson/slaves/SlaveComputer.java index 8870d8e593..700bf44d59 100644 --- a/core/src/main/java/hudson/slaves/SlaveComputer.java +++ b/core/src/main/java/hudson/slaves/SlaveComputer.java @@ -466,7 +466,7 @@ public class SlaveComputer extends Computer { String remoteFs = node.getRemoteFS(); if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\")) log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?"); - FilePath root = new FilePath(channel,node.getRemoteFS()); + FilePath root = new FilePath(channel,remoteFs); // reference counting problem is known to happen, such as JENKINS-9017, and so as a preventive measure // we pin the base classloader so that it'll never get GCed. When this classloader gets released, diff --git a/core/src/main/java/hudson/tools/ToolInstallation.java b/core/src/main/java/hudson/tools/ToolInstallation.java index 370c1119a2..0ba5dd730c 100644 --- a/core/src/main/java/hudson/tools/ToolInstallation.java +++ b/core/src/main/java/hudson/tools/ToolInstallation.java @@ -153,7 +153,7 @@ public abstract class ToolInstallation extends AbstractDescribableImpl Date: Wed, 4 Jun 2014 18:31:39 +0400 Subject: [PATCH 25/26] Added annotations to kernel security classes. Most of methods define @Nonnull inputs and outputs (the legacy behavior is mostly non-documented), but there're several exceptions Signed-off-by: Oleg Nenashev --- core/src/main/java/hudson/security/ACL.java | 11 ++--- .../hudson/security/AccessControlled.java | 7 ++-- .../security/AuthorizationStrategy.java | 32 ++++++++------- .../main/java/hudson/security/Permission.java | 40 ++++++++++--------- 4 files changed, 50 insertions(+), 40 deletions(-) diff --git a/core/src/main/java/hudson/security/ACL.java b/core/src/main/java/hudson/security/ACL.java index 132344fc52..d13b53ec96 100644 --- a/core/src/main/java/hudson/security/ACL.java +++ b/core/src/main/java/hudson/security/ACL.java @@ -23,6 +23,7 @@ */ package hudson.security; +import javax.annotation.Nonnull; import jenkins.security.NonSerializableSecurityContext; import jenkins.model.Jenkins; import org.acegisecurity.AccessDeniedException; @@ -48,7 +49,7 @@ public abstract class ACL { * @throws AccessDeniedException * if the user doesn't have the permission. */ - public final void checkPermission(Permission p) { + public final void checkPermission(@Nonnull Permission p) { Authentication a = Jenkins.getAuthentication(); if(!hasPermission(a,p)) throw new AccessDeniedException2(a,p); @@ -60,7 +61,7 @@ public abstract class ACL { * @return false * if the user doesn't have the permission. */ - public final boolean hasPermission(Permission p) { + public final boolean hasPermission(@Nonnull Permission p) { return hasPermission(Jenkins.getAuthentication(),p); } @@ -71,7 +72,7 @@ public abstract class ACL { * Note that {@link #SYSTEM} can be passed in as the authentication parameter, * in which case you should probably just assume it has every permission. */ - public abstract boolean hasPermission(Authentication a, Permission permission); + public abstract boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission); // // Sid constants @@ -124,7 +125,7 @@ public abstract class ACL { * because the same {@link SecurityContext} object is reused for all the concurrent requests from the same session. * @since 1.462 */ - public static SecurityContext impersonate(Authentication auth) { + public static @Nonnull SecurityContext impersonate(@Nonnull Authentication auth) { SecurityContext old = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(new NonSerializableSecurityContext(auth)); return old; @@ -136,7 +137,7 @@ public abstract class ACL { * @param body an action to run with this alternate authentication in effect * @since 1.509 */ - public static void impersonate(Authentication auth, Runnable body) { + public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) { SecurityContext old = impersonate(auth); try { body.run(); diff --git a/core/src/main/java/hudson/security/AccessControlled.java b/core/src/main/java/hudson/security/AccessControlled.java index 5bed4a28dc..0b3e81adde 100644 --- a/core/src/main/java/hudson/security/AccessControlled.java +++ b/core/src/main/java/hudson/security/AccessControlled.java @@ -23,6 +23,7 @@ */ package hudson.security; +import javax.annotation.Nonnull; import org.acegisecurity.AccessDeniedException; /** @@ -36,16 +37,16 @@ public interface AccessControlled { * * @return never null. */ - ACL getACL(); + @Nonnull ACL getACL(); /** * Convenient short-cut for {@code getACL().checkPermission(permission)} */ - void checkPermission(Permission permission) throws AccessDeniedException; + void checkPermission(@Nonnull Permission permission) throws AccessDeniedException; /** * Convenient short-cut for {@code getACL().hasPermission(permission)} */ - boolean hasPermission(Permission permission); + boolean hasPermission(@Nonnull Permission permission); } diff --git a/core/src/main/java/hudson/security/AuthorizationStrategy.java b/core/src/main/java/hudson/security/AuthorizationStrategy.java index b110647fb5..da7d7348fd 100644 --- a/core/src/main/java/hudson/security/AuthorizationStrategy.java +++ b/core/src/main/java/hudson/security/AuthorizationStrategy.java @@ -33,6 +33,7 @@ import hudson.util.DescriptorList; import java.io.Serializable; import java.util.Collection; import java.util.Collections; +import javax.annotation.Nonnull; import jenkins.model.Jenkins; import net.sf.json.JSONObject; @@ -68,18 +69,18 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl * IOW, this ACL will have the ultimate say on the access control. */ - public abstract ACL getRootACL(); + public abstract @Nonnull ACL getRootACL(); /** * @deprecated since 1.277 * Override {@link #getACL(Job)} instead. */ @Deprecated - public ACL getACL(AbstractProject project) { + public @Nonnull ACL getACL(@Nonnull AbstractProject project) { return getACL((Job)project); } - public ACL getACL(Job project) { + public @Nonnull ACL getACL(@Nonnull Job project) { return getRootACL(); } @@ -93,7 +94,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl getGroups(); + public abstract @Nonnull Collection getGroups(); /** * Returns all the registered {@link AuthorizationStrategy} descriptors. */ - public static DescriptorExtensionList> all() { + public static @Nonnull DescriptorExtensionList> all() { return Jenkins.getInstance().>getDescriptorList(AuthorizationStrategy.class); } @@ -214,15 +215,17 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl getGroups() { + @Override + public @Nonnull Collection getGroups() { return Collections.emptySet(); } private static final ACL UNSECURED_ACL = new ACL() { + @Override public boolean hasPermission(Authentication a, Permission permission) { return true; } @@ -230,12 +233,13 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl { + @Override public String getDisplayName() { return Messages.AuthorizationStrategy_DisplayName(); } @Override - public AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException { + public @Nonnull AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException { return UNSECURED; } diff --git a/core/src/main/java/hudson/security/Permission.java b/core/src/main/java/hudson/security/Permission.java index f9b6bd4a0f..20c43b0980 100644 --- a/core/src/main/java/hudson/security/Permission.java +++ b/core/src/main/java/hudson/security/Permission.java @@ -34,6 +34,7 @@ import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import javax.annotation.CheckForNull; +import javax.annotation.Nonnull; import org.jvnet.localizer.Localizable; @@ -58,14 +59,14 @@ public final class Permission { */ // break eclipse compilation //Override - public int compare(Permission one, Permission two) { + public int compare(@Nonnull Permission one, @Nonnull Permission two) { return one.getId().compareTo(two.getId()); } }; - public final Class owner; + public final @Nonnull Class owner; - public final PermissionGroup group; + public final @Nonnull PermissionGroup group; /** * Human readable ID of the permission. @@ -76,7 +77,7 @@ public final class Permission { *

      * The expected naming convention is something like "BrowseWorkspace". */ - public final String name; + public final @Nonnull String name; /** * Human-readable description of this permission. @@ -86,7 +87,7 @@ public final class Permission { *

      * If null, there will be no description text. */ - public final Localizable description; + public final @CheckForNull Localizable description; /** * Bundled {@link Permission} that also implies this permission. @@ -101,7 +102,7 @@ public final class Permission { * such broad permission bundle is good enough, and those few * that need finer control can do so. */ - public final Permission impliedBy; + public final @CheckForNull Permission impliedBy; /** * Whether this permission is available for use. @@ -118,7 +119,7 @@ public final class Permission { /** * Scopes that this permission is directly contained by. */ - private final Set scopes; + private final @Nonnull Set scopes; /** * Defines a new permission. @@ -144,7 +145,9 @@ public final class Permission { * @param impliedBy * See {@link #impliedBy}. */ - public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, boolean enable, PermissionScope[] scopes) { + public Permission(@Nonnull PermissionGroup group, @Nonnull String name, + @CheckForNull Localizable description, @CheckForNull Permission impliedBy, boolean enable, + @Nonnull PermissionScope[] scopes) { if(!JSONUtils.isJavaIdentifier(name)) throw new IllegalArgumentException(name+" is not a Java identifier"); this.owner = group.owner; @@ -159,7 +162,8 @@ public final class Permission { ALL.add(this); } - public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, PermissionScope scope) { + public Permission(@Nonnull PermissionGroup group, @Nonnull String name, + @CheckForNull Localizable description, @CheckForNull Permission impliedBy, @Nonnull PermissionScope scope) { this(group,name,description,impliedBy,true,new PermissionScope[]{scope}); assert scope!=null; } @@ -168,7 +172,7 @@ public final class Permission { * @deprecated as of 1.421 * Use {@link #Permission(PermissionGroup, String, Localizable, Permission, boolean, PermissionScope[])} */ - public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, boolean enable) { + public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Localizable description, @CheckForNull Permission impliedBy, boolean enable) { this(group,name,description,impliedBy,enable,new PermissionScope[]{PermissionScope.JENKINS}); } @@ -176,7 +180,7 @@ public final class Permission { * @deprecated as of 1.421 * Use {@link #Permission(PermissionGroup, String, Localizable, Permission, PermissionScope)} */ - public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy) { + public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Localizable description, @CheckForNull Permission impliedBy) { this(group, name, description, impliedBy, PermissionScope.JENKINS); } @@ -184,18 +188,18 @@ public final class Permission { * @deprecated since 1.257. * Use {@link #Permission(PermissionGroup, String, Localizable, Permission)} */ - public Permission(PermissionGroup group, String name, Permission impliedBy) { + public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Permission impliedBy) { this(group,name,null,impliedBy); } - private Permission(PermissionGroup group, String name) { + private Permission(@Nonnull PermissionGroup group, @Nonnull String name) { this(group,name,null,null); } /** * Checks if this permission is contained in the specified scope, (either directly or indirectly.) */ - public boolean isContainedBy(PermissionScope s) { + public boolean isContainedBy(@Nonnull PermissionScope s) { for (PermissionScope c : scopes) { if (c.isContainedBy(s)) return true; @@ -210,10 +214,10 @@ public final class Permission { * *

      * This string representation is suitable for persistence. - * + * @return ID with the following format: permissionClass.permissionName * @see #fromId(String) */ - public String getId() { + public @Nonnull String getId() { return owner.getName()+'.'+name; } @@ -224,7 +228,7 @@ public final class Permission { * null if the conversion failed. * @see #getId() */ - public static @CheckForNull Permission fromId(String id) { + public static @CheckForNull Permission fromId(@Nonnull String id) { int idx = id.lastIndexOf('.'); if(idx<0) return null; @@ -257,7 +261,7 @@ public final class Permission { * @return * always non-null. Read-only. */ - public static List getAll() { + public static @Nonnull List getAll() { return ALL_VIEW; } From 9ce6b0fec3c0a0f1b9ea786865b2130a900a5886 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Wed, 4 Jun 2014 11:29:30 -0700 Subject: [PATCH 26/26] Integrating a new version that supports multiple issue trackers --- test/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/pom.xml b/test/pom.xml index 342188b473..669fd5eb56 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -103,9 +103,9 @@ THE SOFTWARE. 6.1.26 - org.jvnet.hudson + org.jenkins-ci test-annotations - 1.0 + 1.1 compile