restartStrategy = RestartStrategy.get(webAppClassLoader);
+ if (restartStrategy.isPresent()) {
+ restartStrategy.get().restart(new GuiceInjectionContext());
+ } else {
+ LOG.warn("restarting is not supported by the underlying platform");
+ }
}
}
- private class GuiceInjectionContext implements RestartStrategy.InjectionContext {
+ private class GuiceInjectionContext implements RestartStrategy.InternalInjectionContext {
@Override
public void initialize() {
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/CLibrary.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/CLibrary.java
new file mode 100644
index 0000000000..cee163eb8b
--- /dev/null
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/CLibrary.java
@@ -0,0 +1,45 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+/**
+ * Interface for native c library.
+ */
+@SuppressWarnings({
+ "squid:S1214", // usage as constant is common practice for jna
+ "squid:S1191" // use of sun.* classes is required for jna
+})
+interface CLibrary extends com.sun.jna.Library {
+ CLibrary LIBC = com.sun.jna.Native.load("c", CLibrary.class);
+
+ int F_GETFD = 1;
+ int F_SETFD = 2;
+ int FD_CLOEXEC = 1;
+
+ int getdtablesize();
+ int fcntl(int fd, int command);
+ int fcntl(int fd, int command, int flags);
+ int execvp(String file, com.sun.jna.StringArray args);
+ String strerror(int errno);
+}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/LoggingAdapter.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/DefaultRestarter.java
similarity index 56%
rename from scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/LoggingAdapter.java
rename to scm-webapp/src/main/java/sonia/scm/lifecycle/DefaultRestarter.java
index ec52672904..cb85852f83 100644
--- a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/LoggingAdapter.java
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/DefaultRestarter.java
@@ -21,48 +21,44 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
-package sonia.scm.lifecycle.classloading;
+package sonia.scm.lifecycle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
+import com.google.common.annotations.VisibleForTesting;
+import sonia.scm.event.ScmEventBus;
-/**
- * Logging adapter for {@link ClassLoaderLeakPreventor}.
- */
-public class LoggingAdapter implements se.jiderhamn.classloader.leak.prevention.Logger {
+import javax.inject.Inject;
+import javax.inject.Singleton;
- @SuppressWarnings("squid:S3416") // suppress "loggers should be named for their enclosing classes" rule
- private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderLeakPreventor.class);
+@Singleton
+public class DefaultRestarter implements Restarter {
- @Override
- public void debug(String msg) {
- LOG.debug(msg);
+ private ScmEventBus eventBus;
+ private RestartStrategy strategy;
+
+ @Inject
+ public DefaultRestarter() {
+ this(
+ ScmEventBus.getInstance(),
+ RestartStrategy.get(Thread.currentThread().getContextClassLoader()).orElse(null)
+ );
+ }
+
+ @VisibleForTesting
+ DefaultRestarter(ScmEventBus eventBus, RestartStrategy strategy) {
+ this.eventBus = eventBus;
+ this.strategy = strategy;
}
@Override
- public void info(String msg) {
- LOG.info(msg);
+ public boolean isSupported() {
+ return strategy != null;
}
@Override
- public void warn(String msg) {
- LOG.warn(msg);
- }
-
- @Override
- public void warn(Throwable t) {
- LOG.warn(t.getMessage(), t);
- }
-
- @Override
- public void error(String msg) {
- LOG.error(msg);
- }
-
- @Override
- public void error(Throwable t) {
- LOG.error(t.getMessage(), t);
+ public void restart(Class> cause, String reason) {
+ if (!isSupported()) {
+ throw new RestartNotSupportedException("restarting is not supported");
+ }
+ eventBus.post(new RestartEvent(cause, reason));
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/ExitRestartStrategy.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/ExitRestartStrategy.java
new file mode 100644
index 0000000000..04d58df731
--- /dev/null
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/ExitRestartStrategy.java
@@ -0,0 +1,77 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.function.IntConsumer;
+
+/**
+ * {@link RestartStrategy} which tears down the scm-manager context and
+ * then exists the java process with {@link System#exit(int)}.
+ *
+ * This is useful if an external mechanism is able to restart the process after it has exited.
+ */
+class ExitRestartStrategy extends RestartStrategy {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ExitRestartStrategy.class);
+
+ static final String NAME = "exit";
+
+ static final String PROPERTY_EXIT_CODE = "sonia.scm.restart.exit-code";
+
+ private IntConsumer exiter = System::exit;
+
+ private int exitCode;
+
+ ExitRestartStrategy() {
+ }
+
+ @VisibleForTesting
+ void setExiter(IntConsumer exiter) {
+ this.exiter = exiter;
+ }
+
+ @Override
+ public void prepareRestart(InjectionContext context) {
+ exitCode = determineExitCode();
+ }
+
+ @Override
+ protected void executeRestart(InjectionContext context) {
+ LOG.warn("exit scm-manager with exit code {}", exitCode);
+ exiter.accept(exitCode);
+ }
+
+ private int determineExitCode() {
+ String exitCodeAsString = System.getProperty(PROPERTY_EXIT_CODE, "0");
+ try {
+ return Integer.parseInt(exitCodeAsString);
+ } catch (NumberFormatException ex) {
+ throw new RestartNotSupportedException("invalid exit code " + exitCodeAsString, ex);
+ }
+ }
+}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/InjectionContextRestartStrategy.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/InjectionContextRestartStrategy.java
deleted file mode 100644
index 6c9b474d14..0000000000
--- a/scm-webapp/src/main/java/sonia/scm/lifecycle/InjectionContextRestartStrategy.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * MIT License
- *
- * Copyright (c) 2020-present Cloudogu GmbH and 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.
- */
-
-package sonia.scm.lifecycle;
-
-import com.google.common.annotations.VisibleForTesting;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import sonia.scm.event.RecreateEventBusEvent;
-import sonia.scm.event.ScmEventBus;
-import sonia.scm.event.ShutdownEventBusEvent;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * Restart strategy implementation which destroy the injection context and re initialize it.
- */
-public class InjectionContextRestartStrategy implements RestartStrategy {
-
- private static final String DISABLE_RESTART_PROPERTY = "sonia.scm.restart.disable";
- private static final String WAIT_PROPERTY = "sonia.scm.restart.wait";
- private static final String DISABLE_GC_PROPERTY = "sonia.scm.restart.disable-gc";
-
- private static final AtomicLong INSTANCE_COUNTER = new AtomicLong();
- private static final Logger LOG = LoggerFactory.getLogger(InjectionContextRestartStrategy.class);
-
- private boolean restartEnabled = !Boolean.getBoolean(DISABLE_RESTART_PROPERTY);
- private long waitInMs = Integer.getInteger(WAIT_PROPERTY, 250);
- private boolean gcEnabled = !Boolean.getBoolean(DISABLE_GC_PROPERTY);
-
- private final ClassLoader webAppClassLoader;
-
- InjectionContextRestartStrategy(ClassLoader webAppClassLoader) {
- this.webAppClassLoader = webAppClassLoader;
- }
-
- @VisibleForTesting
- void setWaitInMs(long waitInMs) {
- this.waitInMs = waitInMs;
- }
-
- @VisibleForTesting
- void setGcEnabled(boolean gcEnabled) {
- this.gcEnabled = gcEnabled;
- }
-
- @Override
- public void restart(InjectionContext context) {
- stop(context);
- if (restartEnabled) {
- start(context);
- } else {
- LOG.warn("restarting context is disabled");
- }
- }
-
- @SuppressWarnings("squid:S1215") // suppress explicit gc call warning
- private void start(InjectionContext context) {
- LOG.debug("use WebAppClassLoader as ContextClassLoader, to avoid ClassLoader leaks");
- Thread.currentThread().setContextClassLoader(webAppClassLoader);
-
- LOG.warn("send recreate eventbus event");
- ScmEventBus.getInstance().post(new RecreateEventBusEvent());
-
- // restart context delayed, to avoid timing problems
- new Thread(() -> {
- try {
- if (gcEnabled){
- LOG.info("call gc to clean up memory from old instances");
- System.gc();
- }
-
- LOG.info("wait {}ms before re starting the context", waitInMs);
- Thread.sleep(waitInMs);
-
- LOG.warn("reinitialize injection context");
- context.initialize();
-
- LOG.debug("register injection context on new eventbus");
- ScmEventBus.getInstance().register(context);
- } catch ( Exception ex) {
- LOG.error("failed to restart", ex);
- }
- }, "Delayed-Restart-" + INSTANCE_COUNTER.incrementAndGet()).start();
- }
-
- private void stop(InjectionContext context) {
- LOG.warn("destroy injection context");
- context.destroy();
-
- if (!restartEnabled) {
- // shutdown eventbus, but do this only if restart is disabled
- ScmEventBus.getInstance().post(new ShutdownEventBusEvent());
- }
- }
-}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/PosixRestartStrategy.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/PosixRestartStrategy.java
new file mode 100644
index 0000000000..852d4b5f60
--- /dev/null
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/PosixRestartStrategy.java
@@ -0,0 +1,72 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+import static sonia.scm.lifecycle.CLibrary.*;
+
+/**
+ * Restart strategy which uses execvp from libc. This strategy is only supported on posix base operating systems.
+ */
+class PosixRestartStrategy extends RestartStrategy {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PosixRestartStrategy.class);
+
+ PosixRestartStrategy() {
+ }
+
+ @Override
+ protected void executeRestart(InjectionContext context) {
+ LOG.warn("restart scm-manager jvm process");
+ try {
+ restart();
+ } catch (IOException e) {
+ LOG.error("failed to collect java vm arguments", e);
+ LOG.error("we will now exit the java process");
+ System.exit(1);
+ }
+ }
+
+ @SuppressWarnings("squid:S1191") // use of sun.* classes is required for jna)
+ private static void restart() throws IOException {
+ com.sun.akuma.JavaVMArguments args = com.sun.akuma.JavaVMArguments.current();
+ args.remove("--daemon");
+
+ int sz = LIBC.getdtablesize();
+ for(int i=3; i get(ClassLoader webAppClassLoader) {
+ return Optional.ofNullable(RestartStrategyFactory.create(webAppClassLoader));
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/RestartStrategyFactory.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/RestartStrategyFactory.java
new file mode 100644
index 0000000000..4520bb3ddf
--- /dev/null
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/RestartStrategyFactory.java
@@ -0,0 +1,98 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import com.google.common.base.Strings;
+import sonia.scm.PlatformType;
+import sonia.scm.util.SystemUtil;
+
+import java.lang.reflect.Constructor;
+
+final class RestartStrategyFactory {
+
+ /**
+ * System property to load a specific restart strategy.
+ */
+ static final String PROPERTY_STRATEGY = "sonia.scm.lifecycle.restart-strategy";
+
+ /**
+ * No restart supported.
+ */
+ static final String STRATEGY_NONE = "none";
+
+ private RestartStrategyFactory() {
+ }
+
+ /**
+ * Returns the configured strategy or {@code null} if restart is not supported.
+ *
+ * @param webAppClassLoader root webapp classloader
+ * @return configured strategy or {@code null}
+ */
+ static RestartStrategy create(ClassLoader webAppClassLoader) {
+ String property = System.getProperty(PROPERTY_STRATEGY);
+ if (Strings.isNullOrEmpty(property)) {
+ return forPlatform();
+ }
+ return fromProperty(webAppClassLoader, property);
+ }
+
+ private static RestartStrategy fromProperty(ClassLoader webAppClassLoader, String property) {
+ if (STRATEGY_NONE.equalsIgnoreCase(property)) {
+ return null;
+ } else if (ExitRestartStrategy.NAME.equalsIgnoreCase(property)) {
+ return new ExitRestartStrategy();
+ } else {
+ return fromClassName(property, webAppClassLoader);
+ }
+ }
+
+ private static RestartStrategy fromClassName(String className, ClassLoader classLoader) {
+ try {
+ Class extends RestartStrategy> rsClass = Class.forName(className).asSubclass(RestartStrategy.class);
+ return createInstance(rsClass, classLoader);
+ } catch (Exception e) {
+ throw new RestartNotSupportedException("failed to create restart strategy from property", e);
+ }
+ }
+
+ private static RestartStrategy createInstance(Class extends RestartStrategy> rsClass, ClassLoader classLoader) throws InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException, NoSuchMethodException {
+ try {
+ Constructor extends RestartStrategy> constructor = rsClass.getConstructor(ClassLoader.class);
+ return constructor.newInstance(classLoader);
+ } catch (NoSuchMethodException ex) {
+ return rsClass.getConstructor().newInstance();
+ }
+ }
+
+ private static RestartStrategy forPlatform() {
+ // we do not use SystemUtil here, to allow testing
+ String osName = System.getProperty(SystemUtil.PROPERTY_OSNAME);
+ PlatformType platform = PlatformType.createPlatformType(osName);
+ if (platform.isPosix()) {
+ return new PosixRestartStrategy();
+ }
+ return null;
+ }
+}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycle.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycle.java
index 8f5bcaeccc..e9c739e22f 100644
--- a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycle.java
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycle.java
@@ -21,10 +21,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.lifecycle.classloading;
-import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.lifecycle.LifeCycle;
@@ -42,18 +41,10 @@ public abstract class ClassLoaderLifeCycle implements LifeCycle {
private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderLifeCycle.class);
- @VisibleForTesting
- static final String PROPERTY = "sonia.scm.classloading.lifecycle";
-
public static ClassLoaderLifeCycle create() {
ClassLoader webappClassLoader = Thread.currentThread().getContextClassLoader();
- String implementation = System.getProperty(PROPERTY);
- if (SimpleClassLoaderLifeCycle.NAME.equalsIgnoreCase(implementation)) {
- LOG.info("create new simple ClassLoaderLifeCycle");
- return new SimpleClassLoaderLifeCycle(webappClassLoader);
- }
- LOG.info("create new ClassLoaderLifeCycle with leak prevention");
- return new ClassLoaderLifeCycleWithLeakPrevention(webappClassLoader);
+ LOG.info("create new simple ClassLoaderLifeCycle");
+ return new SimpleClassLoaderLifeCycle(webappClassLoader);
}
private final ClassLoader webappClassLoader;
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPrevention.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPrevention.java
deleted file mode 100644
index 2f83d2278a..0000000000
--- a/scm-webapp/src/main/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPrevention.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * MIT License
- *
- * Copyright (c) 2020-present Cloudogu GmbH and 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.
- */
-
-package sonia.scm.lifecycle.classloading;
-
-import com.google.common.annotations.VisibleForTesting;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
-import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventorFactory;
-import se.jiderhamn.classloader.leak.prevention.cleanup.IIOServiceProviderCleanUp;
-import se.jiderhamn.classloader.leak.prevention.cleanup.MBeanCleanUp;
-import se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp;
-import se.jiderhamn.classloader.leak.prevention.cleanup.StopThreadsCleanUp;
-import se.jiderhamn.classloader.leak.prevention.preinit.AwtToolkitInitiator;
-import se.jiderhamn.classloader.leak.prevention.preinit.Java2dDisposerInitiator;
-import se.jiderhamn.classloader.leak.prevention.preinit.Java2dRenderQueueInitiator;
-import se.jiderhamn.classloader.leak.prevention.preinit.SunAwtAppContextInitiator;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.ArrayDeque;
-import java.util.Deque;
-
-import static se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp.SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
-
-/**
- * Creates and shutdown SCM-Manager ClassLoaders with ClassLoader leak detection.
- */
-final class ClassLoaderLifeCycleWithLeakPrevention extends ClassLoaderLifeCycle {
-
- private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderLifeCycleWithLeakPrevention.class);
-
- private Deque classLoaders = new ArrayDeque<>();
-
- private final ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory;
-
- private ClassLoaderAppendListener classLoaderAppendListener = new ClassLoaderAppendListener() {
- @Override
- public C apply(C classLoader) {
- return classLoader;
- }
- };
-
- ClassLoaderLifeCycleWithLeakPrevention(ClassLoader webappClassLoader) {
- this(webappClassLoader, createClassLoaderLeakPreventorFactory(webappClassLoader));
- }
-
- ClassLoaderLifeCycleWithLeakPrevention(ClassLoader webappClassLoader, ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory) {
- super(webappClassLoader);
- this.classLoaderLeakPreventorFactory = classLoaderLeakPreventorFactory;
- }
-
- private static ClassLoaderLeakPreventorFactory createClassLoaderLeakPreventorFactory(ClassLoader webappClassLoader) {
- // Should threads tied to the web app classloader be forced to stop at application shutdown?
- boolean stopThreads = Boolean.getBoolean("ClassLoaderLeakPreventor.stopThreads");
-
- // Should Timer threads tied to the web app classloader be forced to stop at application shutdown?
- boolean stopTimerThreads = Boolean.getBoolean("ClassLoaderLeakPreventor.stopTimerThreads");
-
- // Should shutdown hooks registered from the application be executed at application shutdown?
- boolean executeShutdownHooks = Boolean.getBoolean("ClassLoaderLeakPreventor.executeShutdownHooks");
-
- // No of milliseconds to wait for threads to finish execution, before stopping them.
- int threadWaitMs = Integer.getInteger("ClassLoaderLeakPreventor.threadWaitMs", ClassLoaderLeakPreventor.THREAD_WAIT_MS_DEFAULT);
-
- /*
- * No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
- * If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
- */
- int shutdownHookWaitMs = Integer.getInteger("ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
-
- LOG.info("Settings for {} (CL: 0x{}):", ClassLoaderLifeCycleWithLeakPrevention.class.getName(), Integer.toHexString(System.identityHashCode(webappClassLoader)) );
- LOG.info(" stopThreads = {}", stopThreads);
- LOG.info(" stopTimerThreads = {}", stopTimerThreads);
- LOG.info(" executeShutdownHooks = {}", executeShutdownHooks);
- LOG.info(" threadWaitMs = {} ms", threadWaitMs);
- LOG.info(" shutdownHookWaitMs = {} ms", shutdownHookWaitMs);
-
- // use webapp classloader as safe base? or system?
- ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory = new ClassLoaderLeakPreventorFactory(webappClassLoader);
- classLoaderLeakPreventorFactory.setLogger(new LoggingAdapter());
-
- final ShutdownHookCleanUp shutdownHookCleanUp = classLoaderLeakPreventorFactory.getCleanUp(ShutdownHookCleanUp.class);
- shutdownHookCleanUp.setExecuteShutdownHooks(executeShutdownHooks);
- shutdownHookCleanUp.setShutdownHookWaitMs(shutdownHookWaitMs);
-
- final StopThreadsCleanUp stopThreadsCleanUp = classLoaderLeakPreventorFactory.getCleanUp(StopThreadsCleanUp.class);
- stopThreadsCleanUp.setStopThreads(stopThreads);
- stopThreadsCleanUp.setStopTimerThreads(stopTimerThreads);
- stopThreadsCleanUp.setThreadWaitMs(threadWaitMs);
-
- // remove awt and imageio cleanup
- classLoaderLeakPreventorFactory.removePreInitiator(AwtToolkitInitiator.class);
- classLoaderLeakPreventorFactory.removePreInitiator(SunAwtAppContextInitiator.class);
- classLoaderLeakPreventorFactory.removeCleanUp(IIOServiceProviderCleanUp.class);
- classLoaderLeakPreventorFactory.removePreInitiator(Java2dRenderQueueInitiator.class);
- classLoaderLeakPreventorFactory.removePreInitiator(Java2dDisposerInitiator.class);
-
- // the MBeanCleanUp causes a Exception and we use no mbeans
- classLoaderLeakPreventorFactory.removeCleanUp(MBeanCleanUp.class);
-
- return classLoaderLeakPreventorFactory;
- }
-
- @VisibleForTesting
- void setClassLoaderAppendListener(ClassLoaderAppendListener classLoaderAppendListener) {
- this.classLoaderAppendListener = classLoaderAppendListener;
- }
-
- @Override
- protected void shutdownClassLoaders() {
- ClassLoaderAndPreventor clap = classLoaders.poll();
- while (clap != null) {
- clap.shutdown();
- clap = classLoaders.poll();
- }
- // be sure it is realy empty
- classLoaders.clear();
- classLoaders = new ArrayDeque<>();
- }
-
- @Override
- protected T initAndAppend(T originalClassLoader) {
- LOG.debug("init classloader {}", originalClassLoader);
- T classLoader = classLoaderAppendListener.apply(originalClassLoader);
-
- ClassLoaderLeakPreventor preventor = classLoaderLeakPreventorFactory.newLeakPreventor(classLoader);
- preventor.runPreClassLoaderInitiators();
- classLoaders.push(new ClassLoaderAndPreventor(classLoader, preventor));
-
- return classLoader;
- }
-
- interface ClassLoaderAppendListener {
- C apply(C classLoader);
- }
-
- private static class ClassLoaderAndPreventor {
-
- private final ClassLoader classLoader;
- private final ClassLoaderLeakPreventor preventor;
-
- private ClassLoaderAndPreventor(ClassLoader classLoader, ClassLoaderLeakPreventor preventor) {
- this.classLoader = classLoader;
- this.preventor = preventor;
- }
-
- void shutdown() {
- LOG.debug("shutdown classloader {}", classLoader);
- preventor.runCleanUps();
- close();
- }
-
- private void close() {
- if (classLoader instanceof Closeable) {
- LOG.trace("close classloader {}", classLoader);
- try {
- ((Closeable) classLoader).close();
- } catch (IOException e) {
- LOG.warn("failed to close classloader", e);
- }
- }
- }
- }
-}
diff --git a/scm-webapp/src/main/java/sonia/scm/lifecycle/modules/BootstrapModule.java b/scm-webapp/src/main/java/sonia/scm/lifecycle/modules/BootstrapModule.java
index 618d3a05d8..8a112c2e94 100644
--- a/scm-webapp/src/main/java/sonia/scm/lifecycle/modules/BootstrapModule.java
+++ b/scm-webapp/src/main/java/sonia/scm/lifecycle/modules/BootstrapModule.java
@@ -33,6 +33,8 @@ import sonia.scm.SCMContext;
import sonia.scm.SCMContextProvider;
import sonia.scm.io.DefaultFileSystem;
import sonia.scm.io.FileSystem;
+import sonia.scm.lifecycle.DefaultRestarter;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.plugin.PluginLoader;
import sonia.scm.repository.RepositoryLocationResolver;
import sonia.scm.repository.xml.MetadataStore;
@@ -85,6 +87,8 @@ public class BootstrapModule extends AbstractModule {
bind(FileSystem.class, DefaultFileSystem.class);
+ bind(Restarter.class, DefaultRestarter.class);
+
// note CipherUtil uses an other generator
bind(CipherHandler.class).toInstance(CipherUtil.getInstance().getCipherHandler());
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginManager.java b/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginManager.java
index a24d41e0f6..ba41ada287 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginManager.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/DefaultPluginManager.java
@@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory;
import sonia.scm.NotFoundException;
import sonia.scm.event.ScmEventBus;
import sonia.scm.lifecycle.RestartEvent;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.version.Version;
import javax.inject.Inject;
@@ -59,20 +60,21 @@ public class DefaultPluginManager implements PluginManager {
private static final Logger LOG = LoggerFactory.getLogger(DefaultPluginManager.class);
- private final ScmEventBus eventBus;
private final PluginLoader loader;
private final PluginCenter center;
private final PluginInstaller installer;
+ private final Restarter restarter;
+
private final Collection pendingInstallQueue = new ArrayList<>();
private final Collection pendingUninstallQueue = new ArrayList<>();
private final PluginDependencyTracker dependencyTracker = new PluginDependencyTracker();
@Inject
- public DefaultPluginManager(ScmEventBus eventBus, PluginLoader loader, PluginCenter center, PluginInstaller installer) {
- this.eventBus = eventBus;
+ public DefaultPluginManager(PluginLoader loader, PluginCenter center, PluginInstaller installer, Restarter restarter) {
this.loader = loader;
this.center = center;
this.installer = installer;
+ this.restarter = restarter;
this.computeInstallationDependencies();
}
@@ -233,16 +235,8 @@ public class DefaultPluginManager implements PluginManager {
}
}
- @VisibleForTesting
- void triggerRestart(String cause) {
- new Thread(() -> {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- eventBus.post(new RestartEvent(PluginManager.class, cause));
- }).start();
+ private void triggerRestart(String cause) {
+ restarter.restart(PluginManager.class, cause);
}
private void cancelPending(List pendingInstallations) {
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/PluginChecksumMismatchException.java b/scm-webapp/src/main/java/sonia/scm/plugin/PluginChecksumMismatchException.java
index 0cdb3c6b2c..af419fa297 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/PluginChecksumMismatchException.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/PluginChecksumMismatchException.java
@@ -21,11 +21,21 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.plugin;
+import static sonia.scm.ContextEntry.ContextBuilder.entity;
+
public class PluginChecksumMismatchException extends PluginInstallException {
- public PluginChecksumMismatchException(String message) {
- super(message);
+ public PluginChecksumMismatchException(AvailablePlugin plugin, String calculatedChecksum, String expectedChecksum) {
+ super(
+ entity("Plugin", plugin.getDescriptor().getInformation().getName()).build(),
+ String.format("downloaded plugin checksum %s does not match expected %s", calculatedChecksum, expectedChecksum)
+ );
+ }
+
+ @Override
+ public String getCode() {
+ return "6mRuFxaWM1";
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/PluginCleanupException.java b/scm-webapp/src/main/java/sonia/scm/plugin/PluginCleanupException.java
new file mode 100644
index 0000000000..82c4d94b66
--- /dev/null
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/PluginCleanupException.java
@@ -0,0 +1,40 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+
+package sonia.scm.plugin;
+
+import java.nio.file.Path;
+
+import static sonia.scm.ContextEntry.ContextBuilder.entity;
+
+public class PluginCleanupException extends PluginInstallException {
+ public PluginCleanupException(Path file) {
+ super(entity("File", file.toString()).build(), "failed to cleanup, after broken installation");
+ }
+
+ @Override
+ public String getCode() {
+ return "8nRuFzjss1";
+ }
+}
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/PluginDownloadException.java b/scm-webapp/src/main/java/sonia/scm/plugin/PluginDownloadException.java
index 75dfc78b40..b67a766ed2 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/PluginDownloadException.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/PluginDownloadException.java
@@ -21,11 +21,18 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.plugin;
+import static sonia.scm.ContextEntry.ContextBuilder.entity;
+
public class PluginDownloadException extends PluginInstallException {
- public PluginDownloadException(String message, Throwable cause) {
- super(message, cause);
+ public PluginDownloadException(AvailablePlugin plugin, Exception cause) {
+ super(entity("Plugin", plugin.getDescriptor().getInformation().getName()).build(), "failed to download plugin", cause);
+ }
+
+ @Override
+ public String getCode() {
+ return "9iRuFz1UB1";
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstallException.java b/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstallException.java
index e5d1d0d2a2..b70f668b37 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstallException.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstallException.java
@@ -21,16 +21,21 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.plugin;
-public class PluginInstallException extends RuntimeException {
+import sonia.scm.ContextEntry;
+import sonia.scm.ExceptionWithContext;
- public PluginInstallException(String message) {
- super(message);
+import java.util.List;
+
+abstract class PluginInstallException extends ExceptionWithContext {
+
+ public PluginInstallException(List context, String message) {
+ super(context, message);
}
- public PluginInstallException(String message, Throwable cause) {
- super(message, cause);
+ public PluginInstallException(List context, String message, Exception cause) {
+ super(context, message, cause);
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstaller.java b/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstaller.java
index 0649d161e1..1ca34c5166 100644
--- a/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstaller.java
+++ b/scm-webapp/src/main/java/sonia/scm/plugin/PluginInstaller.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.plugin;
import com.google.common.hash.HashCode;
@@ -64,7 +64,7 @@ class PluginInstaller {
return new PendingPluginInstallation(plugin.install(), file);
} catch (IOException ex) {
cleanup(file);
- throw new PluginDownloadException("failed to download plugin", ex);
+ throw new PluginDownloadException(plugin, ex);
}
}
@@ -74,7 +74,7 @@ class PluginInstaller {
Files.deleteIfExists(file);
}
} catch (IOException e) {
- throw new PluginInstallException("failed to cleanup, after broken installation");
+ throw new PluginCleanupException(file);
}
}
@@ -84,9 +84,7 @@ class PluginInstaller {
String calculatedChecksum = hash.toString();
if (!checksum.get().equalsIgnoreCase(calculatedChecksum)) {
cleanup(file);
- throw new PluginChecksumMismatchException(
- String.format("downloaded plugin checksum %s does not match expected %s", calculatedChecksum, checksum.get())
- );
+ throw new PluginChecksumMismatchException(plugin, calculatedChecksum, checksum.get());
}
}
}
diff --git a/scm-webapp/src/main/java/sonia/scm/update/MigrationWizardServlet.java b/scm-webapp/src/main/java/sonia/scm/update/MigrationWizardServlet.java
index 949c6a2bd9..99833c57cc 100644
--- a/scm-webapp/src/main/java/sonia/scm/update/MigrationWizardServlet.java
+++ b/scm-webapp/src/main/java/sonia/scm/update/MigrationWizardServlet.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.update;
import com.github.mustachejava.DefaultMustacheFactory;
@@ -36,6 +36,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.event.ScmEventBus;
import sonia.scm.lifecycle.RestartEvent;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.update.repository.DefaultMigrationStrategyDAO;
import sonia.scm.update.repository.MigrationStrategy;
import sonia.scm.update.repository.V1Repository;
@@ -65,11 +66,13 @@ class MigrationWizardServlet extends HttpServlet {
private final XmlRepositoryV1UpdateStep repositoryV1UpdateStep;
private final DefaultMigrationStrategyDAO migrationStrategyDao;
+ private final Restarter restarter;
@Inject
- MigrationWizardServlet(XmlRepositoryV1UpdateStep repositoryV1UpdateStep, DefaultMigrationStrategyDAO migrationStrategyDao) {
+ MigrationWizardServlet(XmlRepositoryV1UpdateStep repositoryV1UpdateStep, DefaultMigrationStrategyDAO migrationStrategyDao, Restarter restarter) {
this.repositoryV1UpdateStep = repositoryV1UpdateStep;
this.migrationStrategyDao = migrationStrategyDao;
+ this.restarter = restarter;
}
@Override
@@ -140,12 +143,16 @@ class MigrationWizardServlet extends HttpServlet {
);
Map model = Collections.singletonMap("contextPath", req.getContextPath());
-
- respondWithTemplate(resp, model, "templates/repository-migration-restart.mustache");
-
ThreadContext.bind(new Subject.Builder(new DefaultSecurityManager()).authenticated(false).buildSubject());
- ScmEventBus.getInstance().post(new RestartEvent(MigrationWizardServlet.class, "wrote migration data"));
+ if (restarter.isSupported()) {
+ respondWithTemplate(resp, model, "templates/repository-migration-restart.mustache");
+ restarter.restart(MigrationWizardServlet.class, "wrote migration data");
+ } else {
+ respondWithTemplate(resp, model, "templates/repository-migration-manual-restart.mustache");
+ LOG.error("Restarting is not supported on this platform.");
+ LOG.error("Please do a manual restart");
+ }
}
private List getRepositoryLineEntries() {
diff --git a/scm-webapp/src/main/resources/locales/de/plugins.json b/scm-webapp/src/main/resources/locales/de/plugins.json
index 809da9d0df..8c5c88e0f8 100644
--- a/scm-webapp/src/main/resources/locales/de/plugins.json
+++ b/scm-webapp/src/main/resources/locales/de/plugins.json
@@ -203,6 +203,18 @@
"4GRrgkSC01": {
"displayName": "Unerwartetes Merge-Ergebnis",
"description": "Der Merge hatte ein unerwartetes Ergebis, das nicht automatisiert behandelt werden konnte. Nähere Details sind im Log zu finden. Führen Sie den Merge ggf. manuell durch."
+ },
+ "6mRuFxaWM1": {
+ "displayName": "Falsche Checksumme",
+ "description": "Die Checksumme des heruntergeladenen Plugins stimmt nicht mit der erwarteten Checksumme überein. Bitte versuchen Sie es erneut und prüfen Sie die Interneteinstellungen wie z. B. die Proxy-Einstellungen."
+ },
+ "9iRuFz1UB1": {
+ "displayName": "Fehler beim Herunterladen",
+ "description": "Das Plugin konnte nicht vom Server heruntergeladen werden. BitteThe plugin could not be loaded from the server. Bitte versuchen Sie es erneut und prüfen Sie die Interneteinstellungen wie z. B. die Proxy-Einstellungen. Weitere Details finden sich im Server Log."
+ },
+ "8nRuFzjss1": {
+ "displayName": "Fehler beim Löschen falscher Downloads",
+ "description": "Ein fehlerhaft heruntergeladenes Plugin konnte nicht gelöscht werden. Bitte prüfen Sie die Server Logs und löschen die Datei manuell."
}
},
"namespaceStrategies": {
diff --git a/scm-webapp/src/main/resources/locales/en/plugins.json b/scm-webapp/src/main/resources/locales/en/plugins.json
index 69e8d057ee..998e796bac 100644
--- a/scm-webapp/src/main/resources/locales/en/plugins.json
+++ b/scm-webapp/src/main/resources/locales/en/plugins.json
@@ -203,6 +203,18 @@
"4GRrgkSC01": {
"displayName": "Unexpected merge result",
"description": "The merge led to an unexpected result, that could not be handled automatically. More details could be found in the log. Please merge the branches manually."
+ },
+ "6mRuFxaWM1": {
+ "displayName": "Wrong checksum",
+ "description": "The checksum of the downloaded plugin did not match the expected checksum. Please try again or check the internet settings like proxies."
+ },
+ "9iRuFz1UB1": {
+ "displayName": "Could not load plugin",
+ "description": "The plugin could not be loaded from the server. Please try again or check the internet settings like proxies. More information can be found in the server log."
+ },
+ "8nRuFzjss1": {
+ "displayName": "Error while cleaning up failed plugin",
+ "description": "A failed plugin download could not be removed correctly. Please check the server log and remove the plugin manually."
}
},
"namespaceStrategies": {
diff --git a/scm-webapp/src/main/resources/templates/repository-migration-manual-restart.mustache b/scm-webapp/src/main/resources/templates/repository-migration-manual-restart.mustache
new file mode 100644
index 0000000000..46d65fa86b
--- /dev/null
+++ b/scm-webapp/src/main/resources/templates/repository-migration-manual-restart.mustache
@@ -0,0 +1,12 @@
+{{
+ The migration is prepared and gets executed after SCM-Manager is restarted.
+ Please restart your SCM-Manager instance.
+
+ {{/content}}
+
+{{/layout}}
diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ConfigResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ConfigResourceTest.java
index cbf4f61570..6f3803bbfd 100644
--- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ConfigResourceTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ConfigResourceTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.api.v2.resources;
import com.github.sdorra.shiro.ShiroRule;
@@ -89,6 +89,7 @@ public class ConfigResourceTest {
initMocks(this);
ConfigResource configResource = new ConfigResource(dtoToConfigMapper, configToDtoMapper, createConfiguration(), namespaceStrategyValidator);
+ configResource.setStore(config -> {});
dispatcher.addSingletonResource(configResource);
}
@@ -128,7 +129,9 @@ public class ConfigResourceTest {
request = MockHttpRequest.get("/" + ConfigResource.CONFIG_PATH_V2);
response = new MockHttpResponse();
- dispatcher.invoke(request, response); assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+ dispatcher.invoke(request, response);
+
+ assertEquals(HttpServletResponse.SC_OK, response.getStatus());
assertTrue(response.getContentAsString().contains("\"proxyPassword\":\"newPassword\""));
assertTrue(response.getContentAsString().contains("\"self\":{\"href\":\"/v2/config"));
assertTrue("link not found", response.getContentAsString().contains("\"update\":{\"href\":\"/v2/config"));
@@ -146,8 +149,6 @@ public class ConfigResourceTest {
assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
}
-
-
@Test
@SubjectAware(username = "readWrite")
public void shouldValidateNamespaceStrategy() throws URISyntaxException {
diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PendingPluginResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PendingPluginResourceTest.java
index a4e43d1da7..2f545761b7 100644
--- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PendingPluginResourceTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PendingPluginResourceTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.api.v2.resources;
import com.google.inject.util.Providers;
@@ -38,6 +38,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.plugin.AvailablePlugin;
import sonia.scm.plugin.AvailablePluginDescriptor;
import sonia.scm.plugin.InstalledPlugin;
@@ -66,10 +67,15 @@ class PendingPluginResourceTest {
private RestDispatcher dispatcher = new RestDispatcher();
+ @SuppressWarnings("unused")
ResourceLinks resourceLinks = ResourceLinksMock.createMock(create("/"));
@Mock
PluginManager pluginManager;
+
+ @Mock
+ Restarter restarter;
+
@Mock
PluginDtoMapper mapper;
@@ -109,6 +115,7 @@ class PendingPluginResourceTest {
void bindSubject() {
ThreadContext.bind(subject);
lenient().when(subject.isPermitted("plugin:manage")).thenReturn(true);
+ lenient().when(restarter.isSupported()).thenReturn(true);
}
@AfterEach
@@ -176,6 +183,23 @@ class PendingPluginResourceTest {
assertThat(response.getContentAsString()).contains("\"execute\":{\"href\":\"/v2/plugins/pending/execute\"}");
}
+ @Test
+ void shouldNotReturnExecuteLinkIfRestartIsNotSupported() throws URISyntaxException, UnsupportedEncodingException {
+ when(restarter.isSupported()).thenReturn(false);
+
+ when(pluginManager.getAvailable()).thenReturn(emptyList());
+ InstalledPlugin installedPlugin = createInstalledPlugin("uninstalled-plugin");
+ when(installedPlugin.isMarkedForUninstall()).thenReturn(true);
+ when(pluginManager.getInstalled()).thenReturn(singletonList(installedPlugin));
+
+ MockHttpRequest request = MockHttpRequest.get("/v2/plugins/pending");
+ dispatcher.invoke(request, response);
+
+ assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
+ assertThat(response.getContentAsString()).contains("\"uninstall\":[{\"name\":\"uninstalled-plugin\"");
+ assertThat(response.getContentAsString()).doesNotContain("\"execute\"");
+ }
+
@Test
void shouldExecutePendingPlugins() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.post("/v2/plugins/pending/execute");
diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoCollectionMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoCollectionMapperTest.java
index 0029296882..a3fa801a22 100644
--- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoCollectionMapperTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoCollectionMapperTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.api.v2.resources;
import de.otto.edison.hal.HalRepresentation;
@@ -36,6 +36,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.plugin.AvailablePlugin;
import sonia.scm.plugin.AvailablePluginDescriptor;
import sonia.scm.plugin.InstalledPlugin;
@@ -59,6 +60,9 @@ class PluginDtoCollectionMapperTest {
ResourceLinks resourceLinks = ResourceLinksMock.createMock(URI.create("/"));
+ @Mock
+ private Restarter restarter;
+
@InjectMocks
PluginDtoMapperImpl pluginDtoMapper;
@@ -142,7 +146,7 @@ class PluginDtoCollectionMapperTest {
}
@Test
- void shouldAddInstallLinkForNewVersionWhenPermitted() {
+ void shouldAddUpdateLinkForNewVersionWhenPermitted() {
when(subject.isPermitted("plugin:manage")).thenReturn(true);
PluginDtoCollectionMapper mapper = new PluginDtoCollectionMapper(resourceLinks, pluginDtoMapper, manager);
@@ -154,6 +158,21 @@ class PluginDtoCollectionMapperTest {
assertThat(plugin.getLinks().getLinkBy("update")).isNotEmpty();
}
+ @Test
+ void shouldAddUpdateWithRestartLinkForNewVersionWhenPermitted() {
+ when(restarter.isSupported()).thenReturn(true);
+ when(subject.isPermitted("plugin:manage")).thenReturn(true);
+ PluginDtoCollectionMapper mapper = new PluginDtoCollectionMapper(resourceLinks, pluginDtoMapper, manager);
+
+ HalRepresentation result = mapper.mapInstalled(
+ singletonList(createInstalledPlugin("scm-some-plugin", "1")),
+ singletonList(createAvailablePlugin("scm-some-plugin", "2")));
+
+ PluginDto plugin = getPluginDtoFromResult(result);
+ assertThat(plugin.getLinks().getLinkBy("update")).isNotEmpty();
+ assertThat(plugin.getLinks().getLinkBy("updateWithRestart")).isNotEmpty();
+ }
+
@Test
void shouldSetInstalledPluginPendingWhenCorrespondingAvailablePluginIsPending() {
when(subject.isPermitted("plugin:manage")).thenReturn(true);
diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoMapperTest.java
index c4ccbe521d..51a7001140 100644
--- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoMapperTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/PluginDtoMapperTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.api.v2.resources;
import com.google.common.collect.ImmutableSet;
@@ -35,6 +35,7 @@ import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.plugin.AvailablePlugin;
import sonia.scm.plugin.AvailablePluginDescriptor;
import sonia.scm.plugin.InstalledPlugin;
@@ -56,6 +57,9 @@ class PluginDtoMapperTest {
@SuppressWarnings("unused") // Is injected
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(URI.create("https://hitchhiker.com/"));
+ @Mock
+ private Restarter restarter;
+
@InjectMocks
private PluginDtoMapperImpl mapper;
@@ -122,6 +126,7 @@ class PluginDtoMapperTest {
PluginDto dto = mapper.mapAvailable(plugin);
assertThat(dto.getLinks().getLinkBy("install")).isEmpty();
+ assertThat(dto.getLinks().getLinkBy("installWithRestart")).isEmpty();
}
@Test
@@ -134,6 +139,17 @@ class PluginDtoMapperTest {
.isEqualTo("https://hitchhiker.com/v2/plugins/available/scm-cas-plugin/install");
}
+ @Test
+ void shouldAppendInstallWithRestartLink() {
+ when(restarter.isSupported()).thenReturn(true);
+ when(subject.isPermitted("plugin:manage")).thenReturn(true);
+ AvailablePlugin plugin = createAvailable(createPluginInformation());
+
+ PluginDto dto = mapper.mapAvailable(plugin);
+ assertThat(dto.getLinks().getLinkBy("installWithRestart").get().getHref())
+ .isEqualTo("https://hitchhiker.com/v2/plugins/available/scm-cas-plugin/install?restart=true");
+ }
+
@Test
void shouldReturnMiscellaneousIfCategoryIsNull() {
PluginInformation information = createPluginInformation();
@@ -162,4 +178,17 @@ class PluginDtoMapperTest {
assertThat(dto.getLinks().getLinkBy("uninstall").get().getHref())
.isEqualTo("https://hitchhiker.com/v2/plugins/installed/scm-cas-plugin/uninstall");
}
+
+ @Test
+ void shouldAppendUninstallWithRestartLink() {
+ when(restarter.isSupported()).thenReturn(true);
+ when(subject.isPermitted("plugin:manage")).thenReturn(true);
+
+ InstalledPlugin plugin = createInstalled(createPluginInformation());
+ when(plugin.isUninstallable()).thenReturn(true);
+
+ PluginDto dto = mapper.mapInstalled(plugin, emptyList());
+ assertThat(dto.getLinks().getLinkBy("uninstallWithRestart").get().getHref())
+ .isEqualTo("https://hitchhiker.com/v2/plugins/installed/scm-cas-plugin/uninstall?restart=true");
+ }
}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/DefaultRestarterTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/DefaultRestarterTest.java
new file mode 100644
index 0000000000..a137d7a947
--- /dev/null
+++ b/scm-webapp/src/test/java/sonia/scm/lifecycle/DefaultRestarterTest.java
@@ -0,0 +1,92 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import com.github.legman.Subscribe;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import sonia.scm.event.ScmEventBus;
+
+import javax.swing.*;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.verify;
+
+@ExtendWith(MockitoExtension.class)
+class DefaultRestarterTest {
+
+ @Mock
+ private ScmEventBus eventBus;
+
+ @Captor
+ private ArgumentCaptor eventCaptor;
+
+ @Test
+ void shouldLoadStrategyOnCreation() {
+ System.setProperty(RestartStrategyFactory.PROPERTY_STRATEGY, ExitRestartStrategy.NAME);
+ try {
+ DefaultRestarter restarter = new DefaultRestarter();
+ assertThat(restarter.isSupported()).isTrue();
+ } finally {
+ System.clearProperty(RestartStrategyFactory.PROPERTY_STRATEGY);
+ }
+ }
+
+ @Test
+ void shouldReturnFalseIfRestartStrategyIsNotAvailable() {
+ DefaultRestarter restarter = new DefaultRestarter(eventBus, null);
+ assertThat(restarter.isSupported()).isFalse();
+ }
+
+ @Test
+ void shouldReturnTrueIfRestartStrategyIsAvailable() {
+ DefaultRestarter restarter = new DefaultRestarter();
+ assertThat(restarter.isSupported()).isTrue();
+ }
+
+ @Test
+ void shouldThrowRestartNotSupportedException() {
+ DefaultRestarter restarter = new DefaultRestarter(eventBus,null);
+ assertThrows(
+ RestartNotSupportedException.class, () -> restarter.restart(DefaultRestarterTest.class, "test")
+ );
+ }
+
+ @Test
+ void shouldFireRestartEvent() {
+ DefaultRestarter restarter = new DefaultRestarter(eventBus, new ExitRestartStrategy());
+ restarter.restart(DefaultRestarterTest.class, "testing");
+
+ verify(eventBus).post(eventCaptor.capture());
+
+ RestartEvent event = eventCaptor.getValue();
+ assertThat(event.getCause()).isEqualTo(DefaultRestarterTest.class);
+ assertThat(event.getReason()).isEqualTo("testing");
+ }
+}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/ExitRestartStrategyTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/ExitRestartStrategyTest.java
new file mode 100644
index 0000000000..766fa3bb64
--- /dev/null
+++ b/scm-webapp/src/test/java/sonia/scm/lifecycle/ExitRestartStrategyTest.java
@@ -0,0 +1,98 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.function.IntConsumer;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.verify;
+
+@ExtendWith(MockitoExtension.class)
+class ExitRestartStrategyTest {
+
+ @Mock
+ private RestartStrategy.InternalInjectionContext context;
+
+ private ExitRestartStrategy strategy;
+ private CapturingExiter exiter;
+
+ @BeforeEach
+ void setUpStrategy() {
+ strategy = new ExitRestartStrategy();
+ exiter = new CapturingExiter();
+ strategy.setExiter(exiter);
+ }
+
+ @Test
+ void shouldTearDownContextAndThenExit() {
+ strategy.restart(context);
+
+ verify(context).destroy();
+ assertThat(exiter.getExitCode()).isEqualTo(0);
+ }
+
+ @Test
+ void shouldUseExitCodeFromSystemProperty() {
+ System.setProperty(ExitRestartStrategy.PROPERTY_EXIT_CODE, "42");
+ try {
+ strategy.restart(context);
+
+ verify(context).destroy();
+ assertThat(exiter.getExitCode()).isEqualTo(42);
+ } finally {
+ System.clearProperty(ExitRestartStrategy.PROPERTY_EXIT_CODE);
+ }
+ }
+
+ @Test
+ void shouldThrowExceptionForNonNumericExitCode() {
+ System.setProperty(ExitRestartStrategy.PROPERTY_EXIT_CODE, "xyz");
+ try {
+ assertThrows(RestartNotSupportedException.class, () -> strategy.restart(context));
+ } finally {
+ System.clearProperty(ExitRestartStrategy.PROPERTY_EXIT_CODE);
+ }
+ }
+
+ private static class CapturingExiter implements IntConsumer {
+
+ private int exitCode = -1;
+
+ public int getExitCode() {
+ return exitCode;
+ }
+
+ @Override
+ public void accept(int exitCode) {
+ this.exitCode = exitCode;
+ }
+ }
+}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/InjectionContextRestartStrategyTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/InjectionContextRestartStrategyTest.java
deleted file mode 100644
index 100e0e9031..0000000000
--- a/scm-webapp/src/test/java/sonia/scm/lifecycle/InjectionContextRestartStrategyTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * MIT License
- *
- * Copyright (c) 2020-present Cloudogu GmbH and 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.
- */
-
-package sonia.scm.lifecycle;
-
-import com.github.legman.Subscribe;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-import sonia.scm.event.RecreateEventBusEvent;
-import sonia.scm.event.ScmEventBus;
-
-import java.util.concurrent.TimeUnit;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.awaitility.Awaitility.await;
-import static org.mockito.Mockito.verify;
-
-@ExtendWith(MockitoExtension.class)
-class InjectionContextRestartStrategyTest {
-
- @Mock
- private RestartStrategy.InjectionContext context;
-
- private InjectionContextRestartStrategy strategy = new InjectionContextRestartStrategy(Thread.currentThread().getContextClassLoader());
-
- @BeforeEach
- void setWaitToZero() {
- strategy.setWaitInMs(0L);
- // disable gc during tests
- strategy.setGcEnabled(false);
- }
-
- @Test
- void shouldCallDestroyAndInitialize() {
- TestingInjectionContext ctx = new TestingInjectionContext();
- strategy.restart(ctx);
- await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> assertThat(ctx.destroyed).isTrue());
- await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> assertThat(ctx.initialized).isTrue());
- }
-
- @Test
- void shouldFireRecreateEventBusEvent() {
- Listener listener = new Listener();
- ScmEventBus.getInstance().register(listener);
-
- strategy.restart(context);
-
- assertThat(listener.event).isNotNull();
- }
-
- @Test
- void shouldRegisterContextAfterRestart() throws InterruptedException {
- TestingInjectionContext ctx = new TestingInjectionContext();
- strategy.restart(ctx);
-
- await().atMost(1, TimeUnit.SECONDS).until(() -> ctx.initialized);
- Thread.sleep(50L);
- ScmEventBus.getInstance().post("hello event");
-
- assertThat(ctx.event).isEqualTo("hello event");
- }
-
- public static class Listener {
-
- private RecreateEventBusEvent event;
-
- @Subscribe(async = false)
- public void setEvent(RecreateEventBusEvent event) {
- this.event = event;
- }
- }
-
- public static class TestingInjectionContext implements RestartStrategy.InjectionContext {
-
- private volatile String event;
- private boolean initialized = false;
- private boolean destroyed = false;
-
- @Subscribe(async = false)
- public void setEvent(String event) {
- this.event = event;
- }
-
- @Override
- public void initialize() {
- this.initialized = true;
- }
-
- @Override
- public void destroy() {
- this.destroyed = true;
- }
- }
-
-}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/RestartStrategyTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/RestartStrategyTest.java
new file mode 100644
index 0000000000..2205bfc0d0
--- /dev/null
+++ b/scm-webapp/src/test/java/sonia/scm/lifecycle/RestartStrategyTest.java
@@ -0,0 +1,139 @@
+/*
+ * MIT License
+ *
+ * Copyright (c) 2020-present Cloudogu GmbH and 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.
+ */
+package sonia.scm.lifecycle;
+
+import com.google.common.base.Strings;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import sonia.scm.util.SystemUtil;
+
+import java.util.Optional;
+import java.util.function.Consumer;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class RestartStrategyTest {
+ private final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ @Test
+ void shouldReturnRestartStrategyFromSystemProperty() {
+ withStrategy(TestingRestartStrategy.class.getName(), (rs) -> {
+ assertThat(rs).containsInstanceOf(TestingRestartStrategy.class);
+ });
+ }
+
+ @Test
+ void shouldReturnRestartStrategyFromSystemPropertyWithClassLoaderConstructor() {
+ withStrategy(ComplexRestartStrategy.class.getName(), (rs) -> {
+ assertThat(rs).containsInstanceOf(ComplexRestartStrategy.class)
+ .get()
+ .extracting("classLoader")
+ .isSameAs(classLoader);
+ });
+ }
+
+ @Test
+ void shouldThrowExceptionForNonStrategyClass() {
+ withStrategy(RestartStrategyTest.class.getName(), () -> {
+ assertThrows(RestartNotSupportedException.class, () -> RestartStrategy.get(classLoader));
+ });
+ }
+
+ @Test
+ void shouldReturnEmpty() {
+ withStrategy(RestartStrategyFactory.STRATEGY_NONE, (rs) -> {
+ assertThat(rs).isEmpty();
+ });
+ }
+
+ @Test
+ void shouldReturnEmptyForUnknownOs() {
+ withSystemProperty(SystemUtil.PROPERTY_OSNAME, "hitchhiker-os", () -> {
+ Optional restartStrategy = RestartStrategy.get(classLoader);
+ assertThat(restartStrategy).isEmpty();
+ });
+ }
+
+ @Test
+ void shouldReturnExitRestartStrategy() {
+ withStrategy(ExitRestartStrategy.NAME, (rs) -> {
+ assertThat(rs).containsInstanceOf(ExitRestartStrategy.class);
+ });
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = { "linux", "darwin", "solaris", "freebsd", "openbsd" })
+ void shouldReturnPosixRestartStrategyForPosixBased(String os) {
+ withSystemProperty(SystemUtil.PROPERTY_OSNAME, os, () -> {
+ Optional restartStrategy = RestartStrategy.get(classLoader);
+ assertThat(restartStrategy).containsInstanceOf(PosixRestartStrategy.class);
+ });
+ }
+
+ private void withStrategy(String strategy, Consumer> consumer) {
+ withStrategy(strategy, () -> {
+ consumer.accept(RestartStrategy.get(classLoader));
+ });
+ }
+
+ private void withStrategy(String strategy, Runnable runnable) {
+ withSystemProperty(RestartStrategyFactory.PROPERTY_STRATEGY, strategy, runnable);
+ }
+
+ private void withSystemProperty(String key, String value, Runnable runnable) {
+ String oldValue = System.getProperty(key);
+ System.setProperty(key, value);
+ try {
+ runnable.run();
+ } finally {
+ if (Strings.isNullOrEmpty(oldValue)) {
+ System.clearProperty(key);
+ } else {
+ System.setProperty(key, oldValue);
+ }
+ }
+ }
+
+ public static class TestingRestartStrategy extends RestartStrategy {
+ @Override
+ protected void executeRestart(InjectionContext context) {
+ }
+ }
+
+ public static class ComplexRestartStrategy extends RestartStrategy {
+
+ private final ClassLoader classLoader;
+
+ public ComplexRestartStrategy(ClassLoader classLoader) {
+ this.classLoader = classLoader;
+ }
+
+ @Override
+ protected void executeRestart(InjectionContext context) {
+ }
+ }
+
+}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleTest.java
index 209e641abe..133bbcacbd 100644
--- a/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.lifecycle.classloading;
import org.junit.jupiter.api.Test;
@@ -30,20 +30,9 @@ import static org.assertj.core.api.Assertions.assertThat;
class ClassLoaderLifeCycleTest {
- @Test
- void shouldCreateSimpleClassLoader() {
- System.setProperty(ClassLoaderLifeCycle.PROPERTY, SimpleClassLoaderLifeCycle.NAME);
- try {
- ClassLoaderLifeCycle classLoaderLifeCycle = ClassLoaderLifeCycle.create();
- assertThat(classLoaderLifeCycle).isInstanceOf(SimpleClassLoaderLifeCycle.class);
- } finally {
- System.clearProperty(ClassLoaderLifeCycle.PROPERTY);
- }
- }
-
@Test
void shouldCreateDefaultClassLoader() {
ClassLoaderLifeCycle classLoaderLifeCycle = ClassLoaderLifeCycle.create();
- assertThat(classLoaderLifeCycle).isInstanceOf(ClassLoaderLifeCycleWithLeakPrevention.class);
+ assertThat(classLoaderLifeCycle).isInstanceOf(SimpleClassLoaderLifeCycle.class);
}
}
diff --git a/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPreventionTest.java b/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPreventionTest.java
deleted file mode 100644
index f237ab8a30..0000000000
--- a/scm-webapp/src/test/java/sonia/scm/lifecycle/classloading/ClassLoaderLifeCycleWithLeakPreventionTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * MIT License
- *
- * Copyright (c) 2020-present Cloudogu GmbH and 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.
- */
-
-package sonia.scm.lifecycle.classloading;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
-import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventorFactory;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.net.URL;
-import java.net.URLClassLoader;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.*;
-
-@ExtendWith(MockitoExtension.class)
-class ClassLoaderLifeCycleWithLeakPreventionTest {
-
- @Mock
- private ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory;
-
- @Mock
- private ClassLoaderLeakPreventor classLoaderLeakPreventor;
-
- @Test
- void shouldThrowIllegalStateExceptionWithoutInit() {
- ClassLoaderLifeCycleWithLeakPrevention lifeCycle = new ClassLoaderLifeCycleWithLeakPrevention(Thread.currentThread().getContextClassLoader());
- assertThrows(IllegalStateException.class, lifeCycle::getBootstrapClassLoader);
- }
-
- @Test
- void shouldThrowIllegalStateExceptionAfterShutdown() {
- ClassLoaderLifeCycleWithLeakPrevention lifeCycle = createMockedLifeCycle();
- lifeCycle.initialize();
-
- lifeCycle.shutdown();
- assertThrows(IllegalStateException.class, lifeCycle::getBootstrapClassLoader);
- }
-
- @Test
- void shouldCreateBootstrapClassLoaderOnInit() {
- ClassLoaderLifeCycleWithLeakPrevention lifeCycle = new ClassLoaderLifeCycleWithLeakPrevention(Thread.currentThread().getContextClassLoader());
- lifeCycle.initialize();
-
- assertThat(lifeCycle.getBootstrapClassLoader()).isNotNull();
- }
-
- @Test
- void shouldCallTheLeakPreventor() {
- ClassLoaderLifeCycleWithLeakPrevention lifeCycle = createMockedLifeCycle();
-
- lifeCycle.initialize();
- verify(classLoaderLeakPreventor, times(1)).runPreClassLoaderInitiators();
-
- lifeCycle.createChildFirstPluginClassLoader(new URL[0], null, "a");
- lifeCycle.createPluginClassLoader(new URL[0], null, "b");
- verify(classLoaderLeakPreventor, times(3)).runPreClassLoaderInitiators();
-
- lifeCycle.shutdown();
- verify(classLoaderLeakPreventor, times(3)).runCleanUps();
- }
-
- @Test
- void shouldCloseCloseableClassLoaders() throws IOException {
- // we use URLClassLoader, because we must be sure that the classloader is closable
- URLClassLoader webappClassLoader = spy(new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader()));
-
- ClassLoaderLifeCycleWithLeakPrevention lifeCycle = createMockedLifeCycle(webappClassLoader);
- lifeCycle.setClassLoaderAppendListener(new ClassLoaderLifeCycleWithLeakPrevention.ClassLoaderAppendListener() {
- @Override
- public C apply(C classLoader) {
- return spy(classLoader);
- }
- });
- lifeCycle.initialize();
-
- ClassLoader pluginA = lifeCycle.createChildFirstPluginClassLoader(new URL[0], null, "a");
- ClassLoader pluginB = lifeCycle.createPluginClassLoader(new URL[0], null, "b");
-
- lifeCycle.shutdown();
-
- closed(pluginB);
- closed(pluginA);
-
- neverClosed(webappClassLoader);
- }
-
- private void neverClosed(Object object) throws IOException {
- Closeable closeable = closeable(object);
- verify(closeable, never()).close();
- }
-
- private void closed(Object object) throws IOException {
- Closeable closeable = closeable(object);
- verify(closeable).close();
- }
-
- private Closeable closeable(Object object) {
- assertThat(object).isInstanceOf(Closeable.class);
- return (Closeable) object;
- }
-
- private ClassLoaderLifeCycleWithLeakPrevention createMockedLifeCycle() {
- return createMockedLifeCycle(Thread.currentThread().getContextClassLoader());
- }
-
- private ClassLoaderLifeCycleWithLeakPrevention createMockedLifeCycle(ClassLoader classLoader) {
- when(classLoaderLeakPreventorFactory.newLeakPreventor(any(ClassLoader.class))).thenReturn(classLoaderLeakPreventor);
- return new ClassLoaderLifeCycleWithLeakPrevention(classLoader, classLoaderLeakPreventorFactory);
- }
-
-}
diff --git a/scm-webapp/src/test/java/sonia/scm/plugin/DefaultPluginManagerTest.java b/scm-webapp/src/test/java/sonia/scm/plugin/DefaultPluginManagerTest.java
index b82d7af39e..8f3f7bbe57 100644
--- a/scm-webapp/src/test/java/sonia/scm/plugin/DefaultPluginManagerTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/plugin/DefaultPluginManagerTest.java
@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
-
+
package sonia.scm.plugin;
import com.google.common.collect.ImmutableList;
@@ -36,10 +36,12 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.TempDirectory;
import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import sonia.scm.NotFoundException;
import sonia.scm.ScmConstraintViolationException;
+import sonia.scm.lifecycle.Restarter;
import java.io.IOException;
import java.nio.file.Files;
@@ -78,13 +80,15 @@ class DefaultPluginManagerTest {
@Mock
private PluginInstaller installer;
+ @Mock
+ private Restarter restarter;
+
+ @InjectMocks
private DefaultPluginManager manager;
@Mock
private Subject subject;
- private boolean restartTriggered = false;
-
@BeforeEach
void mockInstaller() {
lenient().when(installer.install(any())).then(ic -> {
@@ -93,16 +97,6 @@ class DefaultPluginManagerTest {
});
}
- @BeforeEach
- void createPluginManagerToTestWithCapturedRestart() {
- manager = new DefaultPluginManager(null, loader, center, installer) { // event bus is only used in restart and this is replaced here
- @Override
- void triggerRestart(String cause) {
- restartTriggered = true;
- }
- };
- }
-
@Nested
class WithAdminPermissions {
@@ -209,7 +203,7 @@ class DefaultPluginManagerTest {
manager.install("scm-git-plugin", false);
verify(installer).install(git);
- assertThat(restartTriggered).isFalse();
+ verify(restarter, never()).restart(any(), any());
}
@Test
@@ -258,7 +252,7 @@ class DefaultPluginManagerTest {
PendingPluginInstallation pendingMail = mock(PendingPluginInstallation.class);
doReturn(pendingMail).when(installer).install(mail);
- doThrow(new PluginChecksumMismatchException("checksum does not match")).when(installer).install(review);
+ doThrow(new PluginChecksumMismatchException(mail, "1", "2")).when(installer).install(review);
assertThrows(PluginInstallException.class, () -> manager.install("scm-review-plugin", false));
@@ -287,7 +281,7 @@ class DefaultPluginManagerTest {
manager.install("scm-git-plugin", true);
verify(installer).install(git);
- assertThat(restartTriggered).isTrue();
+ verify(restarter).restart(any(), any());
}
@Test
@@ -296,7 +290,7 @@ class DefaultPluginManagerTest {
when(loader.getInstalledPlugins()).thenReturn(ImmutableList.of(gitInstalled));
manager.install("scm-git-plugin", true);
- assertThat(restartTriggered).isFalse();
+ verify(restarter, never()).restart(any(), any());
}
@Test
@@ -318,14 +312,14 @@ class DefaultPluginManagerTest {
manager.install("scm-review-plugin", false);
manager.executePendingAndRestart();
- assertThat(restartTriggered).isTrue();
+ verify(restarter).restart(any(), any());
}
@Test
void shouldNotSendRestartEventWithoutPendingPlugins() {
manager.executePendingAndRestart();
- assertThat(restartTriggered).isFalse();
+ verify(restarter, never()).restart(any(), any());
}
@Test
@@ -476,7 +470,7 @@ class DefaultPluginManagerTest {
manager.executePendingAndRestart();
- assertThat(restartTriggered).isTrue();
+ verify(restarter).restart(any(), any());
}
@Test
diff --git a/scm-webapp/src/test/java/sonia/scm/update/MigrationWizardServletTest.java b/scm-webapp/src/test/java/sonia/scm/update/MigrationWizardServletTest.java
index fb33c87d93..c50f2e6927 100644
--- a/scm-webapp/src/test/java/sonia/scm/update/MigrationWizardServletTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/update/MigrationWizardServletTest.java
@@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import sonia.scm.lifecycle.Restarter;
import sonia.scm.update.repository.DefaultMigrationStrategyDAO;
import sonia.scm.update.repository.MigrationStrategy;
import sonia.scm.update.repository.V1Repository;
@@ -51,6 +52,8 @@ class MigrationWizardServletTest {
XmlRepositoryV1UpdateStep updateStep;
@Mock
DefaultMigrationStrategyDAO migrationStrategyDao;
+ @Mock
+ Restarter restarter;
@Mock
HttpServletRequest request;
@@ -64,7 +67,7 @@ class MigrationWizardServletTest {
@BeforeEach
void initServlet() {
- servlet = new MigrationWizardServlet(updateStep, migrationStrategyDao) {
+ servlet = new MigrationWizardServlet(updateStep, migrationStrategyDao, restarter) {
@Override
void respondWithTemplate(HttpServletResponse resp, Map model, String templateName) {
renderedTemplateName = templateName;
diff --git a/scm-webapp/src/test/java/sonia/scm/web/i18n/I18nServletTest.java b/scm-webapp/src/test/java/sonia/scm/web/i18n/I18nServletTest.java
index b3377bee2f..4770a54d91 100644
--- a/scm-webapp/src/test/java/sonia/scm/web/i18n/I18nServletTest.java
+++ b/scm-webapp/src/test/java/sonia/scm/web/i18n/I18nServletTest.java
@@ -44,6 +44,7 @@ import sonia.scm.lifecycle.RestartEvent;
import sonia.scm.cache.Cache;
import sonia.scm.cache.CacheManager;
import sonia.scm.event.ScmEventBus;
+import sonia.scm.lifecycle.RestartEventFactory;
import sonia.scm.plugin.PluginLoader;
import javax.servlet.http.HttpServletRequest;
@@ -138,7 +139,7 @@ public class I18nServletTest {
public void shouldCleanCacheOnRestartEvent() {
ScmEventBus.getInstance().register(servlet);
- ScmEventBus.getInstance().post(new RestartEvent(I18nServlet.class, "Restart to reload the plugin resources"));
+ ScmEventBus.getInstance().post(RestartEventFactory.create(I18nServlet.class, "Restart to reload the plugin resources"));
verify(cache).clear();
}