Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JENKINS-72111] Allow Lifecycle to load implementations from plugins #8589

Merged
merged 1 commit into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions core/src/main/java/hudson/PluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,10 @@

// obtain topologically sorted list and overwrite the list
for (PluginWrapper p : cgd.getSorted()) {
if (p.isActive())
if (p.isActive()) {

Check warning on line 509 in core/src/main/java/hudson/PluginManager.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 509 is only partially covered, one branch is missing
activePlugins.add(p);
((UberClassLoader) uberClassLoader).clearCacheMisses();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found that UberClassLoader.loaded cached class loading misses after plugins were loaded during startup. This would not normally be noticeable, but in this case a call to Lifecycle.get before initializing plugins would cache the miss and it would not subsequently be cleared.

}
}
} catch (CycleDetectedException e) { // TODO this should be impossible, since we override reactOnCycle to not throw the exception
stop(); // disable all plugins since classloading from them can lead to StackOverflow
Expand Down Expand Up @@ -932,9 +934,10 @@
// so existing plugins can't be depending on this newly deployed one.

plugins.add(p);
if (p.isActive())
if (p.isActive()) {
activePlugins.add(p);
((UberClassLoader) uberClassLoader).loaded.clear();
((UberClassLoader) uberClassLoader).clearCacheMisses();
Comment on lines -937 to +939
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for dynamic plugin loading, so already cleared the cache, though also cache hits which seemed unnecessary.

}

// TODO antimodular; perhaps should have a PluginListener to complement ExtensionListListener?
CustomClassFilter.Contributed.load();
Expand Down Expand Up @@ -2385,6 +2388,10 @@
return Collections.enumeration(resources);
}

void clearCacheMisses() {
loaded.values().removeIf(Optional::isEmpty);
}

@Override
public String toString() {
// only for debugging purpose
Expand Down
33 changes: 27 additions & 6 deletions core/src/main/java/hudson/lifecycle/Lifecycle.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import hudson.ExtensionPoint;
import hudson.Functions;
import hudson.Util;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
Expand All @@ -40,6 +42,8 @@
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import org.apache.commons.io.FileUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

/**
* Provides the capability for starting/stopping/restarting/uninstalling Hudson.
Expand All @@ -48,7 +52,8 @@
* The steps to perform these operations depend on how Hudson is launched,
* so the concrete instance of this method (which is VM-wide singleton) is discovered
* by looking up a FQCN from the system property "hudson.lifecycle".
*
* (This may be set to a class defined in a plugin,
* in which case the singleton switches during startup.)
* @author Kohsuke Kawaguchi
* @since 1.254
*/
Expand All @@ -57,9 +62,8 @@

/**
* Gets the singleton instance.
*
* @return never null
*/
@NonNull
public static synchronized Lifecycle get() {
if (INSTANCE == null) {
Lifecycle instance;
Expand All @@ -81,9 +85,8 @@
x.initCause(e);
throw x;
} catch (ClassNotFoundException e) {
NoClassDefFoundError x = new NoClassDefFoundError(e.getMessage());
x.initCause(e);
throw x;
LOGGER.log(Level.FINE, e, () -> "Failed to load " + p + " so will try again later");
instance = new PlaceholderLifecycle();
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
Expand Down Expand Up @@ -307,5 +310,23 @@
LOGGER.log(Level.INFO, status);
}

@Restricted(NoExternalUse.class)
public static final class PlaceholderLifecycle extends ExitLifecycle {

@Initializer(after = InitMilestone.PLUGINS_STARTED, before = InitMilestone.EXTENSIONS_AUGMENTED)
public static synchronized void replacePlaceholder() {
if (get() instanceof PlaceholderLifecycle) {
String p = SystemProperties.getString("hudson.lifecycle");
try {
INSTANCE = (Lifecycle) Jenkins.get().getPluginManager().uberClassLoader.loadClass(p).getConstructor().newInstance();
LOGGER.fine(() -> "Updated to " + INSTANCE);
} catch (Exception | LinkageError x) {

Check warning on line 323 in core/src/main/java/hudson/lifecycle/Lifecycle.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 323 is not covered by tests
LOGGER.log(Level.WARNING, x, () -> "Failed to load " + p + "; using fallback exit lifecycle");

Check warning on line 324 in core/src/main/java/hudson/lifecycle/Lifecycle.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 324 is not covered by tests
}
}
}

}

private static final Logger LOGGER = Logger.getLogger(Lifecycle.class.getName());
}
62 changes: 62 additions & 0 deletions test/src/test/java/hudson/lifecycle/LifecycleTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* The MIT License
*
* Copyright 2023 CloudBees, 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.lifecycle;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import java.lang.reflect.Field;
import java.util.logging.Level;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.RealJenkinsRule;

public final class LifecycleTest {

@Rule
public RealJenkinsRule rr = new RealJenkinsRule()
.addPlugins("plugins/custom-lifecycle.hpi")
.javaOptions("-Dhudson.lifecycle=test.custom_lifecycle.CustomLifecycle")
.withLogger(Lifecycle.class, Level.FINE);

@Test
public void definedInPlugin() throws Throwable {
rr.then(LifecycleTest::_definedInPlugin);
}

private static void _definedInPlugin(JenkinsRule r) throws Throwable {
Class<? extends Lifecycle> type = Jenkins.get().getPluginManager().uberClassLoader
.loadClass("test.custom_lifecycle.CustomLifecycle").asSubclass(Lifecycle.class);
Lifecycle l = Lifecycle.get();
assertThat(l.getClass(), is(type));
Field count = type.getField("count");
assertThat(count.get(l), is(0));
Lifecycle.get().restart();
assertThat(count.get(l), is(1));
}

}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I retained sources in the plugin archive, but for the convenience of reviewers:

package test.custom_lifecycle;
import hudson.lifecycle.Lifecycle;
public final class CustomLifecycle extends Lifecycle {
    public int count;
    @Override
    public void restart() {
        count++;
    }
}

Binary file not shown.