repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ManagedProcessHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; import org.sonar.process.ProcessId; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class ManagedProcessHandler { public static final long DEFAULT_WATCHER_DELAY_MS = 500L; private static final Logger LOG = LoggerFactory.getLogger(ManagedProcessHandler.class); private final ProcessId processId; private final ManagedProcessLifecycle lifecycle; private final List<ManagedProcessEventListener> eventListeners; private final Timeout stopTimeout; private final Timeout hardStopTimeout; private final long watcherDelayMs; private final AppSettings appSettings; private ManagedProcess process; private StreamGobbler stdOutGobbler; private StreamGobbler stdErrGobbler; private final StopWatcher stopWatcher; private final EventWatcher eventWatcher; // keep flag so that the operational event is sent only once // to listeners private boolean operational = false; private ManagedProcessHandler(Builder builder) { this.processId = requireNonNull(builder.processId, "processId can't be null"); this.lifecycle = new ManagedProcessLifecycle(this.processId, builder.lifecycleListeners); this.eventListeners = builder.eventListeners; this.stopTimeout = builder.stopTimeout; this.hardStopTimeout = builder.hardStopTimeout; this.watcherDelayMs = builder.watcherDelayMs; this.stopWatcher = new StopWatcher(); this.eventWatcher = new EventWatcher(); this.appSettings = builder.settings; } public boolean start(Supplier<ManagedProcess> commandLauncher) { if (!lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STARTING)) { // has already been started return false; } try { this.process = commandLauncher.get(); } catch (RuntimeException e) { LOG.error("Failed to launch process [{}]", processId.getHumanReadableName(), e); lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STOPPING); finalizeStop(); throw e; } this.stdOutGobbler = new StreamGobbler(process.getInputStream(), appSettings, processId.getKey()); this.stdOutGobbler.start(); this.stdErrGobbler = new StreamGobbler(process.getErrorStream(), appSettings, processId.getKey()); this.stdErrGobbler.start(); this.stopWatcher.start(); this.eventWatcher.start(); // Could be improved by checking the status "up" in shared memory. // Not a problem so far as this state is not used by listeners. lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STARTED); return true; } public ProcessId getProcessId() { return processId; } ManagedProcessLifecycle.State getState() { return lifecycle.getState(); } public void stop() throws InterruptedException { if (lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STOPPING)) { stopImpl(); if (process != null && process.isAlive()) { LOG.info("{} failed to stop in a graceful fashion. Hard stopping it.", processId.getHumanReadableName()); hardStop(); } else { // enforce stop and clean-up even if process has been quickly stopped finalizeStop(); } } else { // already stopping or stopped waitForDown(); } } /** * Sends kill signal and awaits termination. No guarantee that process is gracefully terminated (=shutdown hooks * executed). It depends on OS. */ public void hardStop() throws InterruptedException { if (lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.HARD_STOPPING)) { hardStopImpl(); if (process != null && process.isAlive()) { LOG.info("{} failed to stop in a quick fashion. Killing it.", processId.getHumanReadableName()); } // enforce stop and clean-up even if process has been quickly stopped finalizeStop(); } else { // already stopping or stopped waitForDown(); } } private void waitForDown() { while (process != null && process.isAlive()) { try { process.waitFor(); } catch (InterruptedException ignored) { // ignore, waiting for process to stop Thread.currentThread().interrupt(); } } } private void stopImpl() throws InterruptedException { if (process == null) { return; } try { process.askForStop(); process.waitFor(stopTimeout.getDuration(), stopTimeout.getUnit()); } catch (InterruptedException e) { // can't wait for the termination of process. Let's assume it's down. throw rethrowWithWarn(e, format("Interrupted while stopping process %s", processId)); } catch (Throwable e) { LOG.error("Failed asking for graceful stop of process {}", processId, e); } } private void hardStopImpl() throws InterruptedException { if (process == null) { return; } try { process.askForHardStop(); process.waitFor(hardStopTimeout.getDuration(), hardStopTimeout.getUnit()); } catch (InterruptedException e) { // can't wait for the termination of process. Let's assume it's down. throw rethrowWithWarn(e, format("Interrupted while hard stopping process %s (currentThread=%s)", processId, Thread.currentThread().getName())); } catch (Throwable e) { LOG.error("Failed while asking for hard stop of process {}", processId, e); } } private static InterruptedException rethrowWithWarn(InterruptedException e, String errorMessage) { LOG.warn(errorMessage, e); Thread.currentThread().interrupt(); return new InterruptedException(errorMessage); } private void finalizeStop() { if (!lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.FINALIZE_STOPPING)) { return; } interrupt(eventWatcher); interrupt(stopWatcher); if (process != null) { process.destroyForcibly(); waitForDown(); process.closeStreams(); } if (stdOutGobbler != null) { StreamGobbler.waitUntilFinish(stdOutGobbler); stdOutGobbler.interrupt(); } if (stdErrGobbler != null) { StreamGobbler.waitUntilFinish(stdErrGobbler); stdErrGobbler.interrupt(); } // will trigger state listeners lifecycle.tryToMoveTo(ManagedProcessLifecycle.State.STOPPED); } private static void interrupt(@Nullable Thread thread) { Thread currentThread = Thread.currentThread(); // prevent current thread from interrupting itself if (thread != null && currentThread != thread) { thread.interrupt(); if (LOG.isTraceEnabled()) { Exception e = new Exception("(capturing stack trace for debugging purpose)"); LOG.trace("{} interrupted {}", currentThread.getName(), thread.getName(), e); } } } void refreshState() { if (process.isAlive()) { if (!operational && process.isOperational()) { operational = true; eventListeners.forEach(l -> l.onManagedProcessEvent(processId, ManagedProcessEventListener.Type.OPERATIONAL)); } if (process.askedForRestart()) { process.acknowledgeAskForRestart(); eventListeners.forEach(l -> l.onManagedProcessEvent(processId, ManagedProcessEventListener.Type.ASK_FOR_RESTART)); } } } @Override public String toString() { return format("Process[%s]", processId.getHumanReadableName()); } /** * This thread blocks as long as the monitored process is physically alive. * It avoids from executing {@link Process#exitValue()} at a fixed rate : * <ul> * <li>no usage of exception for flow control. Indeed {@link Process#exitValue()} throws an exception * if process is alive. There's no method <code>Process#isAlive()</code></li> * <li>no delay, instantaneous notification that process is down</li> * </ul> */ private class StopWatcher extends Thread { StopWatcher() { // this name is different than Thread#toString(), which includes name, priority // and thread group // -> do not override toString() super(format("StopWatcher[%s]", processId.getHumanReadableName())); } @Override public void run() { try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // stop watching process } // since process is already stopped, this will only finalize the stop sequence // call hardStop() rather than finalizeStop() directly because hardStop() checks lifeCycle state and this // avoid running to concurrent stop finalization pieces of code try { hardStop(); } catch (InterruptedException e) { LOG.debug("Interrupted while stopping [{}] after process ended", processId.getHumanReadableName(), e); Thread.currentThread().interrupt(); } } } private class EventWatcher extends Thread { EventWatcher() { // this name is different than Thread#toString(), which includes name, priority // and thread group // -> do not override toString() super(format("EventWatcher[%s]", processId.getHumanReadableName())); } @Override public void run() { try { while (process.isAlive()) { refreshState(); Thread.sleep(watcherDelayMs); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } public static Builder builder(ProcessId processId) { return new Builder(processId); } public static class Builder { private final ProcessId processId; private final List<ManagedProcessEventListener> eventListeners = new ArrayList<>(); private final List<ProcessLifecycleListener> lifecycleListeners = new ArrayList<>(); private long watcherDelayMs = DEFAULT_WATCHER_DELAY_MS; private Timeout stopTimeout; private Timeout hardStopTimeout; private AppSettings settings; private Builder(ProcessId processId) { this.processId = processId; } public Builder addEventListener(ManagedProcessEventListener listener) { this.eventListeners.add(listener); return this; } public Builder addProcessLifecycleListener(ProcessLifecycleListener listener) { this.lifecycleListeners.add(listener); return this; } /** * Default delay is {@link #DEFAULT_WATCHER_DELAY_MS} */ public Builder setWatcherDelayMs(long l) { this.watcherDelayMs = l; return this; } public Builder setStopTimeout(Timeout stopTimeout) { this.stopTimeout = ensureStopTimeoutNonNull(stopTimeout); return this; } public Builder setHardStopTimeout(Timeout hardStopTimeout) { this.hardStopTimeout = ensureHardStopTimeoutNonNull(hardStopTimeout); return this; } private static Timeout ensureStopTimeoutNonNull(Timeout stopTimeout) { return requireNonNull(stopTimeout, "stopTimeout can't be null"); } private static Timeout ensureHardStopTimeoutNonNull(Timeout hardStopTimeout) { return requireNonNull(hardStopTimeout, "hardStopTimeout can't be null"); } public ManagedProcessHandler build() { ensureStopTimeoutNonNull(this.stopTimeout); ensureHardStopTimeoutNonNull(this.hardStopTimeout); return new ManagedProcessHandler(this); } public Builder setAppSettings(AppSettings settings) { this.settings = settings; return this; } } public static final class Timeout { private final long duration; private final TimeUnit timeoutUnit; private Timeout(long duration, TimeUnit unit) { this.duration = duration; this.timeoutUnit = Objects.requireNonNull(unit, "unit can't be null"); } public static Timeout newTimeout(long duration, TimeUnit unit) { return new Timeout(duration, unit); } public long getDuration() { return duration; } public TimeUnit getUnit() { return timeoutUnit; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Timeout timeout = (Timeout) o; return duration == timeout.duration && timeoutUnit == timeout.timeoutUnit; } @Override public int hashCode() { return Objects.hash(duration, timeoutUnit); } } }
13,453
32.551122
126
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ManagedProcessLifecycle.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.ProcessId; import static org.sonar.application.process.ManagedProcessLifecycle.State.FINALIZE_STOPPING; import static org.sonar.application.process.ManagedProcessLifecycle.State.HARD_STOPPING; import static org.sonar.application.process.ManagedProcessLifecycle.State.INIT; import static org.sonar.application.process.ManagedProcessLifecycle.State.STARTED; import static org.sonar.application.process.ManagedProcessLifecycle.State.STARTING; import static org.sonar.application.process.ManagedProcessLifecycle.State.STOPPED; import static org.sonar.application.process.ManagedProcessLifecycle.State.STOPPING; public class ManagedProcessLifecycle { public enum State { INIT, STARTING, STARTED, STOPPING, HARD_STOPPING, FINALIZE_STOPPING, STOPPED } private static final Logger LOG = LoggerFactory.getLogger(ManagedProcessLifecycle.class); private static final Map<State, Set<State>> TRANSITIONS = buildTransitions(); private final ProcessId processId; private final List<ProcessLifecycleListener> listeners; private State state; public ManagedProcessLifecycle(ProcessId processId, List<ProcessLifecycleListener> listeners) { this.processId = processId; this.listeners = listeners; this.state = INIT; } private static Map<State, Set<State>> buildTransitions() { Map<State, Set<State>> res = new EnumMap<>(State.class); res.put(INIT, toSet(STARTING)); res.put(STARTING, toSet(STARTED, STOPPING, HARD_STOPPING)); res.put(STARTED, toSet(STOPPING, HARD_STOPPING)); res.put(STOPPING, toSet(HARD_STOPPING, FINALIZE_STOPPING)); res.put(HARD_STOPPING, toSet(FINALIZE_STOPPING)); res.put(FINALIZE_STOPPING, toSet(STOPPED)); res.put(STOPPED, toSet()); return Collections.unmodifiableMap(res); } private static Set<State> toSet(State... states) { if (states.length == 0) { return Collections.emptySet(); } if (states.length == 1) { return Collections.singleton(states[0]); } return EnumSet.copyOf(Arrays.asList(states)); } State getState() { return state; } synchronized boolean tryToMoveTo(State to) { boolean res = false; State currentState = state; if (TRANSITIONS.get(currentState).contains(to)) { this.state = to; res = true; listeners.forEach(listener -> listener.onProcessState(processId, to)); } LOG.debug("{} tryToMoveTo {} from {} to {} => {}", Thread.currentThread().getName(), processId.getHumanReadableName(), currentState, to, res); return res; } }
3,660
36.357143
146
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ProcessCommandsManagedProcess.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static java.util.Objects.requireNonNull; public class ProcessCommandsManagedProcess extends AbstractManagedProcess { private final ProcessCommands commands; public ProcessCommandsManagedProcess(Process process, ProcessId processId, ProcessCommands commands) { super(process, processId); this.commands = requireNonNull(commands, "commands can't be null"); } /** * Whether the process has set the operational flag (in ipc shared memory) */ @Override public boolean isOperational() { return commands.isOperational(); } /** * Send request to gracefully stop to the process (via ipc shared memory) */ @Override public void askForStop() { commands.askForStop(); } /** * Send request to quickly stop to the process (via ipc shared memory) */ @Override public void askForHardStop() { commands.askForHardStop(); } /** * Whether the process asked for a full restart (via ipc shared memory) */ @Override public boolean askedForRestart() { return commands.askedForRestart(); } /** * Removes the flag in ipc shared memory so that next call to {@link #askedForRestart()} * returns {@code false}, except if meanwhile process asks again for restart. */ @Override public void acknowledgeAskForRestart() { commands.acknowledgeAskForRestart(); } }
2,331
28.897436
104
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ProcessLifecycleListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import org.sonar.process.ProcessId; @FunctionalInterface public interface ProcessLifecycleListener { /** * This method is called when the state of the process with the specified {@link ProcessId} * changes. * * Call blocks the process watcher. Implementations should be asynchronous and * fork a new thread if call can be long. */ void onProcessState(ProcessId processId, ManagedProcessLifecycle.State state); }
1,320
34.702703
93
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/StreamGobbler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; import org.sonar.process.Props; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonar.process.ProcessProperties.Property.LOG_JSON_OUTPUT; /** * Reads process output and writes to logs */ public class StreamGobbler extends Thread { public static final String LOGGER_STARTUP = "startup"; public static final String LOGGER_GOBBLER = "gobbler"; private static final String LOGGER_STARTUP_FORMAT = String.format("[%s]", LOGGER_STARTUP); private final AppSettings appSettings; private final InputStream is; private final Logger logger; /* This logger forwards startup logs (thanks to re-using fileappender) from subprocesses to sonar.log when running SQ not from wrapper. */ private final Logger startupLogger; StreamGobbler(InputStream is, AppSettings appSettings, String processKey) { this(is, processKey, appSettings, LoggerFactory.getLogger(LOGGER_GOBBLER), LoggerFactory.getLogger(LOGGER_STARTUP)); } StreamGobbler(InputStream is, String processKey, AppSettings appSettings, Logger logger, Logger startupLogger) { super(String.format("Gobbler[%s]", processKey)); this.is = is; this.logger = logger; this.appSettings = appSettings; this.startupLogger = startupLogger; } @Override public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8))) { String line; while ((line = br.readLine()) != null) { if (line.contains(LOGGER_STARTUP)) { logStartupLog(line); } else { logger.info(line); } } } catch (Exception ignored) { // ignore } } private void logStartupLog(String line) { if (isJsonLoggingEnabled()) { JsonElement jsonElement = JsonParser.parseString(line); if (!jsonElement.getAsJsonObject().get("logger").getAsString().equals(LOGGER_STARTUP)) { // Log contains "startup" string but only in the message content. We skip. return; } startupLogger.warn(jsonElement.getAsJsonObject().get("message").getAsString()); } else if (line.contains(LOGGER_STARTUP_FORMAT)) { startupLogger.warn(line.substring(line.indexOf(LOGGER_STARTUP_FORMAT) + LOGGER_STARTUP_FORMAT.length() + 1)); } } private boolean isJsonLoggingEnabled() { Props props = appSettings.getProps(); return props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), Boolean.parseBoolean(LOG_JSON_OUTPUT.getDefaultValue())); } static void waitUntilFinish(@Nullable StreamGobbler gobbler) { if (gobbler != null) { try { gobbler.join(); } catch (InterruptedException ignored) { // consider as finished, restore the interrupted flag Thread.currentThread().interrupt(); } } } }
3,946
34.558559
134
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.application.process; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AbstractStopRequestWatcherTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; public class AbstractStopRequestWatcherTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); private String threadName = RandomStringUtils.randomAlphabetic(12); private TestBooleanSupplier booleanSupplier = new TestBooleanSupplier(); private TestAction stopAction = new TestAction(); @Test public void constructor_sets_thread_name_and_daemon_true() { AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction) { }; assertThat(underTest.getName()).isEqualTo(threadName); assertThat(underTest.isDaemon()).isTrue(); } @Test public void call_stop_action_when_booleanSupplier_returns_true() { AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction) { }; underTest.startWatching(); assertThat(underTest.isAlive()).isTrue(); assertThat(stopAction.isCalled()).isFalse(); booleanSupplier.flag = true; await().atMost(1, TimeUnit.MINUTES).until(() -> stopAction.isCalled()); assertThat(stopAction.isCalled()).isTrue(); underTest.stopWatching(); await().until(() -> !underTest.isAlive()); } @Test public void create_instance_with_default_delay() { AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction) { }; assertThat(underTest.getDelayMs()).isEqualTo(500L); } @Test public void create_instance_with_specified_delay() { long delayMs = new Random().nextLong(); AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction, delayMs) { }; assertThat(underTest.getDelayMs()).isEqualTo(delayMs); } @Test public void stop_watching_commands_if_thread_is_interrupted() { AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction) { }; underTest.startWatching(); underTest.interrupt(); await().until(() -> !underTest.isAlive()); assertThat(underTest.isAlive()).isFalse(); } private static class TestBooleanSupplier implements BooleanSupplier { volatile boolean flag = false; @Override public boolean getAsBoolean() { return flag; } } private static class TestAction implements Runnable { volatile boolean called = false; @Override public void run() { called = true; } public boolean isCalled() { return called; } } }
3,823
29.349206
125
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/App.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; /** * This class is looked for by {@link org.sonar.application.config.AppSettingsLoaderImpl} to locate the location * of SQ's sonar-application jar file. * * Adding a fake one here to be able to test the feature in {@link org.sonar.application.config.AppSettingsLoaderImplTest}. */ public class App { }
1,183
38.466667
123
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AppFileSystemTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import javax.annotation.CheckForNull; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.application.config.TestAppSettings; import org.sonar.process.sharedmemoryfile.AllProcessesCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; public class AppFileSystemTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File homeDir; private File dataDir; private File tempDir; private File logsDir; private File webDir; private TestAppSettings settings = new TestAppSettings(); private AppFileSystem underTest = new AppFileSystem(settings); @Before public void before() throws IOException { homeDir = temp.newFolder(); dataDir = new File(homeDir, "data"); tempDir = new File(homeDir, "temp"); logsDir = new File(homeDir, "logs"); webDir = new File(homeDir, "web"); settings.getProps().set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); settings.getProps().set(PATH_DATA.getKey(), dataDir.getAbsolutePath()); settings.getProps().set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); settings.getProps().set(PATH_LOGS.getKey(), logsDir.getAbsolutePath()); settings.getProps().set(PATH_WEB.getKey(), webDir.getAbsolutePath()); } @Test public void reset_creates_dirs_if_they_don_t_exist() throws Exception { assertThat(dataDir).doesNotExist(); underTest.reset(); assertThat(dataDir).exists().isDirectory(); assertThat(logsDir).exists().isDirectory(); assertThat(tempDir).exists().isDirectory(); assertThat(webDir).exists().isDirectory(); underTest.reset(); assertThat(dataDir).exists().isDirectory(); assertThat(logsDir).exists().isDirectory(); assertThat(tempDir).exists().isDirectory(); assertThat(webDir).exists().isDirectory(); } @Test public void reset_deletes_content_of_temp_dir_but_not_temp_dir_itself_if_it_already_exists() throws Exception { assertThat(tempDir.mkdir()).isTrue(); Object tempDirKey = getFileKey(tempDir); File fileInTempDir = new File(tempDir, "someFile.txt"); assertThat(fileInTempDir.createNewFile()).isTrue(); File subDirInTempDir = new File(tempDir, "subDir"); assertThat(subDirInTempDir.mkdir()).isTrue(); underTest.reset(); assertThat(tempDir).exists(); assertThat(fileInTempDir).doesNotExist(); assertThat(subDirInTempDir).doesNotExist(); assertThat(getFileKey(tempDir)).isEqualTo(tempDirKey); } @Test public void reset_deletes_content_of_temp_dir_but_not_sharedmemory_file() throws Exception { assertThat(tempDir.mkdir()).isTrue(); File sharedmemory = new File(tempDir, "sharedmemory"); assertThat(sharedmemory.createNewFile()).isTrue(); FileUtils.write(sharedmemory, "toto"); Object fileKey = getFileKey(sharedmemory); Object tempDirKey = getFileKey(tempDir); File fileInTempDir = new File(tempDir, "someFile.txt"); assertThat(fileInTempDir.createNewFile()).isTrue(); underTest.reset(); assertThat(tempDir).exists(); assertThat(fileInTempDir).doesNotExist(); assertThat(getFileKey(tempDir)).isEqualTo(tempDirKey); assertThat(getFileKey(sharedmemory)).isEqualTo(fileKey); // content of sharedMemory file is reset assertThat(FileUtils.readFileToString(sharedmemory)).isNotEqualTo("toto"); } @Test public void reset_cleans_the_sharedmemory_file() throws IOException { assertThat(tempDir.mkdir()).isTrue(); try (AllProcessesCommands commands = new AllProcessesCommands(tempDir)) { for (int i = 0; i < MAX_PROCESSES; i++) { commands.create(i).setUp(); } underTest.reset(); for (int i = 0; i < MAX_PROCESSES; i++) { assertThat(commands.create(i).isUp()).isFalse(); } } } @CheckForNull private static Object getFileKey(File fileInTempDir) throws IOException { Path path = Paths.get(fileInTempDir.toURI()); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); return attrs.fileKey(); } @Test public void reset_throws_ISE_if_data_dir_is_a_file() throws Exception { resetThrowsISEIfDirIsAFile(PATH_DATA.getKey()); } @Test public void reset_throws_ISE_if_web_dir_is_a_file() throws Exception { resetThrowsISEIfDirIsAFile(PATH_WEB.getKey()); } @Test public void reset_throws_ISE_if_logs_dir_is_a_file() throws Exception { resetThrowsISEIfDirIsAFile(PATH_LOGS.getKey()); } @Test public void reset_throws_ISE_if_temp_dir_is_a_file() throws Exception { resetThrowsISEIfDirIsAFile(PATH_TEMP.getKey()); } private void resetThrowsISEIfDirIsAFile(String property) throws IOException { File file = new File(homeDir, "zoom.store"); assertThat(file.createNewFile()).isTrue(); settings.getProps().set(property, file.getAbsolutePath()); assertThatThrownBy(() -> underTest.reset()) .isInstanceOf(IllegalStateException.class) .hasMessage("Property '" + property + "' is not valid, not a directory: " + file.getAbsolutePath()); } @Test public void fail_if_required_directory_is_a_file() throws Exception { // <home>/data is missing FileUtils.forceMkdir(webDir); FileUtils.forceMkdir(logsDir); FileUtils.touch(dataDir); assertThatThrownBy(() -> underTest.reset()) .isInstanceOf(IllegalStateException.class) .hasMessage("Property 'sonar.path.data' is not valid, not a directory: " + dataDir.getAbsolutePath()); } }
7,098
34.853535
113
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AppLoggingTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.joran.spi.ConsoleTarget; import ch.qos.logback.core.rolling.RollingFileAppender; import java.io.File; import java.util.Iterator; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; import org.sonar.application.config.TestAppSettings; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.logging.LogbackJsonLayout; import org.sonar.process.logging.PatternLayoutEncoder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.application.process.StreamGobbler.LOGGER_GOBBLER; import static org.sonar.application.process.StreamGobbler.LOGGER_STARTUP; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; public class AppLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File logDir; private AppSettings settings = new TestAppSettings(); private AppLogging underTest = new AppLogging(settings); @Before public void setUp() throws Exception { logDir = temp.newFolder(); settings.getProps().set(PATH_LOGS.getKey(), logDir.getAbsolutePath()); } @AfterClass public static void resetLogback() throws Exception { new LogbackHelper().resetFromXml("/logback-test.xml"); } @Test public void root_logger_only_writes_to_console_with_formatting_when_running_from_sonar_script() { LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); var consoleAppender = (ConsoleAppender<ILoggingEvent>) rootLogger.getAppender("APP_CONSOLE"); verifyAppFormattedLogEncoder(consoleAppender.getEncoder()); var rollingFileAppender = rootLogger.getAppender("file_sonar"); assertThat(rollingFileAppender).isNotNull(); assertThat(rootLogger.iteratorForAppenders()).toIterable().hasSize(2); } @Test public void gobbler_logger_writes_to_console_without_formatting_when_running_from_sonar_script() { LoggerContext ctx = underTest.configure(); Logger gobblerLogger = ctx.getLogger(LOGGER_GOBBLER); verifyGobblerConsoleAppender(gobblerLogger); assertThat(gobblerLogger.iteratorForAppenders()).toIterable().hasSize(1); } @Test public void root_logger_writes_to_console_with_formatting_and_to_sonar_log_file_when_running_from_command_line() { emulateRunFromCommandLine(false); LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); verifyAppConsoleAppender(rootLogger.getAppender("APP_CONSOLE")); verifySonarLogFileAppender(rootLogger.getAppender("file_sonar")); assertThat(rootLogger.iteratorForAppenders()).toIterable().hasSize(2); // verify no other logger except startup logger writes to sonar.log ctx.getLoggerList() .stream() .filter(logger -> !ROOT_LOGGER_NAME.equals(logger.getName()) && !LOGGER_STARTUP.equals(logger.getName())) .forEach(AppLoggingTest::verifyNoFileAppender); } @Test public void gobbler_logger_writes_to_console_without_formatting_when_running_from_command_line() { emulateRunFromCommandLine(false); LoggerContext ctx = underTest.configure(); Logger gobblerLogger = ctx.getLogger(LOGGER_GOBBLER); verifyGobblerConsoleAppender(gobblerLogger); assertThat(gobblerLogger.iteratorForAppenders()).toIterable().hasSize(1); } @Test public void root_logger_writes_to_console_with_formatting_and_to_sonar_log_file_when_running_from_ITs() { emulateRunFromCommandLine(true); LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); verifyAppConsoleAppender(rootLogger.getAppender("APP_CONSOLE")); verifySonarLogFileAppender(rootLogger.getAppender("file_sonar")); assertThat(rootLogger.iteratorForAppenders()).toIterable().hasSize(2); ctx.getLoggerList() .stream() .filter(logger -> !ROOT_LOGGER_NAME.equals(logger.getName()) && !LOGGER_STARTUP.equals(logger.getName())) .forEach(AppLoggingTest::verifyNoFileAppender); } @Test public void gobbler_logger_writes_to_console_without_formatting_when_running_from_ITs() { emulateRunFromCommandLine(true); LoggerContext ctx = underTest.configure(); Logger gobblerLogger = ctx.getLogger(LOGGER_GOBBLER); verifyGobblerConsoleAppender(gobblerLogger); assertThat(gobblerLogger.iteratorForAppenders()).toIterable().hasSize(1); } @Test public void configure_no_rotation_on_sonar_file() { settings.getProps().set("sonar.log.rollingPolicy", "none"); LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); Appender<ILoggingEvent> appender = rootLogger.getAppender("file_sonar"); assertThat(appender) .isNotInstanceOf(RollingFileAppender.class) .isInstanceOf(FileAppender.class); } @Test public void default_level_for_root_logger_is_INFO() { LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.INFO); } @Test public void root_logger_level_changes_with_global_property() { settings.getProps().set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.TRACE); } @Test public void root_logger_level_changes_with_app_property() { settings.getProps().set("sonar.log.level.app", "TRACE"); LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.TRACE); } @Test public void root_logger_level_is_configured_from_app_property_over_global_property() { settings.getProps().set("sonar.log.level", "TRACE"); settings.getProps().set("sonar.log.level.app", "DEBUG"); LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.DEBUG); } @Test public void root_logger_level_changes_with_app_property_and_is_case_insensitive() { settings.getProps().set("sonar.log.level.app", "debug"); LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.DEBUG); } @Test public void default_to_INFO_if_app_property_has_invalid_value() { settings.getProps().set("sonar.log.level.app", "DodoDouh!"); LoggerContext ctx = underTest.configure(); verifyRootLogLevel(ctx, Level.INFO); } @Test public void fail_with_IAE_if_global_property_unsupported_level() { settings.getProps().set("sonar.log.level", "ERROR"); assertThatThrownBy(() -> underTest.configure()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_app_property_unsupported_level() { settings.getProps().set("sonar.log.level.app", "ERROR"); assertThatThrownBy(() -> underTest.configure()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.app is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void no_info_log_from_hazelcast() { settings.getProps().set(CLUSTER_ENABLED.getKey(), "true"); underTest.configure(); assertThat( LoggerFactory.getLogger("com.hazelcast").isInfoEnabled()).isFalse(); } @Test public void use_json_output() { settings.getProps().set("sonar.log.jsonOutput", "true"); LoggerContext ctx = underTest.configure(); Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); ConsoleAppender appender = (ConsoleAppender<ILoggingEvent>)rootLogger.getAppender("APP_CONSOLE"); Encoder<ILoggingEvent> encoder = appender.getEncoder(); assertThat(encoder).isInstanceOf(LayoutWrappingEncoder.class); assertThat(((LayoutWrappingEncoder)encoder).getLayout()).isInstanceOf(LogbackJsonLayout.class); } private void emulateRunFromCommandLine(boolean withAllLogsPrintedToConsole) { if (withAllLogsPrintedToConsole) { settings.getProps().set("sonar.log.console", "true"); } } private static void verifyNoFileAppender(Logger logger) { Iterator<Appender<ILoggingEvent>> iterator = logger.iteratorForAppenders(); while (iterator.hasNext()) { assertThat(iterator.next()).isNotInstanceOf(FileAppender.class); } } private void verifySonarLogFileAppender(Appender<ILoggingEvent> appender) { assertThat(appender).isInstanceOf(FileAppender.class); FileAppender fileAppender = (FileAppender) appender; assertThat(fileAppender.getFile()).isEqualTo(new File(logDir, "sonar.log").getAbsolutePath()); verifyAppFormattedLogEncoder(fileAppender.getEncoder()); } private void verifyAppConsoleAppender(Appender<ILoggingEvent> appender) { assertThat(appender).isInstanceOf(ConsoleAppender.class); ConsoleAppender<ILoggingEvent> consoleAppender = (ConsoleAppender<ILoggingEvent>) appender; assertThat(consoleAppender.getTarget()).isEqualTo(ConsoleTarget.SystemOut.getName()); verifyAppFormattedLogEncoder(consoleAppender.getEncoder()); } private void verifyAppFormattedLogEncoder(Encoder<ILoggingEvent> encoder) { verifyFormattedLogEncoder(encoder, "%d{yyyy.MM.dd HH:mm:ss} %-5level app[][%logger{20}] %msg%n"); } private void verifyGobblerConsoleAppender(Logger logger) { Appender<ILoggingEvent> appender = logger.getAppender("GOBBLER_CONSOLE"); assertThat(appender).isInstanceOf(ConsoleAppender.class); ConsoleAppender<ILoggingEvent> consoleAppender = (ConsoleAppender<ILoggingEvent>) appender; assertThat(consoleAppender.getTarget()).isEqualTo(ConsoleTarget.SystemOut.getName()); verifyFormattedLogEncoder(consoleAppender.getEncoder(), "%msg%n"); } private void verifyFormattedLogEncoder(Encoder<ILoggingEvent> encoder, String logPattern) { assertThat(encoder).isInstanceOf(PatternLayoutEncoder.class); PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) encoder; assertThat(patternEncoder.getPattern()).isEqualTo(logPattern); } private void verifyRootLogLevel(LoggerContext ctx, Level expected) { Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); assertThat(rootLogger.getLevel()).isEqualTo(expected); } }
11,709
36.89644
136
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AppReloaderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import com.google.common.collect.ImmutableMap; import java.io.IOException; import org.junit.Test; import org.sonar.application.config.AppSettings; import org.sonar.application.config.AppSettingsLoader; import org.sonar.application.config.TestAppSettings; import org.sonar.process.MessageException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class AppReloaderImplTest { private final AppSettingsLoader settingsLoader = mock(AppSettingsLoader.class); private final FileSystem fs = mock(FileSystem.class); private final AppState state = mock(AppState.class); private final AppLogging logging = mock(AppLogging.class); private final AppReloaderImpl underTest = new AppReloaderImpl(settingsLoader, fs, state, logging); @Test public void reload_configuration_then_reset_all() throws IOException { AppSettings settings = new TestAppSettings(ImmutableMap.of("foo", "bar")); AppSettings newSettings = new TestAppSettings(ImmutableMap.of("foo", "newBar", "newProp", "newVal")); when(settingsLoader.load()).thenReturn(newSettings); underTest.reload(settings); assertThat(settings.getProps().rawProperties()) .contains(entry("foo", "newBar")) .contains(entry("newProp", "newVal")); verify(logging).configure(); verify(state).reset(); verify(fs).reset(); } @Test public void throw_ISE_if_cluster_is_enabled() throws IOException { AppSettings settings = new TestAppSettings(ImmutableMap.of(CLUSTER_ENABLED.getKey(), "true")); assertThatThrownBy(() -> { underTest.reload(settings); verifyNoInteractions(logging); verifyNoInteractions(state); verifyNoInteractions(fs); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Restart is not possible with cluster mode"); } @Test public void throw_MessageException_if_path_properties_are_changed() throws IOException { verifyFailureIfPropertyValueChanged(PATH_DATA.getKey()); verifyFailureIfPropertyValueChanged(PATH_LOGS.getKey()); verifyFailureIfPropertyValueChanged(PATH_TEMP.getKey()); verifyFailureIfPropertyValueChanged(PATH_WEB.getKey()); } @Test public void throw_MessageException_if_cluster_mode_changed() throws IOException { verifyFailureIfPropertyValueChanged(CLUSTER_ENABLED.getKey()); } private void verifyFailureIfPropertyValueChanged(String propertyKey) throws IOException { AppSettings settings = new TestAppSettings(ImmutableMap.of(propertyKey, "val1")); AppSettings newSettings = new TestAppSettings(ImmutableMap.of(propertyKey, "val2")); when(settingsLoader.load()).thenReturn(newSettings); assertThatThrownBy(() -> { underTest.reload(settings); verifyNoInteractions(logging); verifyNoInteractions(state); verifyNoInteractions(fs); }) .isInstanceOf(MessageException.class) .hasMessage("Property [" + propertyKey + "] cannot be changed on restart: [val1] => [val2]"); } }
4,495
39.142857
105
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AppStateFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import com.google.common.collect.ImmutableMap; import java.net.InetAddress; import java.util.Optional; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.sonar.application.cluster.ClusterAppStateImpl; import org.sonar.application.config.TestAppSettings; import org.sonar.process.NetworkUtilsImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeThat; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; public class AppStateFactoryTest { @Test public void create_cluster_implementation_if_cluster_is_enabled() { Optional<InetAddress> ip = NetworkUtilsImpl.INSTANCE.getLocalNonLoopbackIpv4Address(); assumeThat(ip.isPresent(), CoreMatchers.is(true)); TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application") .put(CLUSTER_NODE_HOST.getKey(), ip.get().getHostAddress()) .put(CLUSTER_HZ_HOSTS.getKey(), ip.get().getHostAddress()) .put(CLUSTER_NAME.getKey(), "foo") .put(CLUSTER_SEARCH_HOSTS.getKey(), "localhost:9002") .build()); AppStateFactory underTest = new AppStateFactory(settings); AppState appState = underTest.create(); assertThat(appState).isInstanceOf(ClusterAppStateImpl.class); appState.close(); } @Test public void cluster_implementation_is_disabled_by_default() { TestAppSettings settings = new TestAppSettings(); AppStateFactory underTest = new AppStateFactory(settings); assertThat(underTest.create()).isInstanceOf(AppStateImpl.class); } }
2,919
41.318841
90
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/AppStateImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import org.junit.Test; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class AppStateImplTest { private AppStateListener listener = mock(AppStateListener.class); private AppStateImpl underTest = new AppStateImpl(); @Test public void get_and_set_operational_flag() { assertThat(underTest.isOperational(ProcessId.COMPUTE_ENGINE, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.ELASTICSEARCH, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.WEB_SERVER, true)).isFalse(); underTest.setOperational(ProcessId.ELASTICSEARCH); assertThat(underTest.isOperational(ProcessId.COMPUTE_ENGINE, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.ELASTICSEARCH, true)).isTrue(); assertThat(underTest.isOperational(ProcessId.WEB_SERVER, true)).isFalse(); // only local mode is supported. App state = local state assertThat(underTest.isOperational(ProcessId.COMPUTE_ENGINE, false)).isFalse(); assertThat(underTest.isOperational(ProcessId.ELASTICSEARCH, false)).isTrue(); assertThat(underTest.isOperational(ProcessId.WEB_SERVER, false)).isFalse(); } @Test public void notify_listeners_when_a_process_becomes_operational() { underTest.addListener(listener); underTest.setOperational(ProcessId.ELASTICSEARCH); verify(listener).onAppStateOperational(ProcessId.ELASTICSEARCH); verifyNoMoreInteractions(listener); } @Test public void tryToLockWebLeader_returns_true_if_first_call() { assertThat(underTest.tryToLockWebLeader()).isTrue(); // next calls return false assertThat(underTest.tryToLockWebLeader()).isFalse(); assertThat(underTest.tryToLockWebLeader()).isFalse(); } @Test public void reset_initializes_all_flags() { underTest.setOperational(ProcessId.ELASTICSEARCH); assertThat(underTest.tryToLockWebLeader()).isTrue(); underTest.reset(); assertThat(underTest.isOperational(ProcessId.ELASTICSEARCH, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.COMPUTE_ENGINE, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.WEB_SERVER, true)).isFalse(); assertThat(underTest.tryToLockWebLeader()).isTrue(); } }
3,271
37.494118
83
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/HardStopRequestWatcherImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class HardStopRequestWatcherImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); private ProcessCommands commands = mock(ProcessCommands.class); private Scheduler scheduler = mock(Scheduler.class); @Test public void watch_hard_stop_command() { HardStopRequestWatcherImpl underTest = new HardStopRequestWatcherImpl(scheduler, commands, 1); underTest.startWatching(); assertThat(underTest.isAlive()).isTrue(); verify(scheduler, never()).hardStop(); when(commands.askedForHardStop()).thenReturn(true); verify(scheduler, timeout(1_000L)).hardStop(); underTest.stopWatching(); await().until(() -> !underTest.isAlive()); assertThat(underTest.isAlive()).isFalse(); } @Test public void create_instance_with_default_delay() throws IOException { FileSystem fs = mock(FileSystem.class); when(fs.getTempDir()).thenReturn(temp.newFolder()); HardStopRequestWatcherImpl underTest = HardStopRequestWatcherImpl.create(scheduler, fs); assertThat(underTest.getDelayMs()).isEqualTo(500L); } @Test public void stop_watching_commands_if_thread_is_interrupted() { HardStopRequestWatcherImpl underTest = new HardStopRequestWatcherImpl(scheduler, commands); underTest.startWatching(); underTest.interrupt(); await().until(() -> !underTest.isAlive()); assertThat(underTest.isAlive()).isFalse(); } }
2,960
32.647727
98
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/NodeLifecycleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.application.NodeLifecycle.State.FINALIZE_STOPPING; import static org.sonar.application.NodeLifecycle.State.HARD_STOPPING; import static org.sonar.application.NodeLifecycle.State.INIT; import static org.sonar.application.NodeLifecycle.State.OPERATIONAL; import static org.sonar.application.NodeLifecycle.State.RESTARTING; import static org.sonar.application.NodeLifecycle.State.STARTING; import static org.sonar.application.NodeLifecycle.State.STOPPED; import static org.sonar.application.NodeLifecycle.State.STOPPING; @RunWith(DataProviderRunner.class) public class NodeLifecycleTest { private NodeLifecycle underTest = new NodeLifecycle(); @Test public void verify_regular_start_and_graceful_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test public void verify_regular_start_and_early_graceful_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test public void verify_start_and_hard_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(HARD_STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test public void verify_start_graceful_stop_interrupted_by_hard_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(STOPPING); verifyMoveTo(HARD_STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test public void verify_regular_start_restart_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(RESTARTING); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); } @Test public void verify_failed_restart_resulting_in_hard_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(RESTARTING); verifyMoveTo(HARD_STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test public void verify_failed_restart_even_if_FINALIZE_STOPPING_was_initiated_resulting_in_hard_stop_cycle() { assertThat(underTest.getState()).isEqualTo(INIT); verifyMoveTo(STARTING); verifyMoveTo(OPERATIONAL); verifyMoveTo(RESTARTING); verifyMoveTo(HARD_STOPPING); verifyMoveTo(FINALIZE_STOPPING); verifyMoveTo(STOPPED); } @Test @UseDataProvider("allStates") public void RESTARTING_is_only_allowed_from_STARTING_and_OPERATIONAL(NodeLifecycle.State state) { if (state == STARTING || state == OPERATIONAL) { verifyMoveTo(newNodeLifecycle(state), RESTARTING); } else { assertThat(newNodeLifecycle(state).tryToMoveTo(RESTARTING)).isFalse(); } } /** * Moving to stopped displays a log "SQ stopped" which must no appear when restarting */ @Test public void STOPPED_is_not_allowed_from_RESTARTING() { assertThat(newNodeLifecycle(RESTARTING).tryToMoveTo(STOPPED)).isFalse(); } /** * To go to STOPPED state, one must go through FINALIZE_STOPPING */ @Test @UseDataProvider("allStates") public void STOPPED_is_allowed_only_from_FINALIZE_STOPPING(NodeLifecycle.State state) { if (state == FINALIZE_STOPPING) { verifyMoveTo(newNodeLifecycle(state), STOPPED); } else { assertThat(newNodeLifecycle(state).tryToMoveTo(STOPPED)).isFalse(); } } @Test @UseDataProvider("allStates") public void FINALIZE_STOPPING_is_only_allowed_from_STOPPING_and_HARD_STOPPING(NodeLifecycle.State state) { if (state == STOPPING || state == HARD_STOPPING) { verifyMoveTo(newNodeLifecycle(state), FINALIZE_STOPPING); } else { assertThat(newNodeLifecycle(state).tryToMoveTo(FINALIZE_STOPPING)).isFalse(); } } @Test @UseDataProvider("allStates") public void cannot_move_to_any_state_from_STOPPED(NodeLifecycle.State state) { assertThat(newNodeLifecycle(STOPPED).tryToMoveTo(state)).isFalse(); } private void verifyMoveTo(NodeLifecycle.State newState) { verifyMoveTo(this.underTest, newState); } private void verifyMoveTo(NodeLifecycle lifecycle, NodeLifecycle.State newState) { assertThat(lifecycle.tryToMoveTo(newState)).isTrue(); assertThat(lifecycle.getState()).isEqualTo(newState); } /** * Creates a Lifecycle object in the specified state emulating that the shortest path to this state has been followed * to reach it. */ private static NodeLifecycle newNodeLifecycle(NodeLifecycle.State state) { switch (state) { case INIT: return new NodeLifecycle(); case STARTING: return newNodeLifecycle(INIT, state); case OPERATIONAL: return newNodeLifecycle(STARTING, state); case RESTARTING: return newNodeLifecycle(OPERATIONAL, state); case STOPPING: return newNodeLifecycle(OPERATIONAL, state); case HARD_STOPPING: return newNodeLifecycle(OPERATIONAL, state); case FINALIZE_STOPPING: return newNodeLifecycle(STOPPING, state); case STOPPED: return newNodeLifecycle(FINALIZE_STOPPING, state); default: throw new IllegalStateException("Missing state! " + state); } } private static NodeLifecycle newNodeLifecycle(NodeLifecycle.State from, NodeLifecycle.State to) { NodeLifecycle lifecycle = newNodeLifecycle(from); assertThat(lifecycle.tryToMoveTo(to)).isTrue(); return lifecycle; } @DataProvider public static Object[][] allStates() { return Arrays.stream(NodeLifecycle.State.values()) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } }
7,182
33.042654
119
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/ProcessLauncherImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.application.command.EsJvmOptions; import org.sonar.application.command.JavaCommand; import org.sonar.application.command.JvmOptions; import org.sonar.application.es.EsInstallation; import org.sonar.application.es.EsYmlSettings; import org.sonar.application.process.ManagedProcess; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.sharedmemoryfile.AllProcessesCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ProcessLauncherImplTest { @Rule public final TemporaryFolder temp = new TemporaryFolder(); private final AllProcessesCommands commands = mock(AllProcessesCommands.class, RETURNS_MOCKS); @Test public void launch_forks_a_new_process() throws Exception { File tempDir = temp.newFolder(); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); command.addClasspath("lib/*.class"); command.addClasspath("lib/*.jar"); command.setArgument("foo", "bar"); command.setClassName("org.sonarqube.Main"); command.setEnvVariable("VAR1", "valueOfVar1"); command.setJvmOptions(new JvmOptions<>() .add("-Dfoo=bar") .add("-Dfoo2=bar2")); command.setEsInstallation(createEsInstallation()); ManagedProcess monitor = underTest.launch(command); assertThat(monitor).isNotNull(); assertThat(processBuilder.started).isTrue(); assertThat(processBuilder.commands.get(0)).endsWith("java"); assertThat(processBuilder.commands).containsSubsequence( "-Dfoo=bar", "-Dfoo2=bar2", "-cp", "lib/*.class" + System.getProperty("path.separator") + "lib/*.jar", "org.sonarqube.Main"); assertThat(processBuilder.dir).isEqualTo(command.getWorkDir()); assertThat(processBuilder.redirectErrorStream).isTrue(); assertThat(processBuilder.environment) .contains(entry("VAR1", "valueOfVar1")) .containsAllEntriesOf(command.getEnvVariables()); } @Test public void enabling_es_security_should_execute_keystore_cli_if_cert_password_provided() throws Exception { File tempDir = temp.newFolder(); File certificateFile = temp.newFile("certificate.pk12"); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); EsInstallation esInstallation = createEsInstallation(new Props(new Properties()) .set("sonar.cluster.enabled", "true") .set("sonar.cluster.search.password", "bootstrap-password") .set("sonar.cluster.es.ssl.keystore", certificateFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.keystorePassword", "keystore-password") .set("sonar.cluster.es.ssl.truststore", certificateFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.truststorePassword", "truststore-password")); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); command.addClasspath("lib/*.class"); command.addClasspath("lib/*.jar"); command.setArgument("foo", "bar"); command.setClassName("org.sonarqube.Main"); command.setEnvVariable("VAR1", "valueOfVar1"); command.setJvmOptions(new JvmOptions<>() .add("-Dfoo=bar") .add("-Dfoo2=bar2")); command.setEsInstallation(esInstallation); ManagedProcess monitor = underTest.launch(command); assertThat(monitor).isNotNull(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "certificate.pk12")).exists(); } @Test public void enabling_es_security_should_execute_keystore_cli_if_no_cert_password_provided() throws Exception { File tempDir = temp.newFolder(); File certificateFile = temp.newFile("certificate.pk12"); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); EsInstallation esInstallation = createEsInstallation(new Props(new Properties()) .set("sonar.cluster.enabled", "true") .set("sonar.cluster.search.password", "bootstrap-password") .set("sonar.cluster.es.ssl.keystore", certificateFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.truststore", certificateFile.getAbsolutePath())); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); command.addClasspath("lib/*.class"); command.addClasspath("lib/*.jar"); command.setArgument("foo", "bar"); command.setClassName("org.sonarqube.Main"); command.setEnvVariable("VAR1", "valueOfVar1"); command.setJvmOptions(new JvmOptions<>() .add("-Dfoo=bar") .add("-Dfoo2=bar2")); command.setEsInstallation(esInstallation); ManagedProcess monitor = underTest.launch(command); assertThat(monitor).isNotNull(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "certificate.pk12")).exists(); } @Test public void enabling_es_security_should_execute_keystore_cli_if_truststore_and_keystore_provided() throws Exception { File tempDir = temp.newFolder(); File truststoreFile = temp.newFile("truststore.pk12"); File keystoreFile = temp.newFile("keystore.pk12"); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); EsInstallation esInstallation = createEsInstallation(new Props(new Properties()) .set("sonar.cluster.enabled", "true") .set("sonar.cluster.search.password", "bootstrap-password") .set("sonar.cluster.es.ssl.keystore", keystoreFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.keystorePassword", "keystore-password") .set("sonar.cluster.es.ssl.truststore", truststoreFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.truststorePassword", "truststore-password")); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); command.addClasspath("lib/*.class"); command.addClasspath("lib/*.jar"); command.setArgument("foo", "bar"); command.setClassName("org.sonarqube.Main"); command.setEnvVariable("VAR1", "valueOfVar1"); command.setJvmOptions(new JvmOptions<>() .add("-Dfoo=bar") .add("-Dfoo2=bar2")); command.setEsInstallation(esInstallation); ManagedProcess monitor = underTest.launch(command); assertThat(monitor).isNotNull(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "truststore.pk12")).exists(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "keystore.pk12")).exists(); } @Test public void launch_whenEnablingEsWithHttpEncryption_shouldCopyKeystoreToEsConf() throws Exception { File tempDir = temp.newFolder(); File certificateFile = temp.newFile("certificate.pk12"); File httpCertificateFile = temp.newFile("httpCertificate.pk12"); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); EsInstallation esInstallation = createEsInstallation(new Props(new Properties()) .set("sonar.cluster.enabled", "true") .set("sonar.cluster.search.password", "bootstrap-password") .set("sonar.cluster.es.ssl.keystore", certificateFile.getAbsolutePath()) .set("sonar.cluster.es.ssl.truststore", certificateFile.getAbsolutePath()) .set("sonar.cluster.es.http.ssl.keystore", httpCertificateFile.getAbsolutePath()) .set("sonar.cluster.es.http.ssl.keystorePassword", "keystore-password")); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); command.addClasspath("lib/*.class"); command.addClasspath("lib/*.jar"); command.setArgument("foo", "bar"); command.setClassName("org.sonarqube.Main"); command.setEnvVariable("VAR1", "valueOfVar1"); command.setJvmOptions(new JvmOptions<>() .add("-Dfoo=bar") .add("-Dfoo2=bar2")); command.setEsInstallation(esInstallation); ManagedProcess monitor = underTest.launch(command); assertThat(monitor).isNotNull(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "certificate.pk12")).exists(); assertThat(Paths.get(esInstallation.getConfDirectory().getAbsolutePath(), "httpCertificate.pk12")).exists(); } @Test public void properties_are_passed_to_command_via_a_temporary_properties_file() throws Exception { File tempDir = temp.newFolder(); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); long gracefulStopTimeoutMs = 1 + new Random().nextInt(10_000); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.WEB_SERVER, temp.newFolder()) .setReadsArgumentsFromFile(true) .setArgument("foo", "bar") .setArgument("baz", "woo") .setJvmOptions(new JvmOptions<>()) .setGracefulStopTimeoutMs(gracefulStopTimeoutMs); underTest.launch(command); String propsFilePath = processBuilder.commands.get(processBuilder.commands.size() - 1); File file = new File(propsFilePath); assertThat(file).exists().isFile(); try (FileReader reader = new FileReader(file)) { Properties props = new Properties(); props.load(reader); assertThat(props).containsOnly( entry("foo", "bar"), entry("baz", "woo"), entry("process.gracefulStopTimeout", gracefulStopTimeoutMs + ""), entry("process.key", ProcessId.WEB_SERVER.getKey()), entry("process.index", String.valueOf(ProcessId.WEB_SERVER.getIpcIndex())), entry("process.sharedDir", tempDir.getAbsolutePath())); } } @Test public void temporary_properties_file_can_be_avoided() throws Exception { File tempDir = temp.newFolder(); TestProcessBuilder processBuilder = new TestProcessBuilder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); JavaCommand<JvmOptions<?>> command = new JavaCommand<>(ProcessId.WEB_SERVER, temp.newFolder()); command.setReadsArgumentsFromFile(false); command.setArgument("foo", "bar"); command.setArgument("baz", "woo"); command.setJvmOptions(new JvmOptions<>()); underTest.launch(command); String propsFilePath = processBuilder.commands.get(processBuilder.commands.size() - 1); File file = new File(propsFilePath); assertThat(file).doesNotExist(); } @Test public void clean_up_old_es_data() throws Exception { File tempDir = temp.newFolder(); File homeDir = temp.newFolder(); File dataDir = temp.newFolder(); File logDir = temp.newFolder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, TestProcessBuilder::new); JavaCommand command = createEsCommand(tempDir, homeDir, dataDir, logDir); File outdatedEsDir = new File(dataDir, "es"); assertThat(outdatedEsDir.mkdir()).isTrue(); assertThat(outdatedEsDir).exists(); underTest.launch(command); assertThat(outdatedEsDir).doesNotExist(); } @Test public void do_not_fail_if_outdated_es_directory_does_not_exist() throws Exception { File tempDir = temp.newFolder(); File homeDir = temp.newFolder(); File dataDir = temp.newFolder(); File logDir = temp.newFolder(); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, TestProcessBuilder::new); JavaCommand command = createEsCommand(tempDir, homeDir, dataDir, logDir); File outdatedEsDir = new File(dataDir, "es"); assertThat(outdatedEsDir).doesNotExist(); underTest.launch(command); assertThat(outdatedEsDir).doesNotExist(); } @Test public void throw_ISE_if_command_fails() throws IOException { File tempDir = temp.newFolder(); ProcessLauncherImpl.ProcessBuilder processBuilder = mock(ProcessLauncherImpl.ProcessBuilder.class, RETURNS_MOCKS); when(processBuilder.start()).thenThrow(new IOException("error")); ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder); JavaCommand<?> javaCommand = new JavaCommand<>(ProcessId.ELASTICSEARCH, temp.newFolder()); assertThatThrownBy(() -> underTest.launch(javaCommand)) .isInstanceOf(IllegalStateException.class) .hasMessage("Fail to launch process [%s]", ProcessId.ELASTICSEARCH.getHumanReadableName()); } private JavaCommand<?> createEsCommand(File tempDir, File homeDir, File dataDir, File logDir) throws IOException { JavaCommand command = new JavaCommand(ProcessId.ELASTICSEARCH, temp.newFolder()); Props props = new Props(new Properties()); props.set("sonar.path.temp", tempDir.getAbsolutePath()); props.set("sonar.path.home", homeDir.getAbsolutePath()); props.set("sonar.path.data", dataDir.getAbsolutePath()); props.set("sonar.path.logs", logDir.getAbsolutePath()); command.setJvmOptions(mock(JvmOptions.class)); command.setEsInstallation(new EsInstallation(props) .setEsYmlSettings(mock(EsYmlSettings.class)) .setEsJvmOptions(mock(EsJvmOptions.class)) .setLog4j2Properties(new Properties()) .setHost("localhost") .setHttpPort(9001)); return command; } private EsInstallation createEsInstallation(Props props) throws IOException { File tempFolder = this.temp.newFolder("temp"); return new EsInstallation(props .set("sonar.path.home", this.temp.newFolder("home").getAbsolutePath()) .set("sonar.path.data", this.temp.newFolder("data").getAbsolutePath()) .set("sonar.path.temp", tempFolder.getAbsolutePath()) .set("sonar.path.logs", this.temp.newFolder("logs").getAbsolutePath())) .setHttpPort(9001) .setHost("localhost") .setEsYmlSettings(new EsYmlSettings(new HashMap<>())) .setEsJvmOptions(new EsJvmOptions(new Props(new Properties()), tempFolder)) .setLog4j2Properties(new Properties()); } private EsInstallation createEsInstallation() throws IOException { File tempFolder = this.temp.newFolder("temp"); return new EsInstallation(new Props(new Properties()) .set("sonar.path.home", this.temp.newFolder("home").getAbsolutePath()) .set("sonar.path.data", this.temp.newFolder("data").getAbsolutePath()) .set("sonar.path.temp", tempFolder.getAbsolutePath()) .set("sonar.path.logs", this.temp.newFolder("logs").getAbsolutePath())) .setHttpPort(9001) .setHost("localhost") .setEsYmlSettings(new EsYmlSettings(new HashMap<>())) .setEsJvmOptions(new EsJvmOptions(new Props(new Properties()), tempFolder)) .setLog4j2Properties(new Properties()); } private static class TestProcessBuilder implements ProcessLauncherImpl.ProcessBuilder { private List<String> commands = null; private File dir = null; private Boolean redirectErrorStream = null; private final Map<String, String> environment = new HashMap<>(); private boolean started = false; @Override public List<String> command() { return commands; } @Override public TestProcessBuilder command(List<String> commands) { this.commands = commands; return this; } @Override public TestProcessBuilder directory(File dir) { this.dir = dir; return this; } @Override public Map<String, String> environment() { return environment; } @Override public TestProcessBuilder redirectErrorStream(boolean b) { this.redirectErrorStream = b; return this; } @Override public Process start() { this.started = true; return mock(Process.class, RETURNS_MOCKS); } } }
17,374
42.221393
119
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.mockito.Mockito; import org.slf4j.LoggerFactory; import org.sonar.application.command.AbstractCommand; import org.sonar.application.command.CommandFactory; import org.sonar.application.command.JavaCommand; import org.sonar.application.config.AppSettings; import org.sonar.application.config.TestAppSettings; import org.sonar.application.process.ManagedProcess; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.HazelcastMember; import static com.google.common.collect.ImmutableMap.of; import static java.util.Collections.synchronizedList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.sonar.process.ProcessId.COMPUTE_ENGINE; import static org.sonar.process.ProcessId.ELASTICSEARCH; import static org.sonar.process.ProcessId.WEB_SERVER; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; public class SchedulerImplTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private Level initialLevel; private JavaCommand esCommand; private JavaCommand webLeaderCommand; private JavaCommand webFollowerCommand; private JavaCommand ceCommand; private final AppReloader appReloader = mock(AppReloader.class); private final TestCommandFactory javaCommandFactory = new TestCommandFactory(); private final TestProcessLauncher processLauncher = new TestProcessLauncher(); private final TestAppState appState = new TestAppState(); private final HazelcastMember hazelcastMember = mock(HazelcastMember.class); private final TestClusterAppState clusterAppState = new TestClusterAppState(hazelcastMember); private final List<ProcessId> orderedStops = synchronizedList(new ArrayList<>()); @Before public void setUp() throws Exception { File tempDir = temporaryFolder.newFolder(); esCommand = new JavaCommand(ELASTICSEARCH, tempDir); webLeaderCommand = new JavaCommand(WEB_SERVER, tempDir); webFollowerCommand = new JavaCommand(WEB_SERVER, tempDir); ceCommand = new JavaCommand(COMPUTE_ENGINE, tempDir); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); initialLevel = logger.getLevel(); logger.setLevel(Level.TRACE); } @After public void tearDown() { processLauncher.close(); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); logger.setLevel(initialLevel); } @Test public void start_and_stop_sequence_of_ES_WEB_CE_in_order() throws Exception { TestAppSettings settings = new TestAppSettings(); SchedulerImpl underTest = newScheduler(settings, false); underTest.schedule(); // elasticsearch does not have preconditions to start playAndVerifyStartupSequence(); // processes are stopped in reverse order of startup underTest.stop(); assertThat(orderedStops).containsExactly(COMPUTE_ENGINE, WEB_SERVER, ELASTICSEARCH); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); // does nothing because scheduler is already terminated underTest.awaitTermination(); } @Test public void start_and_hard_stop_sequence_of_ES_WEB_CE_in_order() throws Exception { TestAppSettings settings = new TestAppSettings(); SchedulerImpl underTest = newScheduler(settings, false); underTest.schedule(); playAndVerifyStartupSequence(); // processes are stopped in reverse order of startup underTest.hardStop(); assertThat(orderedStops).containsExactly(COMPUTE_ENGINE, WEB_SERVER, ELASTICSEARCH); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); // does nothing because scheduler is already terminated underTest.awaitTermination(); } @Test public void all_processes_are_stopped_if_one_process_goes_down() throws Exception { TestAppSettings settings = new TestAppSettings(); Scheduler underTest = startAll(settings); processLauncher.waitForProcess(WEB_SERVER).destroyForcibly(); underTest.awaitTermination(); assertThat(orderedStops).containsExactly(WEB_SERVER, COMPUTE_ENGINE, ELASTICSEARCH); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); // following does nothing underTest.hardStop(); underTest.awaitTermination(); } @Test public void all_processes_are_stopped_if_one_process_fails_to_start() throws Exception { TestAppSettings settings = new TestAppSettings(); SchedulerImpl underTest = newScheduler(settings, false); processLauncher.makeStartupFail = COMPUTE_ENGINE; underTest.schedule(); processLauncher.waitForProcess(ELASTICSEARCH).signalAsOperational(); processLauncher.waitForProcess(WEB_SERVER).signalAsOperational(); underTest.awaitTermination(); assertThat(orderedStops).containsExactly(WEB_SERVER, ELASTICSEARCH); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); } @Test public void terminate_can_be_called_multiple_times() throws Exception { TestAppSettings settings = new TestAppSettings(); Scheduler underTest = startAll(settings); underTest.hardStop(); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); // does nothing underTest.hardStop(); } @Test public void awaitTermination_blocks_until_all_processes_are_stopped() throws Exception { TestAppSettings settings = new TestAppSettings(); Scheduler underTest = startAll(settings); Thread awaitingTermination = new Thread(underTest::awaitTermination); awaitingTermination.start(); assertThat(awaitingTermination.isAlive()).isTrue(); underTest.hardStop(); // the thread is being stopped awaitingTermination.join(); assertThat(awaitingTermination.isAlive()).isFalse(); } @Test public void restart_stops_all_and_restarts_all_processes() throws InterruptedException, IOException { TestAppSettings settings = new TestAppSettings(); CountDownLatch restarting = new CountDownLatch(1); Scheduler underTest = startAll(settings); Mockito.doAnswer(t -> { orderedStops.clear(); appState.reset(); processLauncher.reset(); restarting.countDown(); return null; }) .when(appReloader).reload(settings); processLauncher.waitForProcess(WEB_SERVER).askedForRestart = true; // waiting for SQ to initiate restart restarting.await(); playAndVerifyStartupSequence(); underTest.stop(); assertThat(orderedStops).containsExactly(COMPUTE_ENGINE, WEB_SERVER, ELASTICSEARCH); processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isFalse()); // does nothing because scheduler is already terminated underTest.awaitTermination(); } @Test public void restart_stops_all_if_new_settings_are_not_allowed() throws Exception { AppSettings settings = new TestAppSettings(); Scheduler underTest = startAll(settings); doThrow(new IllegalStateException("reload error")).when(appReloader).reload(settings); processLauncher.waitForProcess(WEB_SERVER).askedForRestart = true; // waiting for all processes to be stopped processLauncher.waitForProcessDown(COMPUTE_ENGINE); processLauncher.waitForProcessDown(WEB_SERVER); processLauncher.waitForProcessDown(ELASTICSEARCH); // verify that awaitTermination() does not block underTest.awaitTermination(); } @Test public void search_node_starts_only_elasticsearch() throws Exception { AppSettings settings = new TestAppSettings( addRequiredNodeProperties(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search")).build()); SchedulerImpl underTest = newScheduler(settings, true); underTest.schedule(); processLauncher.waitForProcessAlive(ProcessId.ELASTICSEARCH); assertThat(processLauncher.processes).hasSize(1); underTest.hardStop(); } @Test public void application_node_starts_only_web_and_ce() throws Exception { AppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "true", CLUSTER_NODE_TYPE.getKey(), "application")); clusterAppState.setOperational(ProcessId.ELASTICSEARCH); SchedulerImpl underTest = newScheduler(settings, true); underTest.schedule(); processLauncher.waitForProcessAlive(WEB_SERVER).signalAsOperational(); processLauncher.waitForProcessAlive(COMPUTE_ENGINE); assertThat(processLauncher.processes).hasSize(2); underTest.hardStop(); } @Test public void search_node_starts_even_if_web_leader_is_not_yet_operational() throws Exception { AppSettings settings = new TestAppSettings( addRequiredNodeProperties(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search")).build()); // leader takes the lock, so underTest won't get it assertThat(clusterAppState.tryToLockWebLeader()).isTrue(); clusterAppState.setOperational(ProcessId.ELASTICSEARCH); SchedulerImpl underTest = newScheduler(settings, true); underTest.schedule(); processLauncher.waitForProcessAlive(ProcessId.ELASTICSEARCH); assertThat(processLauncher.processes).hasSize(1); underTest.hardStop(); } @Test public void web_follower_starts_only_when_web_leader_is_operational() throws Exception { AppSettings settings = new TestAppSettings( addRequiredNodeProperties(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application")).build()); // leader takes the lock, so underTest won't get it assertThat(clusterAppState.tryToLockWebLeader()).isTrue(); clusterAppState.setOperational(ProcessId.ELASTICSEARCH); SchedulerImpl underTest = newScheduler(settings, true); underTest.schedule(); assertThat(processLauncher.processes).isEmpty(); // leader becomes operational -> follower can start clusterAppState.setOperational(WEB_SERVER); processLauncher.waitForProcessAlive(WEB_SERVER); processLauncher.waitForProcessAlive(COMPUTE_ENGINE); assertThat(processLauncher.processes).hasSize(2); underTest.hardStop(); } @Test public void web_server_waits_for_remote_elasticsearch_to_be_started_if_local_es_is_disabled() throws Exception { AppSettings settings = new TestAppSettings( addRequiredNodeProperties(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application")).build()); SchedulerImpl underTest = newScheduler(settings, true); underTest.schedule(); // WEB and CE wait for ES to be up assertThat(processLauncher.processes).isEmpty(); // ES becomes operational on another node -> web leader can start clusterAppState.setRemoteOperational(ProcessId.ELASTICSEARCH); processLauncher.waitForProcessAlive(WEB_SERVER); assertThat(processLauncher.processes).hasSize(1); underTest.hardStop(); } private void playAndVerifyStartupSequence() throws InterruptedException { // elasticsearch does not have preconditions to start TestManagedProcess es = processLauncher.waitForProcess(ELASTICSEARCH); assertThat(es.isAlive()).isTrue(); assertThat(processLauncher.processes).hasSize(1); assertThat(processLauncher.commands).containsExactly(esCommand); // elasticsearch becomes operational -> web leader is starting es.signalAsOperational(); waitForAppStateOperational(appState, ELASTICSEARCH); TestManagedProcess web = processLauncher.waitForProcess(WEB_SERVER); assertThat(web.isAlive()).isTrue(); assertThat(processLauncher.processes).hasSize(2); assertThat(processLauncher.commands).containsExactly(esCommand, webLeaderCommand); // web becomes operational -> CE is starting web.signalAsOperational(); waitForAppStateOperational(appState, WEB_SERVER); TestManagedProcess ce = processLauncher.waitForProcess(COMPUTE_ENGINE).signalAsOperational(); assertThat(ce.isAlive()).isTrue(); assertThat(processLauncher.processes).hasSize(3); assertThat(processLauncher.commands).containsExactly(esCommand, webLeaderCommand, ceCommand); // all processes are up processLauncher.processes.values().forEach(p -> assertThat(p.isAlive()).isTrue()); } private SchedulerImpl newScheduler(AppSettings settings, boolean clustered) { return new SchedulerImpl(settings, appReloader, javaCommandFactory, processLauncher, clustered ? clusterAppState : appState) .setProcessWatcherDelayMs(1L); } private Scheduler startAll(AppSettings settings) throws InterruptedException { SchedulerImpl scheduler = newScheduler(settings, false); scheduler.schedule(); processLauncher.waitForProcess(ELASTICSEARCH).signalAsOperational(); processLauncher.waitForProcess(WEB_SERVER).signalAsOperational(); processLauncher.waitForProcess(COMPUTE_ENGINE).signalAsOperational(); return scheduler; } private static void waitForAppStateOperational(AppState appState, ProcessId id) throws InterruptedException { while (true) { if (appState.isOperational(id, true)) { return; } Thread.sleep(1L); } } private ImmutableMap.Builder<String, String> addRequiredNodeProperties(ImmutableMap.Builder<String, String> builder) { builder.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(4)); builder.put(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(4)); builder.put(CLUSTER_NODE_HZ_PORT.getKey(), String.valueOf(1 + new Random().nextInt(999))); return builder; } private class TestCommandFactory implements CommandFactory { @Override public JavaCommand createEsCommand() { return esCommand; } @Override public JavaCommand createWebCommand(boolean leader) { return leader ? webLeaderCommand : webFollowerCommand; } @Override public JavaCommand createCeCommand() { return ceCommand; } } private class TestProcessLauncher implements ProcessLauncher { private EnumMap<ProcessId, TestManagedProcess> processes; private List<AbstractCommand<?>> commands; private ProcessId makeStartupFail; public TestProcessLauncher() { reset(); } public TestProcessLauncher reset() { processes = new EnumMap<>(ProcessId.class); commands = synchronizedList(new ArrayList<>()); makeStartupFail = null; return this; } @Override public ManagedProcess launch(AbstractCommand command) { return launchImpl(command); } private ManagedProcess launchImpl(AbstractCommand<?> javaCommand) { commands.add(javaCommand); if (makeStartupFail == javaCommand.getProcessId()) { throw new IllegalStateException("Faking startup of java command failing for " + javaCommand.getProcessId()); } TestManagedProcess process = new TestManagedProcess(javaCommand.getProcessId()); processes.put(javaCommand.getProcessId(), process); return process; } private TestManagedProcess waitForProcess(ProcessId id) throws InterruptedException { while (true) { TestManagedProcess p = processes.get(id); if (p != null) { return p; } Thread.sleep(1L); } } private TestManagedProcess waitForProcessAlive(ProcessId id) throws InterruptedException { while (true) { TestManagedProcess p = processes.get(id); if (p != null && p.isAlive()) { return p; } Thread.sleep(1L); } } private TestManagedProcess waitForProcessDown(ProcessId id) throws InterruptedException { while (true) { TestManagedProcess p = processes.get(id); if (p != null && !p.isAlive()) { return p; } Thread.sleep(1L); } } @Override public void close() { for (TestManagedProcess process : processes.values()) { process.destroyForcibly(); } } } private class TestManagedProcess implements ManagedProcess, AutoCloseable { private final ProcessId processId; private CountDownLatch alive; private boolean operational; private boolean askedForRestart; private TestManagedProcess(ProcessId processId) { this.processId = processId; reset(); } private void reset() { alive = new CountDownLatch(1); operational = false; askedForRestart = false; } public TestManagedProcess signalAsOperational() { this.operational = true; return this; } @Override public InputStream getInputStream() { return mock(InputStream.class, Mockito.RETURNS_MOCKS); } @Override public InputStream getErrorStream() { return mock(InputStream.class, Mockito.RETURNS_MOCKS); } @Override public void closeStreams() { } @Override public boolean isAlive() { return alive.getCount() == 1; } @Override public void askForStop() { destroyForcibly(); } @Override public void askForHardStop() { destroyForcibly(); } @Override public void destroyForcibly() { if (isAlive()) { orderedStops.add(processId); } alive.countDown(); } @Override public void waitFor() throws InterruptedException { alive.await(); } @Override public void waitFor(long timeout, TimeUnit timeoutUnit) throws InterruptedException { alive.await(timeout, timeoutUnit); } @Override public boolean isOperational() { return operational; } @Override public boolean askedForRestart() { return askedForRestart; } @Override public void acknowledgeAskForRestart() { this.askedForRestart = false; } @Override public void close() { alive.countDown(); } } }
19,974
33.558824
128
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/StopRequestWatcherImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.application.config.TestAppSettings; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static com.google.common.collect.ImmutableMap.of; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.ENABLE_STOP_COMMAND; public class StopRequestWatcherImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); private final ProcessCommands commands = mock(ProcessCommands.class); private final Scheduler scheduler = mock(Scheduler.class); @Test public void startWatching_does_not_start_thread_if_stop_command_is_disabled() { TestAppSettings appSettings = new TestAppSettings(); StopRequestWatcherImpl underTest = new StopRequestWatcherImpl(appSettings, scheduler, commands); underTest.startWatching(); assertThat(underTest.isAlive()).isFalse(); } @Test public void watch_stop_command_if_stop_command_is_enabled() { TestAppSettings appSettings = new TestAppSettings(of(ENABLE_STOP_COMMAND.getKey(), "true")); StopRequestWatcherImpl underTest = new StopRequestWatcherImpl(appSettings, scheduler, commands); underTest.startWatching(); assertThat(underTest.isAlive()).isTrue(); verify(scheduler, never()).stop(); when(commands.askedForStop()).thenReturn(true); verify(scheduler, timeout(1_000L)).stop(); underTest.stopWatching(); await().until(() -> !underTest.isAlive()); assertThat(underTest.isAlive()).isFalse(); } @Test public void create_instance_with_default_delay() throws IOException { TestAppSettings appSettings = new TestAppSettings(); FileSystem fs = mock(FileSystem.class); when(fs.getTempDir()).thenReturn(temp.newFolder()); StopRequestWatcherImpl underTest = StopRequestWatcherImpl.create(appSettings, scheduler, fs); assertThat(underTest.getDelayMs()).isEqualTo(500L); } @Test public void stop_watching_commands_if_thread_is_interrupted() { TestAppSettings appSettings = new TestAppSettings(); StopRequestWatcherImpl underTest = new StopRequestWatcherImpl(appSettings, scheduler, commands); underTest.startWatching(); underTest.interrupt(); await().until(() -> !underTest.isAlive()); assertThat(underTest.isAlive()).isFalse(); } }
3,723
35.15534
100
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/TestAppState.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; public class TestAppState implements AppState { private final Map<ProcessId, Boolean> localProcesses = new EnumMap<>(ProcessId.class); private final Map<ProcessId, Boolean> remoteProcesses = new EnumMap<>(ProcessId.class); private final List<AppStateListener> listeners = new ArrayList<>(); private final AtomicBoolean webLeaderLocked = new AtomicBoolean(false); @Override public void addListener(@Nonnull AppStateListener listener) { this.listeners.add(listener); } @Override public boolean isOperational(ProcessId processId, boolean local) { if (local) { return localProcesses.computeIfAbsent(processId, p -> false); } return remoteProcesses.computeIfAbsent(processId, p -> false); } @Override public void setOperational(ProcessId processId) { localProcesses.put(processId, true); remoteProcesses.put(processId, true); listeners.forEach(l -> l.onAppStateOperational(processId)); } public void setRemoteOperational(ProcessId processId) { remoteProcesses.put(processId, true); listeners.forEach(l -> l.onAppStateOperational(processId)); } @Override public boolean tryToLockWebLeader() { return webLeaderLocked.compareAndSet(false, true); } @Override public void reset() { webLeaderLocked.set(false); localProcesses.clear(); remoteProcesses.clear(); } @Override public void registerSonarQubeVersion(String sonarqubeVersion) { // nothing to do } @Override public void registerClusterName(String clusterName) { // nothing to do } @Override public Optional<String> getLeaderHostName() { return Optional.of(NetworkUtilsImpl.INSTANCE.getHostname()); } @Override public void close() { // nothing to do } }
2,914
29.364583
89
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/TestClusterAppState.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import org.sonar.application.cluster.ClusterAppState; import org.sonar.process.cluster.hz.HazelcastMember; public class TestClusterAppState extends TestAppState implements ClusterAppState { private final HazelcastMember hazelcastMember; public TestClusterAppState(HazelcastMember hazelcastMember) { this.hazelcastMember = hazelcastMember; } @Override public HazelcastMember getHazelcastMember() { return hazelcastMember; } }
1,323
34.783784
82
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/cluster/AppNodesClusterHostsConsistencyTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster; import com.google.common.collect.ImmutableMap; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Cluster; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.cp.IAtomicReference; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.function.Consumer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonar.application.config.TestAppSettings; import org.sonar.process.cluster.hz.DistributedAnswer; import org.sonar.process.cluster.hz.DistributedCall; import org.sonar.process.cluster.hz.DistributedCallback; import org.sonar.process.cluster.hz.HazelcastMember; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; public class AppNodesClusterHostsConsistencyTest { @SuppressWarnings("unchecked") private final Consumer<String> logger = mock(Consumer.class); @Before @After public void setUp() { AppNodesClusterHostsConsistency.clearInstance(); } @Test public void log_warning_if_configured_hosts_are_not_consistent() throws UnknownHostException { Map<Member, List<String>> hostsPerMember = new LinkedHashMap<>(); Member m1 = newLocalHostMember(1, true); Member m2 = newLocalHostMember(2); Member m3 = newLocalHostMember(3); hostsPerMember.put(m2, Arrays.asList("1.1.1.1:1000", "1.1.1.1:2000")); hostsPerMember.put(m3, Arrays.asList("1.1.1.1:1000", "1.1.1.2:1000")); TestAppSettings settings = new TestAppSettings(ImmutableMap.of(CLUSTER_HZ_HOSTS.getKey(), "1.1.1.1:1000,1.1.1.1:2000,1.1.1.2:1000")); TestHazelcastMember member = new TestHazelcastMember(hostsPerMember, m1); AppNodesClusterHostsConsistency underTest = AppNodesClusterHostsConsistency.setInstance(member, settings, logger); underTest.check(); verify(logger).accept("The configuration of the current node doesn't match the list of hosts configured in the application nodes that have already joined the cluster:\n" + m1.getAddress().getHost() + ":" + m1.getAddress().getPort() + " : [1.1.1.1:1000, 1.1.1.1:2000, 1.1.1.2:1000] (current)\n" + m2.getAddress().getHost() + ":" + m2.getAddress().getPort() + " : [1.1.1.1:1000, 1.1.1.1:2000]\n" + m3.getAddress().getHost() + ":" + m3.getAddress().getPort() + " : [1.1.1.1:1000, 1.1.1.2:1000]\n" + "Make sure the configuration is consistent among all application nodes before you restart any node"); verifyNoMoreInteractions(logger); } @Test public void dont_log_if_configured_hosts_are_consistent() throws UnknownHostException { Map<Member, List<String>> hostsPerMember = new LinkedHashMap<>(); Member m1 = newLocalHostMember(1, true); Member m2 = newLocalHostMember(2); Member m3 = newLocalHostMember(3); hostsPerMember.put(m2, Arrays.asList("1.1.1.1:1000", "1.1.1.1:2000", "1.1.1.2:1000")); hostsPerMember.put(m3, Arrays.asList("1.1.1.1:1000", "1.1.1.1:2000", "1.1.1.2:1000")); TestAppSettings settings = new TestAppSettings(ImmutableMap.of(CLUSTER_HZ_HOSTS.getKey(), "1.1.1.1:1000,1.1.1.1:2000,1.1.1.2:1000")); TestHazelcastMember member = new TestHazelcastMember(hostsPerMember, m1); AppNodesClusterHostsConsistency underTest = AppNodesClusterHostsConsistency.setInstance(member, settings, logger); underTest.check(); verifyNoMoreInteractions(logger); } @Test public void setInstance_fails_with_ISE_when_called_twice_with_same_arguments() throws UnknownHostException { TestHazelcastMember member = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(1, true)); TestAppSettings settings = new TestAppSettings(); AppNodesClusterHostsConsistency.setInstance(member, settings); assertThatThrownBy(() -> AppNodesClusterHostsConsistency.setInstance(member, settings)) .isInstanceOf(IllegalStateException.class) .hasMessage("Instance is already set"); } @Test public void setInstance_fails_with_ISE_when_called_twice_with_other_arguments() throws UnknownHostException { TestHazelcastMember member1 = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(1, true)); TestHazelcastMember member2 = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(2, true)); AppNodesClusterHostsConsistency.setInstance(member1, new TestAppSettings()); assertThatThrownBy(() -> AppNodesClusterHostsConsistency.setInstance(member2, new TestAppSettings())) .isInstanceOf(IllegalStateException.class) .hasMessage("Instance is already set"); } private Member newLocalHostMember(int port) throws UnknownHostException { return newLocalHostMember(port, false); } private Member newLocalHostMember(int port, boolean localMember) throws UnknownHostException { Member member = mock(Member.class); when(member.localMember()).thenReturn(localMember); Address address1 = new Address(InetAddress.getLocalHost(), port); when(member.getAddress()).thenReturn(address1); return member; } private static class TestHazelcastMember implements HazelcastMember { private final Map<Member, List<String>> hostsPerMember; private final Cluster cluster = mock(Cluster.class); private TestHazelcastMember(Map<Member, List<String>> hostsPerMember, Member localMember) { this.hostsPerMember = hostsPerMember; when(cluster.getLocalMember()).thenReturn(localMember); } @Override public <E> IAtomicReference<E> getAtomicReference(String name) { throw new IllegalStateException("not expected to be called"); } @Override public <K, V> Map<K, V> getReplicatedMap(String name) { throw new IllegalStateException("not expected to be called"); } @Override public UUID getUuid() { throw new IllegalStateException("not expected to be called"); } @Override public Set<UUID> getMemberUuids() { throw new IllegalStateException("not expected to be called"); } @Override public Lock getLock(String name) { throw new IllegalStateException("not expected to be called"); } @Override public long getClusterTime() { throw new IllegalStateException("not expected to be called"); } @Override public Cluster getCluster() { return cluster; } @Override public <T> DistributedAnswer<T> call(DistributedCall<T> callable, MemberSelector memberSelector, long timeoutMs) { throw new IllegalStateException("not expected to be called"); } @Override public <T> void callAsync(DistributedCall<T> callable, MemberSelector memberSelector, DistributedCallback<T> callback) { callback.onComplete((Map<Member, T>) hostsPerMember); } @Override public void close() { } } }
8,116
38.985222
175
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/cluster/ClusterAppStateImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster; import java.net.InetAddress; import java.util.Optional; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.application.AppStateListener; import org.sonar.application.config.TestAppSettings; import org.sonar.application.es.EsConnector; import org.sonar.process.MessageException; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.cluster.hz.HazelcastMemberBuilder; import org.sonar.process.cluster.hz.JoinConfigurationType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.hz.HazelcastObjects.CLUSTER_NAME; import static org.sonar.process.cluster.hz.HazelcastObjects.SONARQUBE_VERSION; public class ClusterAppStateImplTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Test public void tryToLockWebLeader_returns_true_only_for_the_first_call() { try (ClusterAppStateImpl underTest = new ClusterAppStateImpl(new TestAppSettings(), newHzMember(), mock(EsConnector.class), mock(AppNodesClusterHostsConsistency.class))) { assertThat(underTest.tryToLockWebLeader()).isTrue(); assertThat(underTest.tryToLockWebLeader()).isFalse(); } } @Test public void test_listeners() { AppStateListener listener = mock(AppStateListener.class); try (ClusterAppStateImpl underTest = createClusterAppState()) { underTest.addListener(listener); underTest.setOperational(ProcessId.ELASTICSEARCH); verify(listener, timeout(20_000)).onAppStateOperational(ProcessId.ELASTICSEARCH); assertThat(underTest.isOperational(ProcessId.ELASTICSEARCH, true)).isTrue(); assertThat(underTest.isOperational(ProcessId.APP, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.WEB_SERVER, true)).isFalse(); assertThat(underTest.isOperational(ProcessId.COMPUTE_ENGINE, true)).isFalse(); } } @Test public void check_if_elasticsearch_is_operational_on_cluster() { AppStateListener listener = mock(AppStateListener.class); EsConnector esConnectorMock = mock(EsConnector.class); when(esConnectorMock.getClusterHealthStatus()) .thenReturn(Optional.empty()) .thenReturn(Optional.of(ClusterHealthStatus.RED)) .thenReturn(Optional.of(ClusterHealthStatus.GREEN)); try (ClusterAppStateImpl underTest = createClusterAppState(esConnectorMock)) { underTest.addListener(listener); underTest.isOperational(ProcessId.ELASTICSEARCH, false); //wait until undergoing thread marks ES as operational verify(listener, timeout(20_000)).onAppStateOperational(ProcessId.ELASTICSEARCH); } } @Test public void constructor_checks_appNodesClusterHostsConsistency() { AppNodesClusterHostsConsistency clusterHostsConsistency = mock(AppNodesClusterHostsConsistency.class); try (ClusterAppStateImpl underTest = new ClusterAppStateImpl(new TestAppSettings(), newHzMember(), mock(EsConnector.class), clusterHostsConsistency)) { verify(clusterHostsConsistency).check(); } } @Test public void registerSonarQubeVersion_publishes_version_on_first_call() { try (ClusterAppStateImpl underTest = createClusterAppState()) { underTest.registerSonarQubeVersion("6.4.1.5"); assertThat(underTest.getHazelcastMember().getAtomicReference(SONARQUBE_VERSION).get()) .isEqualTo("6.4.1.5"); } } @Test public void registerClusterName_publishes_clusterName_on_first_call() { try (ClusterAppStateImpl underTest = createClusterAppState()) { underTest.registerClusterName("foo"); assertThat(underTest.getHazelcastMember().getAtomicReference(CLUSTER_NAME).get()) .isEqualTo("foo"); } } @Test public void reset_always_throws_ISE() { try (ClusterAppStateImpl underTest = createClusterAppState()) { assertThatThrownBy(underTest::reset) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("state reset is not supported in cluster mode"); } } @Test public void registerSonarQubeVersion_throws_ISE_if_initial_version_is_different() { // Now launch an instance that try to be part of the hzInstance cluster try (ClusterAppStateImpl underTest = createClusterAppState()) { // Register first version underTest.getHazelcastMember().getAtomicReference(SONARQUBE_VERSION).set("6.6.0.1111"); // Registering a second different version must trigger an exception assertThatThrownBy(() -> underTest.registerSonarQubeVersion("6.7.0.9999")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("The local version 6.7.0.9999 is not the same as the cluster 6.6.0.1111"); } } @Test public void registerClusterName_throws_MessageException_if_clusterName_is_different() { try (ClusterAppStateImpl underTest = createClusterAppState()) { // Register first version underTest.getHazelcastMember().getAtomicReference(CLUSTER_NAME).set("goodClusterName"); // Registering a second different cluster name must trigger an exception assertThatThrownBy(() -> underTest.registerClusterName("badClusterName")) .isInstanceOf(MessageException.class) .hasMessage("This node has a cluster name [badClusterName], which does not match [goodClusterName] from the cluster"); } } @Test public void return_hostname_if_node_is_leader() { try (ClusterAppStateImpl underTest = createClusterAppState()) { underTest.tryToLockWebLeader(); Optional<String> hostname = underTest.getLeaderHostName(); assertThat(hostname).isNotEmpty(); } } @Test public void return_null_if_node_is_not_leader() { try (ClusterAppStateImpl underTest = createClusterAppState()) { Optional<String> hostname = underTest.getLeaderHostName(); assertThat(hostname).isEmpty(); } } private ClusterAppStateImpl createClusterAppState() { return createClusterAppState(mock(EsConnector.class)); } private ClusterAppStateImpl createClusterAppState(EsConnector esConnector) { return new ClusterAppStateImpl(new TestAppSettings(), newHzMember(), esConnector, mock(AppNodesClusterHostsConsistency.class)); } private static HazelcastMember newHzMember() { // use loopback for support of offline builds InetAddress loopback = InetAddress.getLoopbackAddress(); return new HazelcastMemberBuilder(JoinConfigurationType.TCP_IP) .setProcessId(ProcessId.COMPUTE_ENGINE) .setNodeName("bar") .setPort(NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort()) .setMembers(loopback.getHostAddress()) .setNetworkInterface(loopback.getHostAddress()) .build(); } }
8,037
38.99005
131
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/cluster/ClusterProcessTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster; import java.util.UUID; import org.junit.Test; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; public class ClusterProcessTest { @Test public void test_equality() { UUID nodeUuid = UUID.randomUUID(); ClusterProcess clusterProcess = new ClusterProcess(nodeUuid, ProcessId.WEB_SERVER); assertThat(clusterProcess) .isNotNull() .isEqualTo(clusterProcess) .isNotEqualTo(new ClusterProcess(UUID.randomUUID(), ProcessId.WEB_SERVER)) .isNotEqualTo(new ClusterProcess(nodeUuid, ProcessId.ELASTICSEARCH)) .isEqualTo(new ClusterProcess(nodeUuid, ProcessId.WEB_SERVER)); } }
1,542
35.738095
87
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/cluster/health/DelegateHealthStateRefresherExecutorServiceTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster.health; import java.util.Collection; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.IntStream; import org.junit.Test; import static java.util.concurrent.TimeUnit.SECONDS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class DelegateHealthStateRefresherExecutorServiceTest { private Random random = new Random(); private Runnable runnable = mock(Runnable.class); private Callable callable = mock(Callable.class); private Collection<Callable<Object>> callables = IntStream.range(0, random.nextInt(5)) .mapToObj(i -> (Callable<Object>) mock(Callable.class)) .toList(); private int initialDelay = random.nextInt(333); private int delay = random.nextInt(333); private int period = random.nextInt(333); private int timeout = random.nextInt(333); private Object result = new Object(); private ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); private DelegateHealthStateRefresherExecutorService underTest = new DelegateHealthStateRefresherExecutorService(executorService); @Test public void schedule() { underTest.schedule(runnable, delay, SECONDS); verify(executorService).schedule(runnable, delay, SECONDS); } @Test public void schedule1() { underTest.schedule(callable, delay, SECONDS); verify(executorService).schedule(callable, delay, SECONDS); } @Test public void scheduleAtFixedRate() { underTest.scheduleAtFixedRate(runnable, initialDelay, period, SECONDS); verify(executorService).scheduleAtFixedRate(runnable, initialDelay, period, SECONDS); } @Test public void scheduleWithFixeddelay() { underTest.scheduleWithFixedDelay(runnable, initialDelay, delay, TimeUnit.SECONDS); verify(executorService).scheduleWithFixedDelay(runnable, initialDelay, delay, TimeUnit.SECONDS); } @Test public void shutdown() { underTest.shutdown(); verify(executorService).shutdown(); } @Test public void shutdownNow() { underTest.shutdownNow(); verify(executorService).shutdownNow(); } @Test public void isShutdown() { underTest.isShutdown(); verify(executorService).isShutdown(); } @Test public void isTerminated() { underTest.isTerminated(); verify(executorService).isTerminated(); } @Test public void awaitTermination() throws InterruptedException { underTest.awaitTermination(timeout, TimeUnit.SECONDS); verify(executorService).awaitTermination(timeout, TimeUnit.SECONDS); } @Test public void submit() { underTest.submit(callable); verify(executorService).submit(callable); } @Test public void submit1() { underTest.submit(runnable, result); verify(executorService).submit(runnable, result); } @Test public void submit2() { underTest.submit(runnable); verify(executorService).submit(runnable); } @Test public void invokeAll() throws InterruptedException { underTest.invokeAll(callables); verify(executorService).invokeAll(callables); } @Test public void invokeAll1() throws InterruptedException { underTest.invokeAll(callables, timeout, SECONDS); verify(executorService).invokeAll(callables, timeout, SECONDS); } @Test public void invokeAny() throws InterruptedException, ExecutionException { underTest.invokeAny(callables); verify(executorService).invokeAny(callables); } @Test public void invokeAny2() throws InterruptedException, ExecutionException, TimeoutException { underTest.invokeAny(callables, timeout, SECONDS); verify(executorService).invokeAny(callables, timeout, SECONDS); } }
4,732
29.934641
131
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster.health; import java.util.Properties; import java.util.Random; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.application.cluster.ClusterAppState; import org.sonar.process.NetworkUtils; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.cluster.health.NodeHealth; import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; public class SearchNodeHealthProviderTest { private final Random random = new Random(); private SearchNodeHealthProvider.Clock clock = mock(SearchNodeHealthProvider.Clock.class); private NetworkUtils networkUtils = mock(NetworkUtils.class); private ClusterAppState clusterAppState = mock(ClusterAppState.class); @Test public void constructor_throws_IAE_if_property_node_name_is_not_set() { Props props = new Props(new Properties()); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property: sonar.cluster.node.name"); } @Test public void constructor_throws_NPE_if_NetworkUtils_getHostname_returns_null_and_property_is_not_set() { Properties properties = new Properties(); properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_IAE_if_property_node_port_is_not_set() { Properties properties = new Properties(); properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property: sonar.cluster.node.port"); } @Test public void constructor_throws_FormatException_if_property_node_port_is_not_an_integer() { String port = randomAlphabetic(3); Properties properties = new Properties(); properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); properties.put(CLUSTER_NODE_HZ_PORT.getKey(), port); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) .isInstanceOf(NumberFormatException.class) .hasMessage("For input string: \"" + port + "\""); } @Test public void get_returns_name_and_port_from_properties_at_constructor_time() { String name = randomAlphanumeric(3); int port = 1 + random.nextInt(4); Properties properties = new Properties(); properties.setProperty(CLUSTER_NODE_NAME.getKey(), name); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(port)); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); when(clock.now()).thenReturn(1L + random.nextInt(87)); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getName()).isEqualTo(name); assertThat(nodeHealth.getDetails().getPort()).isEqualTo(port); // change values in properties properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(6)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(99))); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getName()).isEqualTo(name); assertThat(newNodeHealth.getDetails().getPort()).isEqualTo(port); } @Test public void get_returns_host_from_property_if_set_at_constructor_time() { String host = randomAlphanumeric(55); Properties properties = new Properties(); properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); properties.setProperty(CLUSTER_NODE_HOST.getKey(), host); when(clock.now()).thenReturn(1L + random.nextInt(87)); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change now properties.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(96)); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getHost()).isEqualTo(host); } @Test public void get_returns_host_from_NetworkUtils_getHostname_if_property_is_not_set_at_constructor_time() { getReturnsHostFromNetworkUtils(null); } @Test public void get_returns_host_from_NetworkUtils_getHostname_if_property_is_empty_at_constructor_time() { getReturnsHostFromNetworkUtils(random.nextBoolean() ? "" : " "); } private void getReturnsHostFromNetworkUtils(@Nullable String hostPropertyValue) { String host = randomAlphanumeric(34); Properties properties = new Properties(); properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); if (hostPropertyValue != null) { properties.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue); } when(clock.now()).thenReturn(1L + random.nextInt(87)); when(networkUtils.getHostname()).thenReturn(host); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change now when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(96)); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getHost()).isEqualTo(host); } @Test public void get_returns_started_from_System2_now_at_constructor_time() { Properties properties = new Properties(); long now = setRequiredPropertiesAndMocks(properties); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getStartedAt()).isEqualTo(now); // change now when(clock.now()).thenReturn(now); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getStartedAt()).isEqualTo(now); } @Test public void get_returns_status_GREEN_if_elasticsearch_process_is_operational_in_ClusterAppState() { Properties properties = new Properties(); setRequiredPropertiesAndMocks(properties); when(clusterAppState.isOperational(ProcessId.ELASTICSEARCH, true)).thenReturn(true); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getStatus()).isEqualTo(NodeHealth.Status.GREEN); } @Test public void get_returns_status_RED_with_cause_if_elasticsearch_process_is_not_operational_in_ClusterAppState() { Properties properties = new Properties(); setRequiredPropertiesAndMocks(properties); when(clusterAppState.isOperational(ProcessId.ELASTICSEARCH, true)).thenReturn(false); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getStatus()).isEqualTo(NodeHealth.Status.RED); assertThat(nodeHealth.getCauses()).containsOnly("Elasticsearch is not operational"); } private long setRequiredPropertiesAndMocks(Properties properties) { properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); long now = 1L + random.nextInt(87); when(clock.now()).thenReturn(now); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); return now; } }
9,910
42.279476
131
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.sonar.process.ProcessId; import org.sonar.process.System2; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; public class AbstractCommandTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void constructor_throws_NPE_of_ProcessId_is_null() throws IOException { assertThatThrownBy(() -> { new AbstractCommand<AbstractCommand>(null, temp.newFolder(), System2.INSTANCE) { }; }) .isInstanceOf(NullPointerException.class) .hasMessage("ProcessId can't be null"); } @Test public void constructor_throws_NPE_of_workDir_is_null() { assertThatThrownBy(() -> { new AbstractCommand<AbstractCommand>(ProcessId.WEB_SERVER, null, System2.INSTANCE) { }; }) .isInstanceOf(NullPointerException.class) .hasMessage("workDir can't be null"); } @Test public void setEnvVariable_fails_with_NPE_if_key_is_null() throws IOException { File workDir = temp.newFolder(); AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, System2.INSTANCE) { }; assertThatThrownBy(() -> underTest.setEnvVariable(null, randomAlphanumeric(30))) .isInstanceOf(NullPointerException.class) .hasMessage("key can't be null"); } @Test public void setEnvVariable_fails_with_NPE_if_value_is_null() throws IOException { File workDir = temp.newFolder(); AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, System2.INSTANCE) { }; assertThatThrownBy(() -> underTest.setEnvVariable(randomAlphanumeric(30), null)) .isInstanceOf(NullPointerException.class) .hasMessage("value can't be null"); } @Test public void constructor_puts_System_getEnv_into_map_of_env_variables() throws IOException { File workDir = temp.newFolder(); System2 system2 = Mockito.mock(System2.class); Map<String, String> env = IntStream.range(0, 1 + new Random().nextInt(99)).mapToObj(String::valueOf).collect(Collectors.toMap(i -> "key" + i, j -> "value" + j)); when(system2.getenv()).thenReturn(env); AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, system2) { }; assertThat(underTest.getEnvVariables()).isEqualTo(env); } @Test public void suppressEnvVariable_remove_existing_env_variable_and_add_variable_to_set_of_suppressed_variables() throws IOException { File workDir = temp.newFolder(); System2 system2 = Mockito.mock(System2.class); Map<String, String> env = new HashMap<>(); String key1 = randomAlphanumeric(3); env.put(key1, randomAlphanumeric(9)); when(system2.getenv()).thenReturn(env); AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, system2) { }; underTest.suppressEnvVariable(key1); assertThat(underTest.getEnvVariables()).doesNotContainKey(key1); assertThat(underTest.getSuppressedEnvVariables()).containsOnly(key1); } }
4,346
34.056452
165
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/CeJvmOptionsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import java.io.File; import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; public class CeJvmOptionsTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private File tmpDir; private CeJvmOptions underTest; @Before public void setUp() throws IOException { tmpDir = temporaryFolder.newFolder(); } @Test public void constructor_sets_mandatory_JVM_options() { underTest = new CeJvmOptions(tmpDir); assertThat(underTest.getAll()).containsExactly( "-Djava.awt.headless=true", "-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=" + tmpDir.getAbsolutePath(), "-XX:-OmitStackTraceInFastThrow", "--add-opens=java.base/java.util=ALL-UNNAMED", "--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED", "--add-opens=java.base/java.lang=ALL-UNNAMED", "--add-opens=java.base/java.nio=ALL-UNNAMED", "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens=java.management/sun.management=ALL-UNNAMED", "--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED", "-Dcom.redhat.fips=false"); } }
2,122
35.603448
140
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/CommandFactoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import ch.qos.logback.classic.spi.ILoggingEvent; import com.google.common.collect.ImmutableSet; import java.io.File; import java.io.IOException; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.sonar.application.es.EsInstallation; import org.sonar.application.logging.ListAppender; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.process.System2; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CommandFactoryImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private System2 system2 = Mockito.mock(System2.class); private File homeDir; private File tempDir; private File logsDir; private ListAppender listAppender; @Before public void setUp() throws Exception { homeDir = temp.newFolder(); tempDir = temp.newFolder(); logsDir = temp.newFolder(); } @After public void tearDown() { if (listAppender != null) { ListAppender.detachMemoryAppenderToLoggerOf(CommandFactoryImpl.class, listAppender); } } @Test public void constructor_logs_no_warning_if_env_variable_JAVA_TOOL_OPTIONS_is_not_set() { attachMemoryAppenderToLoggerOf(CommandFactoryImpl.class); new CommandFactoryImpl(new Props(new Properties()), tempDir, system2); assertThat(listAppender.getLogs()).isEmpty(); } @Test public void constructor_logs_warning_if_env_variable_JAVA_TOOL_OPTIONS_is_set() { when(system2.getenv("JAVA_TOOL_OPTIONS")).thenReturn("sds"); attachMemoryAppenderToLoggerOf(CommandFactoryImpl.class); new CommandFactoryImpl(new Props(new Properties()), tempDir, system2); assertThat(listAppender.getLogs()) .extracting(ILoggingEvent::getMessage) .containsOnly( "JAVA_TOOL_OPTIONS is defined but will be ignored. " + "Use properties sonar.*.javaOpts and/or sonar.*.javaAdditionalOpts in sonar.properties to change SQ JVM processes options"); } @Test public void constructor_logs_warning_if_env_variable_ES_JAVA_OPTS_is_set() { when(system2.getenv("ES_JAVA_OPTS")).thenReturn("xyz"); attachMemoryAppenderToLoggerOf(CommandFactoryImpl.class); new CommandFactoryImpl(new Props(new Properties()), tempDir, system2); assertThat(listAppender.getLogs()) .extracting(ILoggingEvent::getMessage) .containsOnly( "ES_JAVA_OPTS is defined but will be ignored. " + "Use properties sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to change SQ JVM processes options"); } @Test public void createEsCommand_for_unix_returns_command_for_default_settings() throws Exception { when(system2.isOsWindows()).thenReturn(false); prepareEsFileSystem(); Properties props = new Properties(); props.setProperty("sonar.search.host", "localhost"); JavaCommand<?> esCommand = newFactory(props, system2).createEsCommand(); EsInstallation esConfig = esCommand.getEsInstallation(); assertThat(esConfig.getHost()).isNotEmpty(); assertThat(esConfig.getHttpPort()).isEqualTo(9001); assertThat(esConfig.getEsJvmOptions().getAll()) // enforced values .contains("-XX:+UseG1GC") .contains("-Dfile.encoding=UTF-8") // default settings .contains("-Xms512m", "-Xmx512m", "-XX:+HeapDumpOnOutOfMemoryError"); assertThat(esConfig.getEsYmlSettings()).isNotNull(); assertThat(esConfig.getLog4j2Properties()) .contains(entry("appender.file_es.fileName", new File(logsDir, "es.log").getAbsolutePath())); assertThat(esCommand.getEnvVariables()) .containsKey("ES_JAVA_HOME"); assertThat(esCommand.getJvmOptions().getAll()) .contains("-Xms4m", "-Xmx64m", "-XX:+UseSerialGC", "-Dcli.name=server", "-Dcli.script=./bin/elasticsearch", "-Dcli.libs=lib/tools/server-cli", "-Des.path.home=" + esConfig.getHomeDirectory().getAbsolutePath(), "-Des.path.conf=" + esConfig.getConfDirectory().getAbsolutePath(), "-Des.distribution.type=tar"); } @Test public void createEsCommand_returns_command_for_overridden_settings() throws Exception { prepareEsFileSystem(); Properties props = new Properties(); props.setProperty("sonar.search.host", "localhost"); props.setProperty("sonar.cluster.name", "foo"); props.setProperty("sonar.search.port", "1234"); props.setProperty("sonar.search.javaOpts", "-Xms10G -Xmx10G"); AbstractCommand esCommand = newFactory(props).createEsCommand(); EsInstallation esConfig = esCommand.getEsInstallation(); assertThat(esConfig.getHttpPort()).isEqualTo(1234); assertThat(esConfig.getEsJvmOptions().getAll()) // enforced values .contains("-XX:+UseG1GC") .contains("-Dfile.encoding=UTF-8") .contains("-Djava.io.tmpdir=" + tempDir.getAbsolutePath()) // user settings .contains("-Xms10G", "-Xmx10G") // default values disabled .doesNotContain("-XX:+HeapDumpOnOutOfMemoryError"); } @Test public void createWebCommand_returns_command_for_default_settings() { JavaCommand command = newFactory(new Properties()).createWebCommand(true); assertThat(command.getClassName()).isEqualTo("org.sonar.server.app.WebServer"); assertThat(command.getWorkDir().getAbsolutePath()).isEqualTo(homeDir.getAbsolutePath()); assertThat(command.getClasspath()).hasSize(1).allMatch(p -> p.toString().startsWith("./lib/sonar-application-")); assertThat(command.getJvmOptions().getAll()) // enforced values .contains("-Djava.awt.headless=true", "-Dfile.encoding=UTF-8") // default settings .contains("-Djava.io.tmpdir=" + tempDir.getAbsolutePath(), "-Dfile.encoding=UTF-8") .contains("-Xmx512m", "-Xms128m", "-XX:+HeapDumpOnOutOfMemoryError"); assertThat(command.getProcessId()).isEqualTo(ProcessId.WEB_SERVER); assertThat(command.getEnvVariables()) .isNotEmpty(); assertThat(command.getArguments()) // default settings .contains(entry("sonar.web.javaOpts", "-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError")) .contains(entry("sonar.cluster.enabled", "false")); assertThat(command.getSuppressedEnvVariables()).containsOnly("JAVA_TOOL_OPTIONS"); } @Test public void createCeCommand_returns_command_for_default_settings() { JavaCommand command = newFactory(new Properties()).createCeCommand(); assertThat(command.getClassName()).isEqualTo("org.sonar.ce.app.CeServer"); assertThat(command.getWorkDir().getAbsolutePath()).isEqualTo(homeDir.getAbsolutePath()); assertThat(command.getClasspath()).hasSize(1).allMatch(p -> p.toString().startsWith("./lib/sonar-application-")); assertThat(command.getJvmOptions().getAll()) // enforced values .contains("-Djava.awt.headless=true", "-Dfile.encoding=UTF-8") // default settings .contains("-Djava.io.tmpdir=" + tempDir.getAbsolutePath(), "-Dfile.encoding=UTF-8") .contains("-Xmx512m", "-Xms128m", "-XX:+HeapDumpOnOutOfMemoryError"); assertThat(command.getProcessId()).isEqualTo(ProcessId.COMPUTE_ENGINE); assertThat(command.getEnvVariables()) .isNotEmpty(); assertThat(command.getArguments()) // default settings .contains(entry("sonar.web.javaOpts", "-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError")) .contains(entry("sonar.cluster.enabled", "false")); assertThat(command.getSuppressedEnvVariables()).containsOnly("JAVA_TOOL_OPTIONS"); } @Test public void createWebCommand_configures_command_with_overridden_settings() { Properties props = new Properties(); props.setProperty("sonar.web.port", "1234"); props.setProperty("sonar.web.javaOpts", "-Xmx10G"); JavaCommand command = newFactory(props).createWebCommand(true); assertThat(command.getJvmOptions().getAll()) // enforced values .contains("-Djava.awt.headless=true", "-Dfile.encoding=UTF-8") // default settings .contains("-Djava.io.tmpdir=" + tempDir.getAbsolutePath(), "-Dfile.encoding=UTF-8") // overridden values .contains("-Xmx10G") .doesNotContain("-Xms128m", "-XX:+HeapDumpOnOutOfMemoryError"); assertThat(command.getArguments()) // default settings .contains(entry("sonar.web.javaOpts", "-Xmx10G")) .contains(entry("sonar.cluster.enabled", "false")); assertThat(command.getSuppressedEnvVariables()).containsOnly("JAVA_TOOL_OPTIONS"); } @Test public void createWebCommand_adds_configured_jdbc_driver_to_classpath() throws Exception { Properties props = new Properties(); File driverFile = temp.newFile(); props.setProperty("sonar.jdbc.driverPath", driverFile.getAbsolutePath()); JavaCommand command = newFactory(props).createWebCommand(true); assertThat(command.getClasspath()).hasSize(2); assertThat(command.getClasspath().get(0).toString()).startsWith("./lib/sonar-application-"); assertThat(command.getClasspath().get(1)).isEqualTo(driverFile.getAbsolutePath()); } private void prepareEsFileSystem() throws IOException { FileUtils.touch(new File(homeDir, "elasticsearch/bin/elasticsearch")); FileUtils.touch(new File(homeDir, "elasticsearch/bin/elasticsearch.bat")); } private CommandFactoryImpl newFactory(Properties userProps) { return newFactory(userProps, System2.INSTANCE); } private CommandFactoryImpl newFactory(Properties userProps, System2 system2) { Properties p = new Properties(); p.setProperty("sonar.path.home", homeDir.getAbsolutePath()); p.setProperty("sonar.path.temp", tempDir.getAbsolutePath()); p.setProperty("sonar.path.logs", logsDir.getAbsolutePath()); p.putAll(userProps); Props props = new Props(p); ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of()); new ProcessProperties(serviceLoaderWrapper).completeDefaults(props); return new CommandFactoryImpl(props, tempDir, system2); } private <T> void attachMemoryAppenderToLoggerOf(Class<T> loggerClass) { this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(loggerClass); } }
11,403
40.169675
144
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.Props; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class EsJvmOptionsTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private final Properties properties = new Properties(); @Before public void before() { properties.put("sonar.path.logs", "path_to_logs"); } @Test public void constructor_sets_mandatory_JVM_options() throws IOException { File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .containsExactlyInAnyOrder( "-XX:+UseG1GC", "-Djava.io.tmpdir=" + tmpDir.getAbsolutePath(), "-XX:ErrorFile=" + Paths.get("path_to_logs/es_hs_err_pid%p.log").toAbsolutePath(), "-Des.networkaddress.cache.ttl=60", "-Des.networkaddress.cache.negative.ttl=10", "-XX:+AlwaysPreTouch", "-Xss1m", "-Djava.awt.headless=true", "-Dfile.encoding=UTF-8", "-Djna.nosys=true", "-Djna.tmpdir=" + tmpDir.getAbsolutePath(), "-XX:-OmitStackTraceInFastThrow", "-Dio.netty.noUnsafe=true", "-Dio.netty.noKeySetOptimization=true", "-Dio.netty.recycler.maxCapacityPerThread=0", "-Dio.netty.allocator.numDirectArenas=0", "-Dlog4j.shutdownHookEnabled=false", "-Dlog4j2.disable.jmx=true", "-Dlog4j2.formatMsgNoLookups=true", "-Djava.locale.providers=COMPAT", "-Dcom.redhat.fips=false", "-Des.enforce.bootstrap.checks=true", "-Xlog:disable"); } @Test public void constructor_does_not_force_boostrap_checks_if_sonarqube_property_is_true() throws IOException { properties.put("sonar.es.bootstrap.checks.disable", "true"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .doesNotContain("-Des.enforce.bootstrap.checks=true"); } @Test public void constructor_forces_boostrap_checks_if_jdbc_url_property_does_not_exist() throws IOException { File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .contains("-Des.enforce.bootstrap.checks=true"); } @Test public void constructor_forces_boostrap_checks_if_jdbc_url_property_is_not_h2() throws IOException { properties.put("sonar.jdbc.url", randomAlphanumeric(53)); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .contains("-Des.enforce.bootstrap.checks=true"); } @Test public void constructor_does_not_force_boostrap_checks_if_jdbc_url_property_contains_h2() throws IOException { properties.put("sonar.jdbc.url", "jdbc:h2:tcp://ffoo:bar/sonar"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .doesNotContain("-Des.enforce.bootstrap.checks=true"); } @Test public void boostrap_checks_can_be_set_true_if_h2() throws IOException { properties.put("sonar.jdbc.url", "jdbc:h2:tcp://ffoo:bar/sonar"); properties.put("sonar.es.bootstrap.checks.disable", "true"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .doesNotContain("-Des.enforce.bootstrap.checks=true"); } @Test public void boostrap_checks_can_be_set_false_if_h2() throws IOException { properties.put("sonar.jdbc.url", "jdbc:h2:tcp://ffoo:bar/sonar"); properties.put("sonar.es.bootstrap.checks.disable", "false"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .contains("-Des.enforce.bootstrap.checks=true"); } @Test public void boostrap_checks_can_be_set_true_if_jdbc_other_than_h2() throws IOException { properties.put("sonar.jdbc.url", randomAlphanumeric(53)); properties.put("sonar.es.bootstrap.checks.disable", "true"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .doesNotContain("-Des.enforce.bootstrap.checks=true"); } @Test public void boostrap_checks_can_be_set_false_if_jdbc_other_than_h2() throws IOException { properties.put("sonar.jdbc.url", randomAlphanumeric(53)); properties.put("sonar.es.bootstrap.checks.disable", "false"); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); assertThat(underTest.getAll()) .isNotEmpty() .contains("-Des.enforce.bootstrap.checks=true"); } /** * This test may fail if SQ's test are not executed with target Java version 8. */ @Test public void writeToJvmOptionFile_writes_all_JVM_options_to_file_with_warning_header() throws IOException { File tmpDir = temporaryFolder.newFolder("with space"); File file = temporaryFolder.newFile(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir) .add("-foo") .add("-bar"); underTest.writeToJvmOptionFile(file); assertThat(file).hasContent( "# This file has been automatically generated by SonarQube during startup.\n" + "# Please use sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to specify jvm options for Elasticsearch\n" + "\n" + "# DO NOT EDIT THIS FILE\n" + "\n" + "-XX:+UseG1GC\n" + "-Djava.io.tmpdir=" + tmpDir.getAbsolutePath() + "\n" + "-XX:ErrorFile=" + Paths.get("path_to_logs/es_hs_err_pid%p.log").toAbsolutePath() + "\n" + "-Xlog:disable\n" + "-Des.networkaddress.cache.ttl=60\n" + "-Des.networkaddress.cache.negative.ttl=10\n" + "-XX:+AlwaysPreTouch\n" + "-Xss1m\n" + "-Djava.awt.headless=true\n" + "-Dfile.encoding=UTF-8\n" + "-Djna.nosys=true\n" + "-Djna.tmpdir=" + tmpDir.getAbsolutePath() + "\n" + "-XX:-OmitStackTraceInFastThrow\n" + "-Dio.netty.noUnsafe=true\n" + "-Dio.netty.noKeySetOptimization=true\n" + "-Dio.netty.recycler.maxCapacityPerThread=0\n" + "-Dio.netty.allocator.numDirectArenas=0\n" + "-Dlog4j.shutdownHookEnabled=false\n" + "-Dlog4j2.disable.jmx=true\n" + "-Dlog4j2.formatMsgNoLookups=true\n" + "-Djava.locale.providers=COMPAT\n" + "-Dcom.redhat.fips=false\n" + "-Des.enforce.bootstrap.checks=true\n" + "-foo\n" + "-bar"); } @Test public void writeToJvmOptionFile_throws_ISE_in_case_of_IOException() throws IOException { File notAFile = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), temporaryFolder.newFolder()); assertThatThrownBy(() -> underTest.writeToJvmOptionFile(notAFile)) .isInstanceOf(IllegalStateException.class) .hasMessage("Cannot write Elasticsearch jvm options file") .hasRootCauseInstanceOf(IOException.class); } }
8,853
37
148
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/JavaCommandTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import java.io.File; import java.util.Properties; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; public class JavaCommandTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void test_command_with_complete_information() throws Exception { File workDir = temp.newFolder(); JavaCommand<JvmOptions> command = new JavaCommand<>(ProcessId.ELASTICSEARCH, workDir); command.setArgument("first_arg", "val1"); Properties args = new Properties(); args.setProperty("second_arg", "val2"); command.setArguments(args); command.setClassName("org.sonar.ElasticSearch"); command.setEnvVariable("JAVA_COMMAND_TEST", "1000"); command.addClasspath("lib/*.jar"); command.addClasspath("conf/*.xml"); JvmOptions<JvmOptions> jvmOptions = new JvmOptions<>() {}; command.setJvmOptions(jvmOptions); assertThat(command.toString()).isNotNull(); assertThat(command.getClasspath()).containsOnly("lib/*.jar", "conf/*.xml"); assertThat(command.getJvmOptions()).isSameAs(jvmOptions); assertThat(command.getWorkDir()).isSameAs(workDir); assertThat(command.getClassName()).isEqualTo("org.sonar.ElasticSearch"); // copy current env variables assertThat(command.getEnvVariables()).containsEntry("JAVA_COMMAND_TEST", "1000"); assertThat(command.getEnvVariables()).hasSize(System.getenv().size() + 1); } }
2,407
36.046154
90
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import com.google.common.collect.ImmutableMap; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.process.MessageException; import org.sonar.process.Props; import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @RunWith(DataProviderRunner.class) public class JvmOptionsTest { private final Random random = new Random(); private final String randomPropertyName = randomAlphanumeric(3); private final String randomPrefix = "-" + randomAlphabetic(5).toLowerCase(Locale.ENGLISH); private final String randomValue = randomAlphanumeric(4).toLowerCase(Locale.ENGLISH); private final Properties properties = new Properties(); private final JvmOptions underTest = new JvmOptions(); @Test public void constructor_without_arguments_creates_empty_JvmOptions() { JvmOptions<JvmOptions> testJvmOptions = new JvmOptions<>(); assertThat(testJvmOptions.getAll()).isEmpty(); } @Test public void constructor_throws_NPE_if_argument_is_null() { expectJvmOptionNotNullNPE(() -> new JvmOptions(null)); } @Test public void constructor_throws_NPE_if_any_option_prefix_is_null() { Map<String, String> mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), Stream.of(new Option(null, "value"))) .flatMap(s -> s)); assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) .isInstanceOf(NullPointerException.class) .hasMessage("JVM option prefix can't be null"); } @Test @UseDataProvider("variousEmptyStrings") public void constructor_throws_IAE_if_any_option_prefix_is_empty(String emptyString) { Map<String, String> mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), Stream.of(new Option(emptyString, "value"))) .flatMap(s -> s)); assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("JVM option prefix can't be empty"); } @Test public void constructor_throws_IAE_if_any_option_prefix_does_not_start_with_dash() { String invalidPrefix = randomAlphanumeric(3); Map<String, String> mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), Stream.of(new Option(invalidPrefix, "value"))) .flatMap(s -> s)); expectJvmOptionNotEmptyAndStartByDashIAE(() -> new JvmOptions(mandatoryJvmOptions)); } @Test public void constructor_throws_NPE_if_any_option_value_is_null() { Map<String, String> mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), Stream.of(new Option("-prefix", null))) .flatMap(s -> s)); assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) .isInstanceOf(NullPointerException.class) .hasMessage("JVM option value can't be null"); } @Test @UseDataProvider("variousEmptyStrings") public void constructor_accepts_any_empty_option_value(String emptyString) { Map<String, String> mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), Stream.of(new Option("-prefix", emptyString))) .flatMap(s -> s)); new JvmOptions(mandatoryJvmOptions); } @Test public void add_throws_NPE_if_argument_is_null() { expectJvmOptionNotNullNPE(() -> underTest.add(null)); } @Test @UseDataProvider("variousEmptyStrings") public void add_throws_IAE_if_argument_is_empty(String emptyString) { expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(emptyString)); } @Test public void add_throws_IAE_if_argument_does_not_start_with_dash() { expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(randomAlphanumeric(3))); } @Test @UseDataProvider("variousEmptyStrings") public void add_adds_with_trimming(String emptyString) { underTest.add(emptyString + "-foo" + emptyString); assertThat(underTest.getAll()).containsOnly("-foo"); } @Test public void add_throws_MessageException_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() { String[] optionOverrides = { randomPrefix, randomPrefix + randomAlphanumeric(1), randomPrefix + randomAlphanumeric(2), randomPrefix + randomAlphanumeric(3), randomPrefix + randomAlphanumeric(4), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); for (String optionOverride : optionOverrides) { try { underTest.add(optionOverride); fail("an MessageException should have been thrown"); } catch (MessageException e) { assertThat(e.getMessage()).isEqualTo("a JVM option can't overwrite mandatory JVM options. " + optionOverride + " overwrites " + randomPrefix + randomValue); } } } @Test public void add_checks_against_mandatory_options_is_case_sensitive() { String[] optionOverrides = { randomPrefix, randomPrefix + randomAlphanumeric(1), randomPrefix + randomAlphanumeric(2), randomPrefix + randomAlphanumeric(3), randomPrefix + randomAlphanumeric(4), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); for (String optionOverride : optionOverrides) { underTest.add(optionOverride.toUpperCase(Locale.ENGLISH)); } } @Test public void add_accepts_property_equal_to_mandatory_option_and_does_not_add_it_twice() { JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); underTest.add(randomPrefix + randomValue); assertThat(underTest.getAll()).containsOnly(randomPrefix + randomValue); } @Test public void addFromMandatoryProperty_fails_with_IAE_if_property_does_not_exist() { expectMissingPropertyIAE(() -> underTest.addFromMandatoryProperty(new Props(properties), this.randomPropertyName), this.randomPropertyName); } @Test public void addFromMandatoryProperty_fails_with_IAE_if_property_contains_an_empty_value() { expectMissingPropertyIAE(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName), this.randomPropertyName); } @Test @UseDataProvider("variousEmptyStrings") public void addFromMandatoryProperty_adds_single_option_of_property_with_trimming(String emptyString) { properties.put(randomPropertyName, emptyString + "-foo" + emptyString); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); assertThat(underTest.getAll()).containsOnly("-foo"); } @Test @UseDataProvider("variousEmptyStrings") public void addFromMandatoryProperty_fails_with_MessageException_if_property_does_not_start_with_dash_after_trimmed(String emptyString) { properties.put(randomPropertyName, emptyString + "foo -bar"); expectJvmOptionNotEmptyAndStartByDashMessageException(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName), randomPropertyName, "foo"); } @Test @UseDataProvider("variousEmptyStrings") public void addFromMandatoryProperty_adds_options_of_property_with_trimming(String emptyString) { properties.put(randomPropertyName, emptyString + "-foo" + emptyString + " -bar" + emptyString + " -duck" + emptyString); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); assertThat(underTest.getAll()).containsOnly("-foo", "-bar", "-duck"); } @Test public void addFromMandatoryProperty_supports_spaces_inside_options() { properties.put(randomPropertyName, "-foo bar -duck"); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); assertThat(underTest.getAll()).containsOnly("-foo bar", "-duck"); } @Test public void addFromMandatoryProperty_throws_IAE_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() { String[] optionOverrides = { randomPrefix, randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3), randomPrefix + randomValue.substring(3) + randomAlphanumeric(1), randomPrefix + randomValue.substring(3) + randomAlphanumeric(2), randomPrefix + randomValue.substring(3) + randomAlphanumeric(3), randomPrefix + randomValue + randomAlphanumeric(1) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); for (String optionOverride : optionOverrides) { try { properties.put(randomPropertyName, optionOverride); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); fail("an MessageException should have been thrown"); } catch (MessageException e) { assertThat(e.getMessage()) .isEqualTo("a JVM option can't overwrite mandatory JVM options. " + "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + optionOverride + " overwrites " + randomPrefix + randomValue); } } } @Test public void addFromMandatoryProperty_checks_against_mandatory_options_is_case_sensitive() { String[] optionOverrides = { randomPrefix, randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3), randomPrefix + randomValue.substring(3) + randomAlphanumeric(1), randomPrefix + randomValue.substring(3) + randomAlphanumeric(2), randomPrefix + randomValue.substring(3) + randomAlphanumeric(3), randomPrefix + randomValue + randomAlphanumeric(1) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); for (String optionOverride : optionOverrides) { properties.setProperty(randomPropertyName, optionOverride.toUpperCase(Locale.ENGLISH)); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); } } @Test public void addFromMandatoryProperty_reports_all_overriding_options_in_single_exception() { String overriding1 = randomPrefix; String overriding2 = randomPrefix + randomValue + randomAlphanumeric(1); properties.setProperty(randomPropertyName, "-foo " + overriding1 + " -bar " + overriding2); JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); assertThatThrownBy(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName)) .isInstanceOf(MessageException.class) .hasMessage("a JVM option can't overwrite mandatory JVM options. " + "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + overriding1 + " overwrites " + randomPrefix + randomValue + ", " + overriding2 + " overwrites " + randomPrefix + randomValue); } @Test public void addFromMandatoryProperty_accepts_property_equal_to_mandatory_option_and_does_not_add_it_twice() { JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); properties.put(randomPropertyName, randomPrefix + randomValue); underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); assertThat(underTest.getAll()).containsOnly(randomPrefix + randomValue); } @Test public void toString_prints_all_jvm_options() { underTest.add("-foo").add("-bar"); assertThat(underTest).hasToString("[-foo, -bar]"); } private void expectJvmOptionNotNullNPE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(NullPointerException.class) .hasMessage("a JVM option can't be null"); } private void expectJvmOptionNotEmptyAndStartByDashIAE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(IllegalArgumentException.class) .hasMessage("a JVM option can't be empty and must start with '-'"); } private void expectJvmOptionNotEmptyAndStartByDashMessageException(ThrowingCallable callback, String randomPropertyName, String option) { assertThatThrownBy(callback) .isInstanceOf(MessageException.class) .hasMessage("a JVM option can't be empty and must start with '-'. " + "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + option); } public void expectMissingPropertyIAE(ThrowingCallable callback, String randomPropertyName) { assertThatThrownBy(callback) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property: " + randomPropertyName); } @DataProvider() public static Object[][] variousEmptyStrings() { return new Object[][] { {""}, {" "}, {" "} }; } private static Map<String, String> shuffleThenToMap(Stream<Option> stream) { List<Option> options = stream.collect(Collectors.toCollection(ArrayList::new)); Collections.shuffle(options); Map<String, String> res = new HashMap<>(options.size()); for (Option option : options) { res.put(option.getPrefix(), option.getValue()); } return res; } private static final class Option { private final String prefix; private final String value; private Option(String prefix, String value) { this.prefix = prefix; this.value = value; } public String getPrefix() { return prefix; } public String getValue() { return value; } @Override public String toString() { return "[" + prefix + "-" + value + ']'; } } }
15,872
37.526699
170
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/command/WebJvmOptionsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.command; import java.io.File; import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; public class WebJvmOptionsTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private File tmpDir; private WebJvmOptions underTest; @Before public void setUp() throws IOException { tmpDir = temporaryFolder.newFolder(); } @Test public void constructor_sets_mandatory_JVM_options() { underTest = new WebJvmOptions(tmpDir); assertThat(underTest.getAll()).containsExactly( "-Djava.awt.headless=true", "-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=" + tmpDir.getAbsolutePath(), "-XX:-OmitStackTraceInFastThrow", "--add-opens=java.base/java.util=ALL-UNNAMED", "--add-opens=java.base/java.lang=ALL-UNNAMED", "--add-opens=java.base/java.io=ALL-UNNAMED", "--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED", "--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED", "--add-opens=java.base/java.nio=ALL-UNNAMED", "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens=java.management/sun.management=ALL-UNNAMED", "--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED", "-Dcom.redhat.fips=false"); } }
2,238
35.112903
140
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import java.util.Properties; import org.junit.Test; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; public class AppSettingsImplTest { @Test public void reload_updates_properties() { Props initialProps = new Props(new Properties()); initialProps.set("foo", "bar"); Props newProps = new Props(new Properties()); newProps.set("foo", "baz"); newProps.set("newProp", "newVal"); AppSettingsImpl underTest = new AppSettingsImpl(initialProps); underTest.reload(newProps); assertThat(underTest.getValue("foo")).contains("baz"); assertThat(underTest.getValue("newProp")).contains("newVal"); assertThat(underTest.getProps().rawProperties()).hasSize(2); } }
1,622
34.282609
75
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.System2; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AppSettingsLoaderImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); private System2 system = mock(System2.class); @Before public void setup() { when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of()); } @Test public void load_properties_from_file() throws Exception { File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "foo=bar", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains(entry("foo", "bar")); } @Test public void load_properties_from_env() throws Exception { when(system.getenv()).thenReturn(ImmutableMap.of( "SONAR_DASHED_PROPERTY", "2", "SONAR_JDBC_URL", "some_jdbc_url", "SONAR_EMBEDDEDDATABASE_PORT", "8765")); when(system.getenv("SONAR_DASHED_PROPERTY")).thenReturn("2"); when(system.getenv("SONAR_JDBC_URL")).thenReturn("some_jdbc_url"); when(system.getenv("SONAR_EMBEDDEDDATABASE_PORT")).thenReturn("8765"); File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "sonar.dashed-property=1", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains( entry("sonar.dashed-property", "2"), entry("sonar.jdbc.url", "some_jdbc_url"), entry("sonar.embeddedDatabase.port", "8765")); } @Test public void load_multi_ldap_settings() throws IOException { when(system.getenv()).thenReturn(ImmutableMap.of( "LDAP_FOO_URL", "url1", "LDAP_RANDOM_PROP", "5")); when(system.getenv("LDAP_FOO_URL")).thenReturn("url1"); when(system.getenv("LDAP_RANDOM_PROP")).thenReturn("5"); File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "ldap.servers=foo,bar\n" + "ldap.bar.url=url2", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains( entry("ldap.servers", "foo,bar"), entry("ldap.foo.url", "url1"), entry("ldap.bar.url", "url2")); } @Test public void throws_ISE_if_file_fails_to_be_loaded() throws Exception { File homeDir = temp.newFolder(); File propsFileAsDir = new File(homeDir, "conf/sonar.properties"); FileUtils.forceMkdir(propsFileAsDir); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); assertThatThrownBy(() -> underTest.load()) .isInstanceOf(IllegalStateException.class) .hasMessage("Cannot open file " + propsFileAsDir.getAbsolutePath()); } @Test public void file_is_not_loaded_if_it_does_not_exist() throws Exception { File homeDir = temp.newFolder(); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); // no failure, file is ignored assertThat(settings.getProps()).isNotNull(); } @Test public void command_line_arguments_are_included_to_settings() throws Exception { File homeDir = temp.newFolder(); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[] {"-Dsonar.foo=bar", "-Dhello=world"}, homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()) .contains(entry("sonar.foo", "bar")) .contains(entry("hello", "world")); } @Test public void command_line_arguments_take_precedence_over_properties_files() throws IOException { File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "sonar.foo=file", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[] {"-Dsonar.foo=cli"}, homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains(entry("sonar.foo", "cli")); } @Test public void env_vars_take_precedence_over_properties_file() throws Exception { when(system.getenv()).thenReturn(ImmutableMap.of("SONAR_CUSTOMPROP", "11")); when(system.getenv("SONAR_CUSTOMPROP")).thenReturn("11"); File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "sonar.customProp=10", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains(entry("sonar.customProp", "11")); } @Test public void command_line_arguments_take_precedence_over_env_vars() throws Exception { when(system.getenv()).thenReturn(ImmutableMap.of("SONAR_CUSTOMPROP", "11")); when(system.getenv("SONAR_CUSTOMPROP")).thenReturn("11"); File homeDir = temp.newFolder(); File propsFile = new File(homeDir, "conf/sonar.properties"); FileUtils.write(propsFile, "sonar.customProp=10", UTF_8); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[] {"-Dsonar.customProp=9"}, homeDir, serviceLoaderWrapper); AppSettings settings = underTest.load(); assertThat(settings.getProps().rawProperties()).contains(entry("sonar.customProp", "9")); } @Test public void detectHomeDir_returns_existing_dir() { assertThat(new AppSettingsLoaderImpl(system, new String[0], serviceLoaderWrapper).getHomeDir()).exists().isDirectory(); } }
7,719
39.846561
154
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/ClusterSettingsLoopbackTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import com.google.common.collect.ImmutableMap; import java.net.InetAddress; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import org.sonar.process.MessageException; import org.sonar.process.NetworkUtils; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assume.assumeThat; import static org.mockito.Mockito.spy; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; public class ClusterSettingsLoopbackTest { private final InetAddress loopback = InetAddress.getLoopbackAddress(); private final NetworkUtils network = spy(NetworkUtilsImpl.INSTANCE); private InetAddress nonLoopbackLocal; @Before public void setUp() { Optional<InetAddress> opt = network.getLocalNonLoopbackIpv4Address(); assumeThat(opt.isPresent(), CoreMatchers.is(true)); nonLoopbackLocal = opt.get(); } @Test public void ClusterSettings_throws_MessageException_if_es_http_host_of_search_node_is_loopback() { TestAppSettings settings = newSettingsForSearchNode(ImmutableMap.of(CLUSTER_NODE_SEARCH_HOST.getKey(), loopback.getHostAddress())); Props props = settings.getProps(); ClusterSettings clusterSettings = new ClusterSettings(network); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Property " + CLUSTER_NODE_SEARCH_HOST.getKey() + " must be a local non-loopback address: " + loopback.getHostAddress()); } @Test public void ClusterSettings_throws_MessageException_if_es_transport_host_of_search_node_is_loopback() { TestAppSettings settings = newSettingsForSearchNode(ImmutableMap.of(CLUSTER_NODE_ES_HOST.getKey(), loopback.getHostAddress())); Props props = settings.getProps(); ClusterSettings clusterSettings = new ClusterSettings(network); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Property " + CLUSTER_NODE_ES_HOST.getKey() + " must be a local non-loopback address: " + loopback.getHostAddress()); } @Test public void ClusterSettings_throws_MessageException_if_host_of_app_node_is_loopback() { TestAppSettings settings = newSettingsForAppNode(ImmutableMap.of(CLUSTER_NODE_HOST.getKey(), loopback.getHostAddress())); Props props = settings.getProps(); ClusterSettings clusterSettings = new ClusterSettings(network); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Property " + CLUSTER_NODE_HOST.getKey() + " must be a local non-loopback address: " + loopback.getHostAddress()); } private TestAppSettings newSettingsForAppNode(ImmutableMap<String, String> settings) { Map<String, String> result = new HashMap<>(); result.put(CLUSTER_ENABLED.getKey(), "true"); result.put(CLUSTER_NODE_TYPE.getKey(), "application"); result.put(CLUSTER_NODE_HOST.getKey(), nonLoopbackLocal.getHostAddress()); result.put(CLUSTER_HZ_HOSTS.getKey(), nonLoopbackLocal.getHostAddress()); result.put(CLUSTER_SEARCH_HOSTS.getKey(), nonLoopbackLocal.getHostAddress()); result.put("sonar.auth.jwtBase64Hs256Secret", "abcde"); result.put(JDBC_URL.getKey(), "jdbc:postgresql://localhost:3306/sonar"); result.putAll(settings); return new TestAppSettings(result); } private TestAppSettings newSettingsForSearchNode(ImmutableMap<String, String> settings) { Map<String, String> result = new HashMap<>(); result.put(CLUSTER_ENABLED.getKey(), "true"); result.put(CLUSTER_NODE_TYPE.getKey(), "search"); result.put(CLUSTER_ES_HOSTS.getKey(), nonLoopbackLocal.getHostAddress()); result.put(CLUSTER_NODE_SEARCH_HOST.getKey(), nonLoopbackLocal.getHostAddress()); result.put(CLUSTER_NODE_ES_HOST.getKey(), nonLoopbackLocal.getHostAddress()); result.putAll(settings); return new TestAppSettings(result); } }
5,598
45.658333
139
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/ClusterSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.net.InetAddress; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.sonar.process.MessageException; import org.sonar.process.NetworkUtils; import org.sonar.process.Props; import static com.google.common.collect.ImmutableMap.of; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessId.COMPUTE_ENGINE; import static org.sonar.process.ProcessId.ELASTICSEARCH; import static org.sonar.process.ProcessId.WEB_SERVER; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; @RunWith(DataProviderRunner.class) public class ClusterSettingsTest { private final NetworkUtils network = Mockito.mock(NetworkUtils.class); @Test @UseDataProvider("validIPv4andIPv6Addresses") public void test_isClusterEnabled(String host) { TestAppSettings settings = newSettingsForAppNode(host, of(CLUSTER_ENABLED.getKey(), "true")); assertThat(ClusterSettings.isClusterEnabled(settings)).isTrue(); settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "false")); assertThat(ClusterSettings.isClusterEnabled(settings)).isFalse(); } @Test public void isClusterEnabled_returns_false_by_default() { assertThat(ClusterSettings.isClusterEnabled(new TestAppSettings())).isFalse(); } @Test public void getEnabledProcesses_returns_all_processes_in_standalone_mode() { TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "false")); assertThat(ClusterSettings.getEnabledProcesses(settings)).containsOnly(COMPUTE_ENGINE, ELASTICSEARCH, WEB_SERVER); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void getEnabledProcesses_returns_configured_processes_in_cluster_mode(String host) { TestAppSettings settings = newSettingsForAppNode(host); assertThat(ClusterSettings.getEnabledProcesses(settings)).containsOnly(COMPUTE_ENGINE, WEB_SERVER); settings = newSettingsForSearchNode(host); assertThat(ClusterSettings.getEnabledProcesses(settings)).containsOnly(ELASTICSEARCH); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void valid_configuration_of_app_node_does_not_throw_exception(String host) { mockValidHost(host); mockLocalNonLoopback(host); TestAppSettings settings = newSettingsForAppNode(host); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatCode(() -> clusterSettings.accept(props)) .doesNotThrowAnyException(); } @Test public void accept_throws_MessageException_if_no_node_type_is_configured() { TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "true")); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Property sonar.cluster.node.type is mandatory"); } @Test public void accept_throws_MessageException_if_node_type_is_not_correct() { TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "true", CLUSTER_NODE_TYPE.getKey(), "bla")); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Invalid value for property sonar.cluster.node.type: [bla], only [application, search] are allowed"); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_internal_property_for_startup_leader_is_configured(String host) { TestAppSettings settings = newSettingsForAppNode(host, of("sonar.cluster.web.startupLeader", "true")); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Property [sonar.cluster.web.startupLeader] is forbidden"); } @Test public void accept_does_nothing_if_cluster_is_disabled() { TestAppSettings settings = new TestAppSettings(of( CLUSTER_ENABLED.getKey(), "false", // this property is supposed to fail if cluster is enabled "sonar.cluster.web.startupLeader", "true")); new ClusterSettings(network).accept(settings.getProps()); } @Test public void accept_throws_MessageException_if_a_cluster_forbidden_property_is_defined_in_a_cluster_search_node() { TestAppSettings settings = new TestAppSettings(of( CLUSTER_ENABLED.getKey(), "true", CLUSTER_NODE_TYPE.getKey(), "search", "sonar.search.host", "localhost")); Props props = settings.getProps(); ClusterSettings clusterSettings = new ClusterSettings(network); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Properties [sonar.search.host] are not allowed when running SonarQube in cluster mode."); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_h2_on_application_node(String host) { TestAppSettings settings = newSettingsForAppNode(host, of("sonar.jdbc.url", "jdbc:h2:mem")); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Embedded database is not supported in cluster mode"); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_does_not_verify_h2_on_search_node(String host) { mockValidHost(host); mockLocalNonLoopback(host); TestAppSettings settings = newSettingsForSearchNode(host, of("sonar.jdbc.url", "jdbc:h2:mem")); // do not fail new ClusterSettings(network).accept(settings.getProps()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_on_application_node_if_default_jdbc_url(String host) { TestAppSettings settings = newSettingsForAppNode(host); settings.clearProperty(JDBC_URL.getKey()); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Embedded database is not supported in cluster mode"); } @Test public void isLocalElasticsearchEnabled_returns_true_in_standalone_mode() { TestAppSettings settings = new TestAppSettings(); assertThat(ClusterSettings.isLocalElasticsearchEnabled(settings)).isTrue(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void isLocalElasticsearchEnabled_returns_true_on_search_node(String host) { TestAppSettings settings = newSettingsForSearchNode(host); assertThat(ClusterSettings.isLocalElasticsearchEnabled(settings)).isTrue(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void shouldStartHazelcast_must_be_true_on_AppNode(String host) { TestAppSettings settings = newSettingsForAppNode(host); assertThat(ClusterSettings.shouldStartHazelcast(settings)).isTrue(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void shouldStartHazelcast_must_be_false_on_SearchNode(String host) { TestAppSettings settings = newSettingsForSearchNode(host); assertThat(ClusterSettings.shouldStartHazelcast(settings)).isFalse(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void shouldStartHazelcast_must_be_false_when_cluster_not_activated(String host) { TestAppSettings settings = newSettingsForSearchNode(host, of(CLUSTER_ENABLED.getKey(), "false")); assertThat(ClusterSettings.shouldStartHazelcast(settings)).isFalse(); settings = newSettingsForAppNode(host, of(CLUSTER_ENABLED.getKey(), "false")); assertThat(ClusterSettings.shouldStartHazelcast(settings)).isFalse(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void isLocalElasticsearchEnabled_returns_true_for_a_application_node(String host) { TestAppSettings settings = newSettingsForAppNode(host); assertThat(ClusterSettings.isLocalElasticsearchEnabled(settings)).isFalse(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_clusterNodeEsHost_is_missing(String host) { String searchHost = "search_host"; TestAppSettings settings = newSettingsForSearchNode(host, of(CLUSTER_NODE_SEARCH_HOST.getKey(), searchHost)); mockValidHost(searchHost); mockLocalNonLoopback(searchHost); settings.clearProperty(CLUSTER_NODE_ES_HOST.getKey()); assertThatPropertyIsMandatory(settings, CLUSTER_NODE_ES_HOST.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_clusterNodeSearchHost_is_missing(String host) { String esHost = "es_host"; TestAppSettings settings = newSettingsForSearchNode(host, of(CLUSTER_NODE_ES_HOST.getKey(), esHost)); mockValidHost(esHost); mockLocalNonLoopback(esHost); settings.clearProperty(CLUSTER_NODE_SEARCH_HOST.getKey()); assertThatPropertyIsMandatory(settings, CLUSTER_NODE_SEARCH_HOST.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_sonarClusterNodeSearchHost_is_empty(String host) { String esHost = "es_host"; TestAppSettings settings = newSettingsForSearchNode(host, of( CLUSTER_NODE_SEARCH_HOST.getKey(), "", CLUSTER_NODE_ES_HOST.getKey(), esHost)); mockValidHost(esHost); mockLocalNonLoopback(esHost); assertThatPropertyIsMandatory(settings, CLUSTER_NODE_SEARCH_HOST.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_sonarClusterNodeEsHost_is_empty(String host) { String searchHost = "search_host"; TestAppSettings settings = newSettingsForSearchNode(host, of( CLUSTER_NODE_ES_HOST.getKey(), "", CLUSTER_NODE_SEARCH_HOST.getKey(), searchHost)); mockValidHost(searchHost); mockLocalNonLoopback(searchHost); assertThatPropertyIsMandatory(settings, CLUSTER_NODE_ES_HOST.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_on_app_node_if_clusterHosts_is_missing(String host) { TestAppSettings settings = newSettingsForAppNode(host); settings.clearProperty(CLUSTER_HZ_HOSTS.getKey()); assertThatPropertyIsMandatory(settings, CLUSTER_HZ_HOSTS.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_clusterEsHosts_is_missing(String host) { mockValidHost(host); mockLocalNonLoopback(host); TestAppSettings settings = newSettingsForSearchNode(host); settings.clearProperty(CLUSTER_ES_HOSTS.getKey()); assertThatPropertyIsMandatory(settings, CLUSTER_ES_HOSTS.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_clusterEsHosts_is_empty(String host) { mockValidHost(host); mockLocalNonLoopback(host); TestAppSettings settings = newSettingsForSearchNode(host, of(CLUSTER_ES_HOSTS.getKey(), "")); assertThatPropertyIsMandatory(settings, CLUSTER_ES_HOSTS.getKey()); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void accept_throws_MessageException_if_jwt_token_is_not_set_on_application_nodes(String host) { TestAppSettings settings = newSettingsForAppNode(host); settings.clearProperty("sonar.auth.jwtBase64Hs256Secret"); assertThatPropertyIsMandatory(settings, "sonar.auth.jwtBase64Hs256Secret"); } @Test public void shouldStartHazelcast_should_return_false_when_cluster_not_enabled() { TestAppSettings settings = new TestAppSettings(); assertThat(ClusterSettings.shouldStartHazelcast(settings)).isFalse(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void shouldStartHazelcast_should_return_false_on_SearchNode(String host) { assertThat(ClusterSettings.shouldStartHazelcast(newSettingsForSearchNode(host))).isFalse(); } @Test @UseDataProvider("validIPv4andIPv6Addresses") public void shouldStartHazelcast_should_return_true_on_AppNode(String host) { assertThat(ClusterSettings.shouldStartHazelcast(newSettingsForAppNode(host))).isTrue(); } @Test public void validate_host_in_any_cluster_property_of_APP_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application") .put(CLUSTER_NODE_HOST.getKey(), "hz_host") .put(CLUSTER_HZ_HOSTS.getKey(), "remote_hz_host_1,remote_hz_host_2") .put(CLUSTER_SEARCH_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(JDBC_URL.getKey(), "jdbc:postgresql://localhost/sonar") .put("sonar.auth.jwtBase64Hs256Secret", "abcde") .build()); verifyHostIsChecked(settings, ImmutableList.of("hz_host"), "Address in property sonar.cluster.node.host is not a valid address: hz_host"); verifyHostIsChecked(settings, ImmutableList.of("remote_hz_host_1"), "Address in property sonar.cluster.hosts is not a valid address: remote_hz_host_1"); verifyHostIsChecked(settings, ImmutableList.of("remote_hz_host_2"), "Address in property sonar.cluster.hosts is not a valid address: remote_hz_host_2"); verifyHostIsChecked(settings, ImmutableList.of("remote_hz_host_1", "remote_hz_host_2"), "Address in property sonar.cluster.hosts is not a valid address: remote_hz_host_1, remote_hz_host_2"); verifyHostIsChecked(settings, ImmutableList.of("remote_search_host_1"), "Address in property sonar.cluster.search.hosts is not a valid address: remote_search_host_1"); verifyHostIsChecked(settings, ImmutableList.of("remote_search_host_2"), "Address in property sonar.cluster.search.hosts is not a valid address: remote_search_host_2"); verifyHostIsChecked(settings, ImmutableList.of("remote_search_host_1", "remote_search_host_2"), "Address in property sonar.cluster.search.hosts is not a valid address: remote_search_host_1, remote_search_host_2"); } @Test public void validate_host_resolved_in_node_search_host_property_of_SEARCH_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_ES_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "search_host").build()); verifyHostIsChecked(settings, ImmutableList.of("search_host"), "Address in property sonar.cluster.node.search.host is not a valid address: search_host"); } private void verifyHostIsChecked(TestAppSettings settings, Collection<String> invalidHosts, String expectedMessage) { reset(network); mockAllHostsValidBut(invalidHosts); mockLocalNonLoopback("hz_host", "search_host"); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage(expectedMessage); } @Test public void ensure_no_loopback_host_in_properties_of_APP_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application") .put(CLUSTER_NODE_HOST.getKey(), "hz_host") .put(CLUSTER_HZ_HOSTS.getKey(), "remote_hz_host_1,remote_hz_host_2") .put(CLUSTER_SEARCH_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(JDBC_URL.getKey(), "jdbc:postgresql://localhost/sonar") .put("sonar.auth.jwtBase64Hs256Secret", "abcde") .build()); verifyLoopbackChecked(settings, ImmutableList.of("hz_host"), "Property sonar.cluster.node.host must be a local non-loopback address: hz_host"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_1"), "Property sonar.cluster.search.hosts must not contain a loopback address: remote_search_host_1"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_2"), "Property sonar.cluster.search.hosts must not contain a loopback address: remote_search_host_2"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_1", "remote_search_host_2"), "Property sonar.cluster.search.hosts must not contain a loopback address: remote_search_host_1, remote_search_host_2"); verifyLoopbackChecked(settings, ImmutableList.of("remote_hz_host_1"), "Property sonar.cluster.hosts must not contain a loopback address: remote_hz_host_1"); verifyLoopbackChecked(settings, ImmutableList.of("remote_hz_host_2"), "Property sonar.cluster.hosts must not contain a loopback address: remote_hz_host_2"); verifyLoopbackChecked(settings, ImmutableList.of("remote_hz_host_1", "remote_hz_host_2"), "Property sonar.cluster.hosts must not contain a loopback address: remote_hz_host_1, remote_hz_host_2"); } @Test public void ensure_no_loopback_host_in_properties_of_SEARCH_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_ES_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "transport_host") .build()); verifyLoopbackChecked(settings, ImmutableList.of("search_host"), "Property sonar.cluster.node.search.host must be a local non-loopback address: search_host"); verifyLoopbackChecked(settings, ImmutableList.of("transport_host"), "Property sonar.cluster.node.es.host must be a local non-loopback address: transport_host"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_1"), "Property sonar.cluster.es.hosts must not contain a loopback address: remote_search_host_1"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_2"), "Property sonar.cluster.es.hosts must not contain a loopback address: remote_search_host_2"); verifyLoopbackChecked(settings, ImmutableList.of("remote_search_host_1", "remote_search_host_2"), "Property sonar.cluster.es.hosts must not contain a loopback address: remote_search_host_1, remote_search_host_2"); } private void verifyLoopbackChecked(TestAppSettings settings, Collection<String> hosts, String expectedMessage) { reset(network); mockAllHostsValid(); mockLocalNonLoopback("hz_host", "search_host", "transport_host"); // will overwrite above move if necessary hosts.forEach(this::mockLoopback); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage(expectedMessage); } @Test public void ensure_HZ_HOST_is_local_non_loopback_in_properties_of_APP_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "application") .put(CLUSTER_NODE_HOST.getKey(), "hz_host") .put(CLUSTER_HZ_HOSTS.getKey(), "remote_hz_host_1,remote_hz_host_2") .put(CLUSTER_SEARCH_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(JDBC_URL.getKey(), "jdbc:postgresql://localhost/sonar") .put("sonar.auth.jwtBase64Hs256Secret", "abcde") .build()); verifyLocalChecked(settings, "hz_host", "Property sonar.cluster.node.host must be a local non-loopback address: hz_host"); } @Test public void ensure_HZ_HOST_and_SEARCH_HOST_are_local_non_loopback_in_properties_of_SEARCH_node() { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_ES_HOSTS.getKey(), "remote_search_host_1:9001, remote_search_host_2:9001") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "search_host") .build()); verifyLocalChecked(settings, "search_host", "Property sonar.cluster.node.search.host must be a local non-loopback address: search_host"); } private void verifyLocalChecked(TestAppSettings settings, String host, String expectedMessage) { reset(network); mockAllHostsValid(); mockLocalNonLoopback("hz_host", "search_host"); // will overwrite above move if necessary mockAllNonLoopback(); mockNonLocal(host); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage(expectedMessage); } @Test public void accept_hosts_only_or_hosts_and_ports_only_in_property_SONAR_CLUSTER_ES_HOSTS_of_search_node() { mockAllHostsValid(); mockLocalNonLoopback("search_host", "transport_host"); verifyAllHostsWithPortsOrAllHostsWithoutPortsIsValid("remote_search_host_1, remote_search_host_2"); verifyAllHostsWithPortsOrAllHostsWithoutPortsIsValid("remote_search_host_1:9001, remote_search_host_2:9001"); } private void verifyAllHostsWithPortsOrAllHostsWithoutPortsIsValid(String searchPropertyValue) { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "transport_host") .put(CLUSTER_ES_HOSTS.getKey(), searchPropertyValue) .build()); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatCode(() -> clusterSettings.accept(props)) .doesNotThrowAnyException(); } @Test public void accept_any_properties_configuration_in_SONAR_CLUSTER_SEARCH_HOSTS_of_search_node() { mockAllHostsValid(); mockLocalNonLoopback("search_host", "transport_host"); verifyAnyHostsConfigurationIsValid("remote_search_host_1, remote_search_host_2"); verifyAnyHostsConfigurationIsValid("remote_search_host_1:9001, remote_search_host_2:9001"); verifyAnyHostsConfigurationIsValid("remote_search_host_1, remote_search_host_2:9001"); verifyAnyHostsConfigurationIsValid("remote_search_host_1, remote_search_host_2"); } private void verifyAnyHostsConfigurationIsValid(String searchPropertyValue) { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_ES_HOSTS.getKey(), "transport_host,transport_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "transport_host") .put(CLUSTER_SEARCH_HOSTS.getKey(), searchPropertyValue) .build()); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatCode(() -> clusterSettings.accept(props)) .doesNotThrowAnyException(); } @Test public void ensure_no_mixed_settings_in_ES_HOSTS_in_properties_of_SEARCH_node() { mockAllHostsValid(); mockLocalNonLoopback("hz_host", "search_host", "transport_host"); verifyPortsAreCheckedOnEsNode("remote_search_host_1,remote_search_host_2:9001"); verifyPortsAreCheckedOnEsNode("remote_search_host_1:9002, remote_search_host_2"); } private void verifyPortsAreCheckedOnEsNode(String searchPropertyValue) { TestAppSettings settings = new TestAppSettings(ImmutableMap.<String, String>builder() .put(CLUSTER_ENABLED.getKey(), "true") .put(CLUSTER_NODE_TYPE.getKey(), "search") .put(CLUSTER_NODE_SEARCH_HOST.getKey(), "search_host") .put(CLUSTER_NODE_ES_HOST.getKey(), "transport_host") .put(CLUSTER_ES_HOSTS.getKey(), searchPropertyValue) .build()); ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage("Entries in property sonar.cluster.es.hosts must not mix 'host:port' and 'host'. Provide hosts without port only or hosts with port only."); } private void mockAllNonLoopback() { when(network.isLoopback(anyString())).thenReturn(false); } private void mockNonLocal(String search_host) { when(network.isLocal(search_host)).thenReturn(false); } private void mockLoopback(String host) { when(network.isLoopback(host)).thenReturn(true); } private void mockValidHost(String host) { String unbracketedHost = host.startsWith("[") ? host.substring(1, host.length() - 1) : host; when(network.toInetAddress(unbracketedHost)).thenReturn(Optional.of(InetAddress.getLoopbackAddress())); } public void mockAllHostsValid() { when(network.toInetAddress(anyString())).thenReturn(Optional.of(InetAddress.getLoopbackAddress())); } public void mockAllHostsValidBut(Collection<String> hosts) { when(network.toInetAddress(anyString())) .thenAnswer((Answer<Optional<InetAddress>>) invocation -> { Object arg = invocation.getArgument(0); if (hosts.contains(arg)) { return Optional.empty(); } return Optional.of(InetAddress.getLoopbackAddress()); }); } private void mockLocalNonLoopback(String host, String... otherhosts) { Stream.concat(Stream.of(host), Arrays.stream(otherhosts)) .forEach(h -> { String unbracketedHost = h.startsWith("[") ? h.substring(1, h.length() - 1) : h; when(network.isLocal(unbracketedHost)).thenReturn(true); when(network.isLoopback(unbracketedHost)).thenReturn(false); }); } @DataProvider public static Object[][] validIPv4andIPv6Addresses() { return new Object[][] { {"10.150.0.188"}, {"[fe80::fde2:607e:ae56:e636]"}, }; } private void assertThatPropertyIsMandatory(TestAppSettings settings, String key) { ClusterSettings clusterSettings = new ClusterSettings(network); Props props = settings.getProps(); assertThatThrownBy(() -> clusterSettings.accept(props)) .isInstanceOf(MessageException.class) .hasMessage(format("Property %s is mandatory", key)); } private TestAppSettings newSettingsForAppNode(String host) { return newSettingsForAppNode(host, of()); } private TestAppSettings newSettingsForAppNode(String host, ImmutableMap<String, String> settings) { Map<String, String> result = new HashMap<>(); result.put(CLUSTER_ENABLED.getKey(), "true"); result.put(CLUSTER_NODE_TYPE.getKey(), "application"); result.put(CLUSTER_NODE_HOST.getKey(), host); result.put(CLUSTER_HZ_HOSTS.getKey(), host); result.put(CLUSTER_SEARCH_HOSTS.getKey(), host + ":9001"); result.put("sonar.auth.jwtBase64Hs256Secret", "abcde"); result.put(JDBC_URL.getKey(), "jdbc:postgresql://localhost/sonar"); result.putAll(settings); return new TestAppSettings(result); } private TestAppSettings newSettingsForSearchNode(String host) { return newSettingsForSearchNode(host, of()); } private TestAppSettings newSettingsForSearchNode(String host, ImmutableMap<String, String> settings) { Map<String, String> result = new HashMap<>(); result.put(CLUSTER_ENABLED.getKey(), "true"); result.put(CLUSTER_NODE_TYPE.getKey(), "search"); result.put(CLUSTER_NODE_HOST.getKey(), host); result.put(CLUSTER_HZ_HOSTS.getKey(), host); result.put(CLUSTER_ES_HOSTS.getKey(), host + ":9001"); result.put(CLUSTER_NODE_SEARCH_HOST.getKey(), host); result.put(CLUSTER_NODE_ES_HOST.getKey(), host); result.putAll(settings); return new TestAppSettings(result); } }
30,839
44.824666
175
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/CommandLineParserTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import java.util.Properties; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CommandLineParserTest { @Test public void parseArguments() { System.setProperty("CommandLineParserTest.unused", "unused"); System.setProperty("sonar.CommandLineParserTest.used", "used"); Properties p = CommandLineParser.parseArguments(new String[] {"-Dsonar.foo=bar"}); // test environment can already declare some system properties prefixed by "sonar." // so we can't test the exact number "2" assertThat(p.size()).isGreaterThanOrEqualTo(2); assertThat(p.getProperty("sonar.foo")).isEqualTo("bar"); assertThat(p.getProperty("sonar.CommandLineParserTest.used")).isEqualTo("used"); } @Test public void argumentsToProperties_throws_IAE_if_argument_does_not_start_with_minusD() { Properties p = CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "-Dsonar.whitespace=foo bar"}); assertThat(p).hasSize(2); assertThat(p.getProperty("sonar.foo")).isEqualTo("bar"); assertThat(p.getProperty("sonar.whitespace")).isEqualTo("foo bar"); assertThatThrownBy(() -> CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "sonar.bad=true"})) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: sonar.bad=true"); } }
2,389
41.678571
124
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/FileSystemSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import java.io.File; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class FileSystemSettingsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private FileSystemSettings underTest = new FileSystemSettings(); private File homeDir; @Before public void setUp() throws Exception { homeDir = temp.newFolder(); } @Test public void relative_paths_are_converted_to_absolute_paths() { Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); // relative paths props.set(PATH_DATA.getKey(), "data"); props.set(PATH_LOGS.getKey(), "logs"); props.set(PATH_TEMP.getKey(), "temp"); // already absolute paths props.set(PATH_WEB.getKey(), new File(homeDir, "web").getAbsolutePath()); underTest.accept(props); assertThat(props.nonNullValue(PATH_DATA.getKey())).isEqualTo(new File(homeDir, "data").getAbsolutePath()); assertThat(props.nonNullValue(PATH_LOGS.getKey())).isEqualTo(new File(homeDir, "logs").getAbsolutePath()); assertThat(props.nonNullValue(PATH_TEMP.getKey())).isEqualTo(new File(homeDir, "temp").getAbsolutePath()); assertThat(props.nonNullValue(PATH_WEB.getKey())).isEqualTo(new File(homeDir, "web").getAbsolutePath()); } }
2,690
36.375
110
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/JdbcSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import java.io.File; import java.net.InetAddress; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.MessageException; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.application.config.JdbcSettings.Provider; import static org.sonar.process.ProcessProperties.Property.JDBC_DRIVER_PATH; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; public class JdbcSettingsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private JdbcSettings underTest = new JdbcSettings(); private File homeDir; @Before public void setUp() throws Exception { homeDir = temp.newFolder(); } @Test public void resolve_H2_provider_when_props_is_empty_and_set_URL_to_default_H2() { Props props = newProps(); assertThat(underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)) .isEqualTo(Provider.H2); assertThat(props.nonNullValue(JDBC_URL.getKey())).isEqualTo(String.format("jdbc:h2:tcp://%s:9092/sonar;NON_KEYWORDS=VALUE", InetAddress.getLoopbackAddress().getHostAddress())); } @Test public void resolve_Oracle_when_jdbc_url_contains_oracle_in_any_case() { checkProviderForUrlAndUnchangedUrl("jdbc:oracle:foo", Provider.ORACLE); checkProviderForUrlAndUnchangedUrl("jdbc:OrAcLe:foo", Provider.ORACLE); } @Test public void resolve_SqlServer_when_jdbc_url_contains_sqlserver_in_any_case() { checkProviderForUrlAndUnchangedUrl("jdbc:sqlserver:foo", Provider.SQLSERVER); checkProviderForUrlAndUnchangedUrl("jdbc:SQLSeRVeR:foo", Provider.SQLSERVER); } @Test public void resolve_POSTGRESQL_when_jdbc_url_contains_POSTGRESQL_in_any_case() { checkProviderForUrlAndUnchangedUrl("jdbc:postgresql:foo", Provider.POSTGRESQL); checkProviderForUrlAndUnchangedUrl("jdbc:POSTGRESQL:foo", Provider.POSTGRESQL); } private void checkProviderForUrlAndUnchangedUrl(String url, Provider expected) { Props props = newProps(JDBC_URL.getKey(), url); assertThat(underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)).isEqualTo(expected); assertThat(props.nonNullValue(JDBC_URL.getKey())).isEqualTo(url); } @Test public void fail_with_MessageException_when_provider_is_not_supported() { Props props = newProps(JDBC_URL.getKey(), "jdbc:microsoft:sqlserver://localhost"); assertThatThrownBy(() -> underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)) .isInstanceOf(MessageException.class) .hasMessage("Unsupported JDBC driver provider: microsoft"); } @Test public void fail_with_MessageException_when_url_does_not_have_jdbc_prefix() { Props props = newProps(JDBC_URL.getKey(), "oracle:thin:@localhost/XE"); assertThatThrownBy(() -> underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)) .isInstanceOf(MessageException.class) .hasMessage("Bad format of JDBC URL: oracle:thin:@localhost/XE"); } @Test public void checkAndComplete_sets_driver_path_for_oracle() throws Exception { File driverFile = new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc6.jar"); FileUtils.touch(driverFile); Props props = newProps(JDBC_URL.getKey(), "jdbc:oracle:thin:@localhost/XE"); underTest.accept(props); assertThat(props.nonNullValueAsFile(JDBC_DRIVER_PATH.getKey())).isEqualTo(driverFile); } @Test public void sets_driver_path_for_h2() throws Exception { File driverFile = new File(homeDir, "lib/jdbc/h2/h2.jar"); FileUtils.touch(driverFile); Props props = newProps(JDBC_URL.getKey(), "jdbc:h2:tcp://localhost:9092/sonar"); underTest.accept(props); assertThat(props.nonNullValueAsFile(JDBC_DRIVER_PATH.getKey())).isEqualTo(driverFile); } @Test public void checkAndComplete_sets_driver_path_for_postgresql() throws Exception { File driverFile = new File(homeDir, "lib/jdbc/postgresql/pg.jar"); FileUtils.touch(driverFile); Props props = newProps(JDBC_URL.getKey(), "jdbc:postgresql://localhost/sonar"); underTest.accept(props); assertThat(props.nonNullValueAsFile(JDBC_DRIVER_PATH.getKey())).isEqualTo(driverFile); } @Test public void checkAndComplete_sets_driver_path_for_mssql() throws Exception { File driverFile = new File(homeDir, "lib/jdbc/mssql/sqljdbc4.jar"); FileUtils.touch(driverFile); Props props = newProps(JDBC_URL.getKey(), "jdbc:sqlserver://localhost/sonar;SelectMethod=Cursor"); underTest.accept(props); assertThat(props.nonNullValueAsFile(JDBC_DRIVER_PATH.getKey())).isEqualTo(driverFile); } @Test public void driver_file() throws Exception { File driverFile = new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc6.jar"); FileUtils.touch(driverFile); String path = underTest.driverPath(homeDir, Provider.ORACLE); assertThat(path).isEqualTo(driverFile.getAbsolutePath()); } @Test public void driver_dir_does_not_exist() { assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) .isInstanceOf(MessageException.class) .hasMessage("Directory does not exist: extensions/jdbc-driver/oracle"); } @Test public void no_files_in_driver_dir() throws Exception { FileUtils.forceMkdir(new File(homeDir, "extensions/jdbc-driver/oracle")); assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) .isInstanceOf(MessageException.class) .hasMessage("Directory does not contain JDBC driver: extensions/jdbc-driver/oracle"); } @Test public void too_many_files_in_driver_dir() throws Exception { FileUtils.touch(new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc5.jar")); FileUtils.touch(new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc6.jar")); assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) .isInstanceOf(MessageException.class) .hasMessage("Directory must contain only one JAR file: extensions/jdbc-driver/oracle"); } private Props newProps(String... params) { Properties properties = new Properties(); for (int i = 0; i < params.length; i++) { properties.setProperty(params[i], params[i + 1]); i++; } properties.setProperty(PATH_HOME.getKey(), homeDir.getAbsolutePath()); return new Props(properties); } }
7,415
37.625
180
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/SonarQubeVersionHelperTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SonarQubeVersionHelperTest { @Test public void getSonarQubeVersion_must_not_return_an_empty_string() { assertThat(SonarQubeVersionHelper.getSonarqubeVersion()).isNotEmpty(); } @Test public void getSonarQubeVersion_must_always_return_same_value() { String sonarqubeVersion = SonarQubeVersionHelper.getSonarqubeVersion(); for (int i = 0; i < 3; i++) { assertThat(SonarQubeVersionHelper.getSonarqubeVersion()).isEqualTo(sonarqubeVersion); } } }
1,455
35.4
91
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/config/TestAppSettings.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.config; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Map; import java.util.Optional; import java.util.Properties; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Simple implementation of {@link AppSettings} that loads * the default values defined by {@link ProcessProperties}. */ public class TestAppSettings implements AppSettings { private Props props; public TestAppSettings() { this(ImmutableMap.of()); } public TestAppSettings(Map<String, String> initialSettings) { Properties properties = new Properties(); properties.putAll(initialSettings); this.props = new Props(properties); ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of()); new ProcessProperties(serviceLoaderWrapper).completeDefaults(this.props); } @Override public Props getProps() { return props; } @Override public Optional<String> getValue(String key) { return Optional.ofNullable(props.value(key)); } @Override public void reload(Props copy) { this.props = copy; } public void clearProperty(String key) { this.props.rawProperties().remove(key); } }
2,305
30.162162
81
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsConnectorImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import com.google.common.collect.Sets; import com.google.common.net.HostAndPort; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyStore; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HeldCertificate; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EsConnectorImplTest { private static final String JSON_SUCCESS_RESPONSE = "{" + " \"cluster_name\" : \"testcluster\"," + " \"status\" : \"yellow\"," + " \"timed_out\" : false," + " \"number_of_nodes\" : 1," + " \"number_of_data_nodes\" : 1," + " \"active_primary_shards\" : 1," + " \"active_shards\" : 1," + " \"relocating_shards\" : 0," + " \"initializing_shards\" : 0," + " \"unassigned_shards\" : 1," + " \"delayed_unassigned_shards\": 0," + " \"number_of_pending_tasks\" : 0," + " \"number_of_in_flight_fetch\": 0," + " \"task_max_waiting_in_queue_millis\": 0," + " \"active_shards_percent_as_number\": 50.0" + "}"; private static final String JSON_ERROR_RESPONSE = "{" + " \"error\" : \"i-have-a-bad-feelings-about-this\"" + "}"; private static final String ES_INFO_RESPONSE = "{" + " \"name\" : \"sonarqube\"," + " \"cluster_name\" : \"sonarqube\"," + " \"cluster_uuid\" : \"6Oj9lFIyQVa_d5HgQWqQpA\"," + " \"version\" : {" + " \"number\" : \"7.14.1\"," + " \"build_flavor\" : \"default\"," + " \"build_type\" : \"tar\"," + " \"build_hash\" : \"66b55ebfa59c92c15db3f69a335d500018b3331e\"," + " \"build_date\" : \"2021-08-26T09:01:05.390870785Z\"," + " \"build_snapshot\" : false," + " \"lucene_version\" : \"8.9.0\"," + " \"minimum_wire_compatibility_version\" : \"6.8.0\"," + " \"minimum_index_compatibility_version\" : \"6.0.0-beta1\"" + " }," + " \"tagline\" : \"You Know, for Search\"" + "}"; @Rule public MockWebServer mockWebServer = new MockWebServer(); @Rule public TemporaryFolder temp = new TemporaryFolder(); EsConnectorImpl underTest = new EsConnectorImpl(Sets.newHashSet(HostAndPort.fromParts(mockWebServer.getHostName(), mockWebServer.getPort())), null, null, null); @After public void after() { underTest.stop(); } @Test public void should_rethrow_if_es_exception() { mockServerResponse(500, JSON_ERROR_RESPONSE); assertThatThrownBy(() -> underTest.getClusterHealthStatus()) .isInstanceOf(ElasticsearchStatusException.class); } @Test public void should_return_status() { mockServerResponse(200, JSON_SUCCESS_RESPONSE); assertThat(underTest.getClusterHealthStatus()) .hasValue(ClusterHealthStatus.YELLOW); } @Test public void should_add_authentication_header() throws InterruptedException { mockServerResponse(200, JSON_SUCCESS_RESPONSE); String password = "test-password"; EsConnectorImpl underTest = new EsConnectorImpl(Sets.newHashSet(HostAndPort.fromParts(mockWebServer.getHostName(), mockWebServer.getPort())), password, null, null); assertThat(underTest.getClusterHealthStatus()) .hasValue(ClusterHealthStatus.YELLOW); assertThat(mockWebServer.takeRequest().getHeader("Authorization")).isEqualTo("Basic ZWxhc3RpYzp0ZXN0LXBhc3N3b3Jk"); } @Test public void newInstance_whenKeyStorePassed_shouldCreateClient() throws GeneralSecurityException, IOException { mockServerResponse(200, JSON_SUCCESS_RESPONSE); Path keyStorePath = temp.newFile("keystore.p12").toPath(); String password = "password"; HandshakeCertificates certificate = createCertificate(mockWebServer.getHostName(), keyStorePath, password); mockWebServer.useHttps(certificate.sslSocketFactory(), false); EsConnectorImpl underTest = new EsConnectorImpl(Sets.newHashSet(HostAndPort.fromParts(mockWebServer.getHostName(), mockWebServer.getPort())), null, keyStorePath, password); assertThat(underTest.getClusterHealthStatus()).hasValue(ClusterHealthStatus.YELLOW); } private HandshakeCertificates createCertificate(String hostName, Path keyStorePath, String password) throws GeneralSecurityException, IOException { HeldCertificate localhostCertificate = new HeldCertificate.Builder() .addSubjectAlternativeName(hostName) .build(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(null); ks.setKeyEntry("alias", localhostCertificate.keyPair().getPrivate(), password.toCharArray(), new java.security.cert.Certificate[]{localhostCertificate.certificate()}); ks.store(baos, password.toCharArray()); try (OutputStream outputStream = Files.newOutputStream(keyStorePath)) { outputStream.write(baos.toByteArray()); } } return new HandshakeCertificates.Builder() .heldCertificate(localhostCertificate) .build(); } private void mockServerResponse(int httpCode, String jsonResponse) { mockWebServer.enqueue(new MockResponse() .setResponseCode(200) .setBody(ES_INFO_RESPONSE) .setHeader("Content-Type", "application/json") .setHeader("X-elastic-product", "Elasticsearch")); mockWebServer.enqueue(new MockResponse() .setResponseCode(httpCode) .setBody(jsonResponse) .setHeader("Content-Type", "application/json") .setHeader("X-elastic-product", "Elasticsearch")); } }
6,839
36.582418
145
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsInstallationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import java.io.File; import java.io.IOException; import java.util.Properties; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; public class EsInstallationTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void constructor_fails_with_IAE_if_sq_home_property_is_not_defined() { Props props = new Props(new Properties()); assertThatThrownBy(() -> new EsInstallation(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property sonar.path.home is not set"); } @Test public void constructor_fails_with_IAE_if_temp_dir_property_is_not_defined() throws IOException { Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); assertThatThrownBy(() -> new EsInstallation(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property sonar.path.temp is not set"); } @Test public void constructor_fails_with_IAE_if_data_dir_property_is_not_defined() throws IOException { Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); assertThatThrownBy(() -> new EsInstallation(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property: sonar.path.data"); } @Test public void getHomeDirectory_is_elasticsearch_subdirectory_of_sq_home_directory() throws IOException { File sqHomeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getHomeDirectory()).isEqualTo(new File(sqHomeDir, "elasticsearch")); } @Test public void override_data_dir() throws Exception { File sqHomeDir = temp.newFolder(); File tempDir = temp.newFolder(); File dataDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_DATA.getKey(), dataDir.getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getDataDirectory()).isEqualTo(new File(dataDir, "es8")); } @Test public void getLogDirectory_is_configured_with_non_nullable_PATH_LOG_variable() throws IOException { File sqHomeDir = temp.newFolder(); File logDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), logDir.getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getLogDirectory()).isEqualTo(logDir); } @Test public void getOutdatedSearchDirectories_returns_all_previously_used_es_data_directory_names() throws IOException { File sqHomeDir = temp.newFolder(); File logDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), logDir.getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getOutdatedSearchDirectories()) .extracting(File::getName) .containsExactlyInAnyOrder("es", "es5", "es6", "es7"); } @Test public void conf_directory_is_conf_es_subdirectory_of_sq_temp_directory() throws IOException { File tempDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getConfDirectory()).isEqualTo(new File(tempDir, "conf/es")); } @Test public void getExecutable_resolve_executable_for_platform() throws IOException { File sqHomeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getExecutable()).isEqualTo(new File(sqHomeDir, "elasticsearch/bin/elasticsearch")); } @Test public void getLog4j2Properties_is_in_es_conf_directory() throws IOException { File tempDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getLog4j2PropertiesLocation()).isEqualTo(new File(tempDir, "conf/es/log4j2.properties")); } @Test public void getElasticsearchYml_is_in_es_conf_directory() throws IOException { File tempDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getElasticsearchYml()).isEqualTo(new File(tempDir, "conf/es/elasticsearch.yml")); } @Test public void getJvmOptions_is_in_es_conf_directory() throws IOException { File tempDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), tempDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.getJvmOptions()).isEqualTo(new File(tempDir, "conf/es/jvm.options")); } @Test public void isHttpEncryptionEnabled_shouldReturnCorrectValue() throws IOException { File sqHomeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); props.set(CLUSTER_ENABLED.getKey(), "true"); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "password"); props.set(CLUSTER_ES_HTTP_KEYSTORE.getKey(), sqHomeDir.getAbsolutePath()); EsInstallation underTest = new EsInstallation(props); assertThat(underTest.isHttpEncryptionEnabled()).isTrue(); props.set(CLUSTER_ENABLED.getKey(), "false"); props.set(CLUSTER_ES_HTTP_KEYSTORE.getKey(), sqHomeDir.getAbsolutePath()); underTest = new EsInstallation(props); assertThat(underTest.isHttpEncryptionEnabled()).isFalse(); props.set(CLUSTER_ENABLED.getKey(), "true"); props.rawProperties().remove(CLUSTER_ES_HTTP_KEYSTORE.getKey()); underTest = new EsInstallation(props); assertThat(underTest.isHttpEncryptionEnabled()).isFalse(); } }
9,948
41.15678
117
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsKeyStoreCliTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatcher; import org.sonar.application.command.JavaCommand; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class EsKeyStoreCliTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); EsInstallation esInstallation = mock(EsInstallation.class); @Test public void execute_command_should_preserve_order_of_properties() throws Exception { File homeDir = temp.newFolder(); File confDir = temp.newFolder(); when(esInstallation.getHomeDirectory()).thenReturn(homeDir); when(esInstallation.getConfDirectory()).thenReturn(confDir); EsKeyStoreCli underTest = EsKeyStoreCli.getInstance(esInstallation); underTest .store("test.property1", "value1") .store("test.property2", "value2") .store("test.property3", "value3"); MockProcess process = (MockProcess) underTest.executeWith(EsKeyStoreCliTest::mockLaunch); JavaCommand<?> executedCommand = process.getExecutedCommand(); String expectedHomeLibPath = Paths.get(homeDir.toString(), "lib") + File.separator + "*"; String expectedHomeKeystorePath = Paths.get(homeDir.toString(), "lib", "cli-launcher") + File.separator + "*"; assertThat(executedCommand.getClassName()).isEqualTo("org.elasticsearch.launcher.CliToolLauncher"); assertThat(executedCommand.getClasspath()).containsExactly(expectedHomeLibPath, expectedHomeKeystorePath); assertThat(executedCommand.getParameters()).containsExactly("add", "-x", "-f", "test.property1", "test.property2", "test.property3"); assertThat(executedCommand.getJvmOptions().getAll()).containsExactly( "-Xms4m", "-Xmx64m", "-XX:+UseSerialGC", "-Dcli.name=", "-Dcli.script=bin/elasticsearch-keystore", "-Dcli.libs=lib/tools/keystore-cli", "-Des.path.home=" + homeDir.toPath(), "-Des.path.conf=" + confDir.toPath()); verify(process.getOutputStream()).write(argThat(new ArrayContainsMatcher("value1\nvalue2\nvalue3\n")), eq(0), eq(21)); verify(process.getOutputStream(), atLeastOnce()).flush(); verify(process.getMock()).waitFor(1L, TimeUnit.MINUTES); } @Test public void ISE_if_process_exited_abnormally() throws Exception { File homeDir = temp.newFolder(); File confDir = temp.newFolder(); when(esInstallation.getHomeDirectory()).thenReturn(homeDir); when(esInstallation.getConfDirectory()).thenReturn(confDir); EsKeyStoreCli underTest = EsKeyStoreCli.getInstance(esInstallation); underTest.store("test.property1", "value1"); assertThatThrownBy(() -> underTest.executeWith(EsKeyStoreCliTest::mockFailureLaunch)) .isInstanceOf(IllegalStateException.class) .hasMessage("Elasticsearch KeyStore tool exited with code: 1"); } @Test public void fail_if_tries_to_store_null_key() throws Exception { File homeDir = temp.newFolder(); File confDir = temp.newFolder(); when(esInstallation.getHomeDirectory()).thenReturn(homeDir); when(esInstallation.getConfDirectory()).thenReturn(confDir); EsKeyStoreCli underTest = EsKeyStoreCli.getInstance(esInstallation); assertThatThrownBy(() -> underTest.store(null, "value1")) .isInstanceOf(NullPointerException.class) .hasMessage("Property key cannot be null"); } @Test public void fail_if_tries_to_store_null_value() throws Exception { File homeDir = temp.newFolder(); File confDir = temp.newFolder(); when(esInstallation.getHomeDirectory()).thenReturn(homeDir); when(esInstallation.getConfDirectory()).thenReturn(confDir); EsKeyStoreCli underTest = EsKeyStoreCli.getInstance(esInstallation); assertThatThrownBy(() -> underTest.store("key", null)) .isInstanceOf(NullPointerException.class) .hasMessage("Property value cannot be null"); } private static MockProcess mockLaunch(JavaCommand<?> javaCommand) { return new MockProcess(javaCommand); } private static MockProcess mockFailureLaunch(JavaCommand<?> javaCommand) { return new MockProcess(javaCommand, 1); } public static class ArrayContainsMatcher implements ArgumentMatcher<byte[]> { private final String left; public ArrayContainsMatcher(String left) { this.left = left; } @Override public boolean matches(byte[] right) { return new String(right).startsWith(left); } } private static class MockProcess extends Process { JavaCommand<?> executedCommand; Process process; OutputStream outputStream = mock(OutputStream.class); public MockProcess(JavaCommand<?> executedCommand) { this(executedCommand, 0); } public MockProcess(JavaCommand<?> executedCommand, int exitCode) { this.executedCommand = executedCommand; process = mock(Process.class); when(process.getOutputStream()).thenReturn(outputStream); when(process.exitValue()).thenReturn(exitCode); } public Process getMock() { return process; } public JavaCommand<?> getExecutedCommand() { return executedCommand; } @Override public OutputStream getOutputStream() { return outputStream; } @Override public InputStream getInputStream() { return null; } @Override public InputStream getErrorStream() { return null; } @Override public int waitFor() throws InterruptedException { process.waitFor(); return 0; } @Override public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { process.waitFor(timeout, unit); return true; } @Override public int exitValue() { return process.exitValue(); } @Override public void destroy() { } } }
7,145
32.707547
137
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsLoggingTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Properties; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; public class EsLoggingTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private final EsLogging underTest = new EsLogging(); @Test public void createProperties_with_empty_props() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties(newProps(), logDir); verifyProperties(properties, "status", "ERROR", "appender.file_es.type", "RollingFile", "appender.file_es.name", "file_es", "appender.file_es.filePattern", new File(logDir, "es.%d{yyyy-MM-dd}.log").getAbsolutePath(), "appender.file_es.fileName", new File(logDir, "es.log").getAbsolutePath(), "appender.file_es.layout.type", "PatternLayout", "appender.file_es.layout.pattern", "%d{yyyy.MM.dd HH:mm:ss} %-5level es[][%logger{1.}] %msg%n", "appender.file_es.policies.type", "Policies", "appender.file_es.policies.time.type", "TimeBasedTriggeringPolicy", "appender.file_es.policies.time.interval", "1", "appender.file_es.policies.time.modulate", "true", "appender.file_es.strategy.type", "DefaultRolloverStrategy", "appender.file_es.strategy.fileIndex", "nomax", "appender.file_es.strategy.action.type", "Delete", "appender.file_es.strategy.action.basepath", logDir.getAbsolutePath(), "appender.file_es.strategy.action.maxDepth", "1", "appender.file_es.strategy.action.condition.type", "IfFileName", "appender.file_es.strategy.action.condition.glob", "es*", "appender.file_es.strategy.action.condition.nested_condition.type", "IfAccumulatedFileCount", "appender.file_es.strategy.action.condition.nested_condition.exceeds", "7", "rootLogger.level", "INFO", "rootLogger.appenderRef.file_es.ref", "file_es" ); } @Test public void createProperties_sets_root_logger_to_INFO_if_no_property_is_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties(newProps(), logDir); assertThat(properties.getProperty("rootLogger.level")).isEqualTo("INFO"); } @Test public void createProperties_sets_root_logger_to_global_property_if_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties(newProps("sonar.log.level", "TRACE"), logDir); assertThat(properties.getProperty("rootLogger.level")).isEqualTo("TRACE"); } @Test public void createProperties_sets_root_logger_to_process_property_if_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties(newProps("sonar.log.level.es", "DEBUG"), logDir); assertThat(properties.getProperty("rootLogger.level")).isEqualTo("DEBUG"); } @Test public void createProperties_sets_root_logger_to_process_property_over_global_property_if_both_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties( newProps( "sonar.log.level", "DEBUG", "sonar.log.level.es", "TRACE"), logDir); assertThat(properties.getProperty("rootLogger.level")).isEqualTo("TRACE"); } @Test public void createProperties_adds_nodename_if_cluster_property_is_set() throws IOException { File logDir = temporaryFolder.newFolder(); Properties properties = underTest.createProperties( newProps( "sonar.cluster.enabled", "true", "sonar.cluster.node.name", "my-node"), logDir); assertThat(properties.getProperty("appender.file_es.layout.pattern")).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level my-node es[][%logger{1.}] %msg%n"); } private static Props newProps(String... propertyKeysAndValues) { assertThat(propertyKeysAndValues.length % 2).describedAs("Number of parameters must be even").isZero(); Properties properties = new Properties(); for (int i = 0; i < propertyKeysAndValues.length; i++) { properties.put(propertyKeysAndValues[i++], propertyKeysAndValues[i]); } return new Props(properties); } private void verifyProperties(Properties properties, String... expectedPropertyKeysAndValuesOrdered) { if (expectedPropertyKeysAndValuesOrdered.length == 0) { assertThat(properties).isEmpty(); } else { assertThat(expectedPropertyKeysAndValuesOrdered.length % 2).describedAs("Number of parameters must be even").isZero(); Set<String> keys = new HashSet<>(expectedPropertyKeysAndValuesOrdered.length / 2 + 1); keys.add("status"); for (int i = 0; i < expectedPropertyKeysAndValuesOrdered.length; i++) { String key = expectedPropertyKeysAndValuesOrdered[i++]; String value = expectedPropertyKeysAndValuesOrdered[i]; assertThat(properties.get(key)).describedAs("Unexpected value for property " + key).isEqualTo(value); keys.add(key); } assertThat(properties).containsOnlyKeys(keys.toArray()); } } }
6,192
41.710345
153
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import ch.qos.logback.classic.spi.ILoggingEvent; import com.google.common.collect.ImmutableSet; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Properties; import javax.annotation.Nullable; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.application.logging.ListAppender; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.MessageException; import org.sonar.process.ProcessProperties; import org.sonar.process.ProcessProperties.Property; import org.sonar.process.Props; import org.sonar.process.System2; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_TRUSTSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; import static org.sonar.process.ProcessProperties.Property.ES_PORT; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.SEARCH_INITIAL_STATE_TIMEOUT; import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; @RunWith(DataProviderRunner.class) public class EsSettingsTest { private static final boolean CLUSTER_ENABLED = true; private static final boolean CLUSTER_DISABLED = false; @Rule public TemporaryFolder temp = new TemporaryFolder(); private ListAppender listAppender; private final System2 system = mock(System2.class); @After public void tearDown() { if (listAppender != null) { ListAppender.detachMemoryAppenderToLoggerOf(EsSettings.class, listAppender); } } @Test public void constructor_does_not_logs_warning_if_env_variable_ES_JVM_OPTIONS_is_not_set() { this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(EsSettings.class); Props props = minimalProps(); new EsSettings(props, new EsInstallation(props), system); assertThat(listAppender.getLogs()).isEmpty(); } @Test public void constructor_does_not_logs_warning_if_env_variable_ES_JVM_OPTIONS_is_set_and_empty() { this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(EsSettings.class); Props props = minimalProps(); when(system.getenv("ES_JVM_OPTIONS")).thenReturn(" "); new EsSettings(props, new EsInstallation(props), system); assertThat(listAppender.getLogs()).isEmpty(); } @Test public void constructor_logs_warning_if_env_variable_ES_JVM_OPTIONS_is_set_and_non_empty() { this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(EsSettings.class); Props props = minimalProps(); when(system.getenv("ES_JVM_OPTIONS")).thenReturn(randomAlphanumeric(2)); new EsSettings(props, new EsInstallation(props), system); assertThat(listAppender.getLogs()) .extracting(ILoggingEvent::getMessage) .containsOnly("ES_JVM_OPTIONS is defined but will be ignored. " + "Use sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to specify jvm options for Elasticsearch"); } private Props minimalProps() { Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), randomAlphanumeric(12)); props.set(PATH_DATA.getKey(), randomAlphanumeric(12)); props.set(PATH_TEMP.getKey(), randomAlphanumeric(12)); props.set(PATH_LOGS.getKey(), randomAlphanumeric(12)); props.set(CLUSTER_NAME.getKey(), randomAlphanumeric(12)); return props; } @Test public void test_default_settings_for_standalone_mode() throws Exception { File homeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(SEARCH_PORT.getKey(), "1234"); props.set(ES_PORT.getKey(), "5678"); props.set(SEARCH_HOST.getKey(), "127.0.0.1"); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); props.set(CLUSTER_NAME.getKey(), "sonarqube"); EsSettings esSettings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> generated = esSettings.build(); assertThat(generated).containsEntry("transport.port", "5678") .containsEntry("transport.host", "127.0.0.1") .containsEntry("http.port", "1234") .containsEntry("http.host", "127.0.0.1") // no cluster, but cluster and node names are set though .containsEntry("cluster.name", "sonarqube") .containsEntry("node.name", "sonarqube") .containsEntry("discovery.type", "single-node") .doesNotContainKey("discovery.seed_hosts") .doesNotContainKey("cluster.initial_master_nodes"); assertThat(generated.get("path.data")).isNotNull(); assertThat(generated.get("path.logs")).isNotNull(); assertThat(generated.get("path.home")).isNull(); assertThat(generated.get("path.conf")).isNull(); assertThat(generated) .containsEntry("discovery.initial_state_timeout", "30s") .containsEntry("action.auto_create_index", "false"); } @Test public void test_default_settings_for_cluster_mode() throws Exception { File homeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(SEARCH_PORT.getKey(), "1234"); props.set(SEARCH_HOST.getKey(), "127.0.0.1"); props.set(CLUSTER_NODE_SEARCH_HOST.getKey(), "127.0.0.1"); props.set(CLUSTER_NODE_SEARCH_PORT.getKey(), "1234"); props.set(CLUSTER_NODE_ES_HOST.getKey(), "127.0.0.1"); props.set(CLUSTER_NODE_ES_PORT.getKey(), "1234"); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); props.set(CLUSTER_NAME.getKey(), "sonarqube-1"); props.set(Property.CLUSTER_ENABLED.getKey(), "true"); props.set(CLUSTER_NODE_NAME.getKey(), "node-1"); EsSettings esSettings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> generated = esSettings.build(); assertThat(generated) .containsEntry("cluster.name", "sonarqube-1") .containsEntry("node.name", "node-1"); } @Test public void test_node_name_default_for_cluster_mode() throws Exception { File homeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(CLUSTER_NAME.getKey(), "sonarqube"); props.set(Property.CLUSTER_ENABLED.getKey(), "true"); props.set(SEARCH_PORT.getKey(), "1234"); props.set(SEARCH_HOST.getKey(), "127.0.0.1"); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsSettings esSettings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> generated = esSettings.build(); assertThat(generated.get("node.name")).startsWith("sonarqube-"); } @Test public void test_node_name_default_for_standalone_mode() throws Exception { File homeDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(CLUSTER_NAME.getKey(), "sonarqube"); props.set(Property.CLUSTER_ENABLED.getKey(), "false"); props.set(SEARCH_PORT.getKey(), "1234"); props.set(ES_PORT.getKey(), "5678"); props.set(SEARCH_HOST.getKey(), "127.0.0.1"); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_TEMP.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); EsSettings esSettings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> generated = esSettings.build(); assertThat(generated).containsEntry("node.name", "sonarqube"); } @Test public void path_properties_are_values_from_EsFileSystem_argument() throws IOException { File foo = temp.newFolder(); EsInstallation mockedEsInstallation = mock(EsInstallation.class); File home = new File(foo, "home"); when(mockedEsInstallation.getHomeDirectory()).thenReturn(home); File conf = new File(foo, "conf"); when(mockedEsInstallation.getConfDirectory()).thenReturn(conf); File log = new File(foo, "log"); when(mockedEsInstallation.getLogDirectory()).thenReturn(log); File data = new File(foo, "data"); when(mockedEsInstallation.getDataDirectory()).thenReturn(data); EsSettings underTest = new EsSettings(minProps(true), mockedEsInstallation, system); Map<String, String> generated = underTest.build(); assertThat(generated) .containsEntry("path.data", data.getPath()) .containsEntry("path.logs", log.getPath()); assertThat(generated.get("path.conf")).isNull(); } @Test public void set_discovery_settings_if_cluster_is_enabled() throws Exception { Props props = minProps(CLUSTER_ENABLED); props.set(CLUSTER_ES_HOSTS.getKey(), "1.2.3.4:9000,1.2.3.5:8080"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings) .containsEntry("discovery.seed_hosts", "1.2.3.4:9000,1.2.3.5:8080") .containsEntry("discovery.initial_state_timeout", "120s"); } @Test public void set_initial_master_nodes_settings_if_cluster_is_enabled() throws Exception { Props props = minProps(CLUSTER_ENABLED); props.set(CLUSTER_ES_HOSTS.getKey(), "1.2.3.4:9000,1.2.3.5:8080"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), System2.INSTANCE).build(); assertThat(settings) .containsEntry("cluster.initial_master_nodes", "1.2.3.4:9000,1.2.3.5:8080") .containsEntry("discovery.initial_state_timeout", "120s"); } @Test public void cluster_is_enabled_with_defined_initialTimeout() throws Exception { Props props = minProps(CLUSTER_ENABLED); props.set(SEARCH_INITIAL_STATE_TIMEOUT.getKey(), "10s"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings).containsEntry("discovery.initial_state_timeout", "10s"); } @Test public void in_standalone_initialTimeout_is_not_overridable() throws Exception { Props props = minProps(CLUSTER_DISABLED); props.set(SEARCH_INITIAL_STATE_TIMEOUT.getKey(), "10s"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings).containsEntry("discovery.initial_state_timeout", "30s"); } @Test @UseDataProvider("clusterEnabledOrNot") public void enable_http_connector_on_port_9001_by_default(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings) .containsEntry("http.port", "9001") .containsEntry("http.host", "127.0.0.1"); } @Test @UseDataProvider("clusterEnabledOrNot") public void enable_http_connector_on_specified_port(boolean clusterEnabled) throws Exception { String port = "" + 49150; Props props = minProps(clusterEnabled, null, port); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), System2.INSTANCE).build(); assertThat(settings) .containsEntry("http.port", port) .containsEntry("http.host", "127.0.0.1"); } @Test @UseDataProvider("clusterEnabledOrNot") public void enable_http_connector_different_host(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled, "127.0.0.2", null); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings) .containsEntry("http.port", "9001") .containsEntry("http.host", "127.0.0.2"); } @Test @UseDataProvider("clusterEnabledOrNot") public void enable_seccomp_filter_by_default(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings.get("bootstrap.system_call_filter")).isNull(); } @Test @UseDataProvider("clusterEnabledOrNot") public void disable_seccomp_filter_if_configured_in_search_additional_props(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); props.set("sonar.search.javaAdditionalOpts", "-Xmx1G -Dbootstrap.system_call_filter=false -Dfoo=bar"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings).containsEntry("bootstrap.system_call_filter", "false"); } @Test @UseDataProvider("clusterEnabledOrNot") public void disable_mmap_if_configured_in_search_additional_props(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); props.set("sonar.search.javaAdditionalOpts", "-Dnode.store.allow_mmap=false"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(settings).containsEntry("node.store.allow_mmap", "false"); } @Test @UseDataProvider("clusterEnabledOrNot") public void throw_exception_if_old_mmap_property_is_used(boolean clusterEnabled) throws Exception { Props props = minProps(clusterEnabled); props.set("sonar.search.javaAdditionalOpts", "-Dnode.store.allow_mmapfs=false"); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); assertThatThrownBy(settings::build) .isInstanceOf(MessageException.class) .hasMessage("Property 'node.store.allow_mmapfs' is no longer supported. Use 'node.store.allow_mmap' instead."); } @Test public void configureSecurity_givenClusterSearchPasswordNotProvided_dontAddXpackParameters() throws Exception { Props props = minProps(true); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> outputParams = settings.build(); assertThat(outputParams.get("xpack.security.transport.ssl.enabled")).isNull(); } @Test public void configureSecurity_givenClusterSearchPasswordProvided_addXpackParameters_file_exists() throws Exception { Props props = minProps(true); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); File keystore = temp.newFile("keystore.p12"); File truststore = temp.newFile("truststore.p12"); props.set(CLUSTER_ES_KEYSTORE.getKey(), keystore.getAbsolutePath()); props.set(CLUSTER_ES_TRUSTSTORE.getKey(), truststore.getAbsolutePath()); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> outputParams = settings.build(); assertThat(outputParams) .containsEntry("xpack.security.transport.ssl.enabled", "true") .containsEntry("xpack.security.transport.ssl.supported_protocols", "TLSv1.3,TLSv1.2") .containsEntry("xpack.security.transport.ssl.keystore.path", keystore.getName()) .containsEntry("xpack.security.transport.ssl.truststore.path", truststore.getName()); } @Test public void configureSecurity_givenClusterSearchPasswordProvidedButKeystorePathMissing_throwException() throws Exception { Props props = minProps(true); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); assertThatThrownBy(settings::build) .isInstanceOf(MessageException.class) .hasMessage("CLUSTER_ES_KEYSTORE property need to be set when using elastic search authentication"); } @Test public void configureSecurity_givenClusterModeFalse_dontAddXpackParameters() throws Exception { Props props = minProps(false); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> outputParams = settings.build(); assertThat(outputParams.get("xpack.security.transport.ssl.enabled")).isNull(); } @Test public void configureSecurity_givenFileNotExist_throwException() throws Exception { Props props = minProps(true); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); File truststore = temp.newFile("truststore.p12"); props.set(CLUSTER_ES_KEYSTORE.getKey(), "not-existing-file"); props.set(CLUSTER_ES_TRUSTSTORE.getKey(), truststore.getAbsolutePath()); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); assertThatThrownBy(settings::build) .isInstanceOf(MessageException.class) .hasMessage("Unable to configure: sonar.cluster.es.ssl.keystore. File specified in [not-existing-file] does not exist"); } @Test public void configureSecurity_whenHttpKeystoreProvided_shouldAddHttpProperties() throws Exception { Props props = minProps(true); File keystore = temp.newFile("keystore.p12"); File truststore = temp.newFile("truststore.p12"); File httpKeystore = temp.newFile("http-keystore.p12"); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); props.set(CLUSTER_ES_KEYSTORE.getKey(), keystore.getAbsolutePath()); props.set(CLUSTER_ES_TRUSTSTORE.getKey(), truststore.getAbsolutePath()); props.set(CLUSTER_ES_HTTP_KEYSTORE.getKey(), httpKeystore.getAbsolutePath()); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> outputParams = settings.build(); assertThat(outputParams) .containsEntry("xpack.security.http.ssl.enabled", "true") .containsEntry("xpack.security.http.ssl.keystore.path", httpKeystore.getName()); } @Test public void configureSecurity_whenHttpKeystoreNotProvided_shouldNotAddHttpProperties() throws Exception { Props props = minProps(true); File keystore = temp.newFile("keystore.p12"); File truststore = temp.newFile("truststore.p12"); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); props.set(CLUSTER_ES_KEYSTORE.getKey(), keystore.getAbsolutePath()); props.set(CLUSTER_ES_TRUSTSTORE.getKey(), truststore.getAbsolutePath()); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); Map<String, String> outputParams = settings.build(); assertThat(outputParams) .doesNotContainKey("xpack.security.http.ssl.enabled") .doesNotContainKey("xpack.security.http.ssl.keystore.path"); } @Test public void configureSecurity_whenHttpKeystoreProvided_shouldFailIfNotExists() throws Exception { Props props = minProps(true); File keystore = temp.newFile("keystore.p12"); File truststore = temp.newFile("truststore.p12"); props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty"); props.set(CLUSTER_ES_KEYSTORE.getKey(), keystore.getAbsolutePath()); props.set(CLUSTER_ES_TRUSTSTORE.getKey(), truststore.getAbsolutePath()); props.set(CLUSTER_ES_HTTP_KEYSTORE.getKey(), "not-existing-file"); EsSettings settings = new EsSettings(props, new EsInstallation(props), system); assertThatThrownBy(settings::build) .isInstanceOf(MessageException.class) .hasMessage("Unable to configure: sonar.cluster.es.http.ssl.keystore. File specified in [not-existing-file] does not exist"); } @DataProvider public static Object[][] clusterEnabledOrNot() { return new Object[][] { {false}, {true} }; } private Props minProps(boolean cluster) throws IOException { return minProps(cluster, null, null); } private Props minProps(boolean cluster, @Nullable String host, @Nullable String port) throws IOException { File homeDir = temp.newFolder(); Props props = new Props(new Properties()); ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of()); new ProcessProperties(serviceLoaderWrapper).completeDefaults(props); props.set(PATH_HOME.getKey(), homeDir.getAbsolutePath()); props.set(Property.CLUSTER_ENABLED.getKey(), Boolean.toString(cluster)); if (cluster) { ofNullable(host).ifPresent(h -> props.set(CLUSTER_NODE_ES_HOST.getKey(), h)); ofNullable(port).ifPresent(p -> props.set(CLUSTER_NODE_ES_PORT.getKey(), p)); ofNullable(host).ifPresent(h -> props.set(CLUSTER_NODE_SEARCH_HOST.getKey(), h)); ofNullable(port).ifPresent(p -> props.set(CLUSTER_NODE_SEARCH_PORT.getKey(), p)); ofNullable(port).ifPresent(h -> props.set(CLUSTER_ES_HOSTS.getKey(), h)); } else { ofNullable(host).ifPresent(h -> props.set(SEARCH_HOST.getKey(), h)); ofNullable(port).ifPresent(p -> props.set(SEARCH_PORT.getKey(), p)); } return props; } }
23,407
43.166038
137
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/es/EsYmlSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import java.io.File; import java.io.IOException; import java.util.HashMap; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EsYmlSettingsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void test_generation_of_file() throws IOException { File yamlFile = temp.newFile(); new EsYmlSettings(new HashMap<>()).writeToYmlSettingsFile(yamlFile); assertThat(yamlFile) .exists() .hasContent(""" # This file has been automatically generated by SonarQube during startup. # DO NOT EDIT THIS FILE { }"""); } @Test public void if_file_is_not_writable_ISE_must_be_thrown() throws IOException { File yamlFile = temp.newFile(); yamlFile.setReadOnly(); assertThatThrownBy(() -> new EsYmlSettings(new HashMap<>()).writeToYmlSettingsFile(yamlFile)) .isInstanceOf(IllegalStateException.class) .hasMessage("Cannot write Elasticsearch yml settings file"); } }
2,026
31.174603
97
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/logging/ListAppender.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.logging; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.ArrayList; import java.util.List; import org.sonar.process.logging.LogbackHelper; public final class ListAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> logs = new ArrayList<>(); @Override protected void append(ILoggingEvent eventObject) { logs.add(eventObject); } public List<ILoggingEvent> getLogs() { return logs; } public static <T> ListAppender attachMemoryAppenderToLoggerOf(Class<T> loggerClass) { ListAppender listAppender = new ListAppender(); new LogbackHelper().getRootContext().getLogger(loggerClass) .addAppender(listAppender); listAppender.start(); return listAppender; } public static <T> void detachMemoryAppenderToLoggerOf(Class<T> loggerClass, ListAppender listAppender) { listAppender.stop(); new LogbackHelper().getRootContext().getLogger(loggerClass) .detachAppender(listAppender); } }
1,899
34.185185
106
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/process/EsManagedProcessTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.net.ConnectException; import java.util.Optional; import java.util.concurrent.ExecutionException; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Test; import org.sonar.application.es.EsConnector; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EsManagedProcessTest { private final static int WAIT_FOR_UP_TIMEOUT = 1; private final static int WAIT_FOR_UP_TIMEOUT_LONG = 2; @Test public void isOperational_should_return_false_if_status_is_unknown() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.empty()); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_return_false_if_Elasticsearch_is_RED() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.RED)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_return_true_if_Elasticsearch_is_YELLOW() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.YELLOW)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isTrue(); } @Test public void isOperational_should_return_true_if_Elasticsearch_is_GREEN() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.GREEN)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isTrue(); } @Test public void isOperational_should_return_true_if_Elasticsearch_was_GREEN_once() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.GREEN)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isTrue(); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.RED)); assertThat(underTest.isOperational()).isTrue(); } @Test public void isOperational_should_retry_if_Elasticsearch_is_unreachable() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenReturn(Optional.empty()) .thenReturn(Optional.of(ClusterHealthStatus.GREEN)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isTrue(); } @Test public void isOperational_should_return_false_if_Elasticsearch_status_cannot_be_evaluated() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new RuntimeException("test")); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_return_false_if_ElasticsearchException_with_connection_refused_thrown() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException("Connection refused")); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_return_false_if_ElasticsearchException_with_connection_timeout_thrown() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException(new ExecutionException(new ConnectException("Timeout connecting to [/127.0.0.1:9001]")))); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT_LONG); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_not_be_os_language_sensitive() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException(new ExecutionException(new ConnectException("Connexion refusée")))); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT_LONG); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_if_exception_root_cause_returned_by_ES_is_not_ConnectException_should_return_false() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException(new ExecutionException(new Exception("Connexion refusée")))); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT_LONG); assertThat(underTest.isOperational()).isFalse(); } @Test public void isOperational_should_return_false_if_ElasticsearchException_thrown() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException("test")); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessId.ELASTICSEARCH, esConnector, WAIT_FOR_UP_TIMEOUT); assertThat(underTest.isOperational()).isFalse(); } }
7,193
47.938776
139
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessHandlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.io.InputStream; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.mockito.Mockito; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.sonar.application.process.ManagedProcessHandler.Timeout.newTimeout; public class ManagedProcessHandlerTest { private static final ProcessId A_PROCESS_ID = ProcessId.ELASTICSEARCH; @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Test public void initial_state_is_INIT() { ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID).build(); assertThat(underTest.getProcessId()).isEqualTo(A_PROCESS_ID); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.INIT); } @Test public void start_and_stop_process() { ProcessLifecycleListener listener = mock(ProcessLifecycleListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addProcessLifecycleListener(listener) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { assertThat(underTest.start(() -> testProcess)).isTrue(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STARTED); assertThat(testProcess.isAlive()).isTrue(); assertThat(testProcess.streamsClosed).isFalse(); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.STARTED); testProcess.close(); Awaitility.await() .atMost(10, TimeUnit.SECONDS) .until(() -> underTest.getState() == ManagedProcessLifecycle.State.STOPPED); assertThat(testProcess.isAlive()).isFalse(); assertThat(testProcess.streamsClosed).isTrue(); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.STOPPED); } } private ManagedProcessHandler.Builder newHanderBuilder(ProcessId aProcessId) { return ManagedProcessHandler.builder(aProcessId) .setStopTimeout(newTimeout(1, TimeUnit.SECONDS)) .setHardStopTimeout(newTimeout(1, TimeUnit.SECONDS)); } @Test public void start_does_not_nothing_if_already_started_once() { ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID).build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { assertThat(underTest.start(() -> testProcess)).isTrue(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STARTED); assertThat(underTest.start(() -> { throw new IllegalStateException(); })).isFalse(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STARTED); } } @Test public void start_throws_exception_and_move_to_state_STOPPED_if_execution_of_command_fails() { ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID).build(); assertThatThrownBy(() -> { underTest.start(() -> { throw new IllegalStateException("error"); }); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); }) .isInstanceOf(IllegalStateException.class) .hasMessage("error"); } @Test public void send_event_when_process_is_operational() { ManagedProcessEventListener listener = mock(ManagedProcessEventListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addEventListener(listener) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); testProcess.operational = true; underTest.refreshState(); verify(listener).onManagedProcessEvent(A_PROCESS_ID, ManagedProcessEventListener.Type.OPERATIONAL); } verifyNoMoreInteractions(listener); } @Test public void operational_event_is_sent_once() { ManagedProcessEventListener listener = mock(ManagedProcessEventListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addEventListener(listener) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); testProcess.operational = true; underTest.refreshState(); verify(listener).onManagedProcessEvent(A_PROCESS_ID, ManagedProcessEventListener.Type.OPERATIONAL); // second run underTest.refreshState(); verifyNoMoreInteractions(listener); } } @Test public void send_event_when_process_requests_for_restart() { ManagedProcessEventListener listener = mock(ManagedProcessEventListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addEventListener(listener) .setWatcherDelayMs(1L) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); testProcess.askedForRestart = true; verify(listener, timeout(10_000)).onManagedProcessEvent(A_PROCESS_ID, ManagedProcessEventListener.Type.ASK_FOR_RESTART); // flag is reset so that next run does not trigger again the event underTest.refreshState(); verifyNoMoreInteractions(listener); assertThat(testProcess.askedForRestart).isFalse(); } } @Test public void process_stops_after_graceful_request_for_stop() throws Exception { ProcessLifecycleListener listener = mock(ProcessLifecycleListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addProcessLifecycleListener(listener) .setHardStopTimeout(newTimeout(1, TimeUnit.HOURS)) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); Thread stopperThread = new Thread(() -> { try { underTest.hardStop(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); stopperThread.start(); // thread is blocked until process stopped assertThat(stopperThread.isAlive()).isTrue(); // wait for the stopper thread to ask graceful stop while (!testProcess.askedForHardStop) { Thread.sleep(1L); } assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.HARD_STOPPING); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.HARD_STOPPING); // process stopped testProcess.close(); // waiting for stopper thread to detect and handle the stop stopperThread.join(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.STOPPED); } } @Test public void process_is_hard_stopped_if_graceful_stop_is_too_long() throws Exception { ProcessLifecycleListener listener = mock(ProcessLifecycleListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addProcessLifecycleListener(listener) .setStopTimeout(newTimeout(1, TimeUnit.MILLISECONDS)) .setHardStopTimeout(newTimeout(1, TimeUnit.MILLISECONDS)) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); underTest.stop(); testProcess.waitFor(); assertThat(testProcess.askedForHardStop).isTrue(); assertThat(testProcess.askedForStop).isTrue(); assertThat(testProcess.destroyedForcibly).isTrue(); assertThat(testProcess.isAlive()).isFalse(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.STOPPED); } } @Test public void process_is_stopped_forcibly_if_hard_stop_is_too_long() throws Exception { ProcessLifecycleListener listener = mock(ProcessLifecycleListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addProcessLifecycleListener(listener) .setHardStopTimeout(newTimeout(1, TimeUnit.MILLISECONDS)) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); underTest.hardStop(); testProcess.waitFor(); assertThat(testProcess.askedForHardStop).isTrue(); assertThat(testProcess.destroyedForcibly).isTrue(); assertThat(testProcess.isAlive()).isFalse(); assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); verify(listener).onProcessState(A_PROCESS_ID, ManagedProcessLifecycle.State.STOPPED); } } @Test public void process_requests_are_listened_on_regular_basis() { ManagedProcessEventListener listener = mock(ManagedProcessEventListener.class); ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID) .addEventListener(listener) .setWatcherDelayMs(1L) .build(); try (TestManagedProcess testProcess = new TestManagedProcess()) { underTest.start(() -> testProcess); testProcess.operational = true; verify(listener, timeout(1_000L)).onManagedProcessEvent(A_PROCESS_ID, ManagedProcessEventListener.Type.OPERATIONAL); } } @Test public void test_toString() { ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID).build(); assertThat(underTest).hasToString("Process[" + A_PROCESS_ID.getHumanReadableName() + "]"); } private static class TestManagedProcess implements ManagedProcess, AutoCloseable { private final CountDownLatch alive = new CountDownLatch(1); private final InputStream inputStream = mock(InputStream.class, Mockito.RETURNS_MOCKS); private final InputStream errorStream = mock(InputStream.class, Mockito.RETURNS_MOCKS); private boolean streamsClosed = false; private boolean operational = false; private boolean askedForRestart = false; private boolean askedForStop = false; private boolean askedForHardStop = false; private boolean destroyedForcibly = false; @Override public InputStream getInputStream() { return inputStream; } @Override public InputStream getErrorStream() { return errorStream; } @Override public void closeStreams() { streamsClosed = true; } @Override public boolean isAlive() { return alive.getCount() == 1; } @Override public void askForStop() { askedForStop = true; // do not stop, just asking } @Override public void askForHardStop() { askedForHardStop = true; // do not stop, just asking } @Override public void destroyForcibly() { destroyedForcibly = true; alive.countDown(); } @Override public void waitFor() throws InterruptedException { alive.await(); } @Override public void waitFor(long timeout, TimeUnit timeoutUnit) throws InterruptedException { alive.await(timeout, timeoutUnit); } @Override public boolean isOperational() { return operational; } @Override public boolean askedForRestart() { return askedForRestart; } @Override public void acknowledgeAskForRestart() { this.askedForRestart = false; } @Override public void close() { alive.countDown(); } } }
12,652
33.571038
126
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessLifecycleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.process.ProcessId; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.application.process.ManagedProcessLifecycle.State; import static org.sonar.application.process.ManagedProcessLifecycle.State.FINALIZE_STOPPING; import static org.sonar.application.process.ManagedProcessLifecycle.State.HARD_STOPPING; import static org.sonar.application.process.ManagedProcessLifecycle.State.INIT; import static org.sonar.application.process.ManagedProcessLifecycle.State.STARTED; import static org.sonar.application.process.ManagedProcessLifecycle.State.STARTING; import static org.sonar.application.process.ManagedProcessLifecycle.State.STOPPED; import static org.sonar.application.process.ManagedProcessLifecycle.State.STOPPING; @RunWith(DataProviderRunner.class) public class ManagedProcessLifecycleTest { @Test public void initial_state_is_INIT() { ManagedProcessLifecycle lifecycle = new ManagedProcessLifecycle(ProcessId.ELASTICSEARCH, emptyList()); assertThat(lifecycle.getState()).isEqualTo(INIT); } @Test public void listeners_are_not_notified_of_INIT_state() { TestLifeCycleListener listener = new TestLifeCycleListener(); new ManagedProcessLifecycle(ProcessId.ELASTICSEARCH, Arrays.asList(listener)); assertThat(listener.states).isEmpty(); } @Test public void try_to_move_does_not_support_jumping_states() { TestLifeCycleListener listener = new TestLifeCycleListener(); ManagedProcessLifecycle lifecycle = new ManagedProcessLifecycle(ProcessId.ELASTICSEARCH, asList(listener)); assertThat(lifecycle.getState()).isEqualTo(INIT); assertThat(listener.states).isEmpty(); assertThat(lifecycle.tryToMoveTo(STARTED)).isFalse(); assertThat(lifecycle.getState()).isEqualTo(INIT); assertThat(listener.states).isEmpty(); assertThat(lifecycle.tryToMoveTo(STARTING)).isTrue(); assertThat(lifecycle.getState()).isEqualTo(STARTING); assertThat(listener.states).containsOnly(STARTING); } @Test @UseDataProvider("allStates") public void no_state_can_not_move_to_itself(State state) { assertThat(newLifeCycle(state).tryToMoveTo(state)).isFalse(); } @Test @UseDataProvider("allStates") public void can_move_to_HARD_STOPPING_from_STARTING_AND_STARTED_and_STOPPING_only(State state) { verifyCanMoveTo(t -> t == STARTING || t == STARTED || t == STOPPING, state, HARD_STOPPING); } @Test @UseDataProvider("allStates") public void can_move_to_STARTED_from_STARTING_only(State state) { verifyCanMoveTo(t -> t == STARTING, state, STARTED); } private void verifyCanMoveTo(Predicate<State> isAllowed, State from, State to) { TestLifeCycleListener listener = new TestLifeCycleListener(); ManagedProcessLifecycle underTest = newLifeCycle(from, listener); boolean tryToMoveTo = underTest.tryToMoveTo(to); if (isAllowed.test(from)) { assertThat(tryToMoveTo).isTrue(); } else { assertThat(tryToMoveTo).isFalse(); } } @Test @UseDataProvider("allStates") public void cannot_move_to_any_state_from_STOPPED(State state) { assertThat(newLifeCycle(STOPPED).tryToMoveTo(state)).isFalse(); } private static ManagedProcessLifecycle newLifeCycle(State from, State to, TestLifeCycleListener... listeners) { ManagedProcessLifecycle lifecycle = newLifeCycle(from, listeners); assertThat(lifecycle.tryToMoveTo(to)).isTrue(); assertThat(lifecycle.getState()).isEqualTo(to); Arrays.stream(listeners) .forEach(t -> assertThat(t.states).endsWith(to)); return lifecycle; } /** * Creates a Lifecycle object in the specified state emulating that the shortest path to this state has been followed * to reach it. */ private static ManagedProcessLifecycle newLifeCycle(State state, TestLifeCycleListener... listeners) { switch (state) { case INIT: return new ManagedProcessLifecycle(ProcessId.ELASTICSEARCH, asList(listeners)); case STARTING: return newLifeCycle(INIT, state, listeners); case STARTED: return newLifeCycle(STARTING, state, listeners); case STOPPING: return newLifeCycle(STARTED, state, listeners); case HARD_STOPPING: return newLifeCycle(STARTED, state, listeners); case FINALIZE_STOPPING: return newLifeCycle(STOPPING, state, listeners); case STOPPED: return newLifeCycle(FINALIZE_STOPPING, state, listeners); default: throw new IllegalStateException("new state is not supported:" + state); } } @DataProvider public static Object[][] allStates() { return Arrays.stream(State.values()) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } private static final class TestLifeCycleListener implements ProcessLifecycleListener { private final List<State> states = new ArrayList<>(); @Override public void onProcessState(ProcessId processId, State state) { this.states.add(state); } } }
6,310
37.717791
119
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/process/ProcessCommandsManagedProcessTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ProcessCommandsManagedProcessTest { @Test public void ProcessMonitorImpl_is_a_proxy_of_Process() throws Exception { Process process = mock(Process.class, RETURNS_DEEP_STUBS); ProcessCommands commands = mock(ProcessCommands.class, RETURNS_DEEP_STUBS); ProcessCommandsManagedProcess underTest = new ProcessCommandsManagedProcess(process, ProcessId.WEB_SERVER, commands); underTest.waitFor(); verify(process).waitFor(); underTest.closeStreams(); verify(process.getErrorStream()).close(); verify(process.getInputStream()).close(); verify(process.getOutputStream()).close(); underTest.destroyForcibly(); verify(process).destroyForcibly(); assertThat(underTest.getInputStream()).isNotNull(); underTest.isAlive(); verify(process).isAlive(); underTest.waitFor(123, TimeUnit.MILLISECONDS); verify(process).waitFor(123, TimeUnit.MILLISECONDS); } @Test public void ProcessMonitorImpl_is_a_proxy_of_Commands() { Process process = mock(Process.class, RETURNS_DEEP_STUBS); ProcessCommands commands = mock(ProcessCommands.class, RETURNS_DEEP_STUBS); ProcessCommandsManagedProcess underTest = new ProcessCommandsManagedProcess(process, null, commands); underTest.askForHardStop(); verify(commands).askForHardStop(); underTest.acknowledgeAskForRestart(); verify(commands).acknowledgeAskForRestart(); underTest.askedForRestart(); verify(commands).askedForRestart(); underTest.isOperational(); verify(commands).isOperational(); } @Test public void closeStreams_ignores_null_stream() { ProcessCommands commands = mock(ProcessCommands.class); Process process = mock(Process.class); when(process.getInputStream()).thenReturn(null); ProcessCommandsManagedProcess underTest = new ProcessCommandsManagedProcess(process, null, commands); // no failures underTest.closeStreams(); } @Test public void closeStreams_ignores_failure_if_stream_fails_to_be_closed() throws Exception { InputStream stream = mock(InputStream.class); doThrow(new IOException("error")).when(stream).close(); Process process = mock(Process.class); when(process.getInputStream()).thenReturn(stream); ProcessCommandsManagedProcess underTest = new ProcessCommandsManagedProcess(process, null, mock(ProcessCommands.class, Mockito.RETURNS_MOCKS)); // no failures underTest.closeStreams(); } }
3,851
34.018182
147
java
sonarqube
sonarqube-master/server/sonar-main/src/test/java/org/sonar/application/process/StreamGobblerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.process; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.sonar.application.config.AppSettings; import org.sonar.process.Props; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.LOG_JSON_OUTPUT; public class StreamGobblerTest { private AppSettings appSettings = mock(AppSettings.class); private Props props = mock(Props.class); @Before public void before() { when(props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), false)).thenReturn(false); when(appSettings.getProps()).thenReturn(props); } @Test public void forward_stream_to_log() { InputStream stream = IOUtils.toInputStream("one\nsecond log\nthird log\n", StandardCharsets.UTF_8); Logger logger = mock(Logger.class); Logger startupLogger = mock(Logger.class); StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, startupLogger); verifyNoInteractions(logger); gobbler.start(); StreamGobbler.waitUntilFinish(gobbler); verify(logger).info("one"); verify(logger).info("second log"); verify(logger).info("third log"); verifyNoMoreInteractions(logger); verifyNoInteractions(startupLogger); } @Test public void startupLogIsLoggedWhenJSONFormatIsNotActive() { InputStream stream = IOUtils.toInputStream("[startup] Admin is still using default credentials\nsecond log\n", StandardCharsets.UTF_8); Logger startupLogger = mock(Logger.class); Logger logger = mock(Logger.class); StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, startupLogger); verifyNoInteractions(startupLogger); gobbler.start(); StreamGobbler.waitUntilFinish(gobbler); verify(startupLogger).warn("Admin is still using default credentials"); verifyNoMoreInteractions(startupLogger); } /* * This is scenario for known limitation of our approach when we detect more than we should - logs here are not really coming * from a startup log from subprocess but from some other log but the message contains '[startup]' */ @Test public void startupLogIsLoggedWhenJSONFormatNotActiveAndMatchingStringIsIntMiddleOfTheTest() { InputStream stream = IOUtils.toInputStream("Some other not [startup] log\nsecond log\n", StandardCharsets.UTF_8); Logger startupLogger = mock(Logger.class); Logger logger = mock(Logger.class); StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, startupLogger); verifyNoInteractions(startupLogger); gobbler.start(); StreamGobbler.waitUntilFinish(gobbler); verify(startupLogger).warn("log"); verifyNoMoreInteractions(startupLogger); } @Test public void startupLogIsLoggedWhenJSONFormatIsActive() { when(props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), false)).thenReturn(true); InputStream stream = IOUtils.toInputStream("{ \"logger\": \"startup\", \"message\": \"Admin is still using default credentials\"}\n", StandardCharsets.UTF_8); Logger startupLogger = mock(Logger.class); Logger logger = mock(Logger.class); StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, startupLogger); verifyNoInteractions(startupLogger); gobbler.start(); StreamGobbler.waitUntilFinish(gobbler); verify(startupLogger).warn("Admin is still using default credentials"); verifyNoMoreInteractions(startupLogger); } @Test public void startupLogIsNotLoggedWhenJSONFormatIsActiveAndLogHasWrongName() { when(props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), false)).thenReturn(true); InputStream stream = IOUtils.toInputStream("{ \"logger\": \"wrong-logger\", \"message\": \"Admin 'startup' is still using default credentials\"}\n", StandardCharsets.UTF_8); Logger startupLogger = mock(Logger.class); Logger logger = mock(Logger.class); StreamGobbler gobbler = new StreamGobbler(stream, "WEB", appSettings, logger, startupLogger); verifyNoInteractions(startupLogger); gobbler.start(); StreamGobbler.waitUntilFinish(gobbler); verifyNoMoreInteractions(startupLogger); } }
5,332
36.822695
152
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/AbstractStopperThread.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.LoggerFactory; /** * Stops process in a short time fashion */ abstract class AbstractStopperThread extends Thread { private final Runnable stopCode; private final long terminationTimeoutMs; AbstractStopperThread(String threadName, Runnable stopCode, long terminationTimeoutMs) { super(threadName); this.setDaemon(true); this.stopCode = stopCode; this.terminationTimeoutMs = terminationTimeoutMs; } @Override public void run() { ExecutorService executor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat(getName() + "-%d") .build()); try { Future future = executor.submit(stopCode); future.get(terminationTimeoutMs, TimeUnit.MILLISECONDS); } catch (TimeoutException | InterruptedException e) { LoggerFactory.getLogger(getClass()).warn("Can not stop in {}ms", terminationTimeoutMs); } catch (ExecutionException e) { LoggerFactory.getLogger(getClass()).error("Can not stop in {}ms", terminationTimeoutMs, e); } executor.shutdownNow(); } public void stopIt() { super.interrupt(); } }
2,353
33.617647
97
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Base64Cipher.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import org.apache.commons.codec.binary.Base64; import java.nio.charset.StandardCharsets; final class Base64Cipher implements Cipher { @Override public String encrypt(String clearText) { return Base64.encodeBase64String(clearText.getBytes(StandardCharsets.UTF_8)); } @Override public String decrypt(String encryptedText) { return new String(Base64.decodeBase64(encryptedText), StandardCharsets.UTF_8); } }
1,299
34.135135
82
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Cipher.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; interface Cipher { String encrypt(String clearText); String decrypt(String encryptedText); }
969
34.925926
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/ConfigurationUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.util.SettingFormatter; import static org.sonar.process.FileUtils2.deleteQuietly; public final class ConfigurationUtils { private static final Logger LOG = LoggerFactory.getLogger(ConfigurationUtils.class); private static final String ENV_VAR_INTERPOLATION_PREFIX = "${env:"; private static final String ENV_VAR_INTERPOLATION_POSTFIX = "}"; private ConfigurationUtils() { // Utility class } public static Properties interpolateVariables(Properties properties, Map<String, String> variables) { Properties result = new Properties(); Enumeration<Object> keys = properties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = (String) properties.get(key); if (value.contains(ENV_VAR_INTERPOLATION_PREFIX)) { String environmentVariableName = SettingFormatter.fromJavaPropertyToEnvVariable(key); LOG.warn("Referencing environment variables in configuration is deprecated and will be removed in a future version of SonarQube. " + "You should stop using '{}' in your configuration and use the '{}' environment variable instead.", value, environmentVariableName); } String interpolatedValue = StrSubstitutor.replace(value, variables, ENV_VAR_INTERPOLATION_PREFIX, ENV_VAR_INTERPOLATION_POSTFIX); result.setProperty(key, interpolatedValue); } return result; } static Props loadPropsFromCommandLineArgs(String[] args) { if (args.length != 1) { throw new IllegalArgumentException("Only a single command-line argument is accepted " + "(absolute path to configuration file)"); } File propertyFile = new File(args[0]); Properties properties = new Properties(); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(propertyFile), StandardCharsets.UTF_8); properties.load(reader); } catch (Exception e) { throw new IllegalStateException("Could not read properties from file: " + args[0], e); } finally { IOUtils.closeQuietly(reader); deleteQuietly(propertyFile); } return new Props(properties); } }
3,420
38.77907
141
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/FileUtils2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.IOException; import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * This utility class provides Java NIO based replacement for some methods of * {@link org.apache.commons.io.FileUtils Common IO FileUtils} class. */ public final class FileUtils2 { private static final Logger LOG = LoggerFactory.getLogger(FileUtils2.class); private static final String DIRECTORY_CAN_NOT_BE_NULL = "Directory can not be null"; private static final EnumSet<FileVisitOption> FOLLOW_LINKS = EnumSet.of(FileVisitOption.FOLLOW_LINKS); private FileUtils2() { // prevents instantiation } /** * Cleans a directory recursively. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful */ public static void cleanDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } cleanDirectoryImpl(directory.toPath()); } /** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param file file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise {@code false} */ public static boolean deleteQuietly(@Nullable File file) { if (file == null) { return false; } try { if (file.isDirectory()) { deleteDirectory(file); if (file.exists()) { LOG.warn("Unable to delete directory '{}'", file); } } else { Files.delete(file.toPath()); } return true; } catch (IOException | SecurityException ignored) { return false; } } /** * Deletes a directory recursively. Does not support symbolic link to directories. * * @param directory directory to delete * @throws IOException in case deletion is unsuccessful */ public static void deleteDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); if (!directory.exists()) { return; } Path path = directory.toPath(); if (Files.isSymbolicLink(path)) { throw new IOException(format("Directory '%s' is a symbolic link", directory)); } if (directory.isFile()) { throw new IOException(format("Directory '%s' is a file", directory)); } deleteDirectoryImpl(path); } /** * Size of file or directory, in bytes. In case of a directory, * the size is the sum of the sizes of all files recursively traversed. * * This implementation is recommended over commons-io * {@code FileUtils#sizeOf(File)} which suffers from slow usage of Java IO. * * @throws IOException if files can't be traversed or size attribute is not present * @see BasicFileAttributes#size() */ public static long sizeOf(Path path) throws IOException { SizeVisitor visitor = new SizeVisitor(); Files.walkFileTree(path, visitor); return visitor.size; } private static void cleanDirectoryImpl(Path path) throws IOException { if (!path.toFile().isDirectory()) { throw new IllegalArgumentException(format("'%s' is not a directory", path)); } Files.walkFileTree(path, FOLLOW_LINKS, CleanDirectoryFileVisitor.VISIT_MAX_DEPTH, new CleanDirectoryFileVisitor(path)); } private static void deleteDirectoryImpl(Path path) throws IOException { Files.walkFileTree(path, DeleteRecursivelyFileVisitor.INSTANCE); } /** * This visitor is intended to be used to visit direct children of directory <strong>or a symLink to a directory</strong>, * so, with a max depth of {@link #VISIT_MAX_DEPTH 1}. Each direct children will either be directly deleted (if file) * or recursively deleted (if directory). */ private static class CleanDirectoryFileVisitor extends SimpleFileVisitor<Path> { public static final int VISIT_MAX_DEPTH = 1; private final Path path; private final boolean symLink; public CleanDirectoryFileVisitor(Path path) { this.path = path; this.symLink = Files.isSymbolicLink(path); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toFile().isDirectory()) { deleteDirectoryImpl(file); } else if (!symLink || !file.equals(path)) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (!dir.equals(path)) { deleteDirectoryImpl(dir); } return FileVisitResult.CONTINUE; } } private static final class DeleteRecursivelyFileVisitor extends SimpleFileVisitor<Path> { public static final DeleteRecursivelyFileVisitor INSTANCE = new DeleteRecursivelyFileVisitor(); @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { Files.delete(file); } catch (AccessDeniedException e) { LOG.debug("Access delete to file '{}'. Ignoring and proceeding with recursive delete", file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { try { Files.delete(dir); } catch (AccessDeniedException e) { LOG.debug("Access denied to delete directory '{}'. Ignoring and proceeding with recursive delete", dir); } catch (DirectoryNotEmptyException e) { LOG.trace("Can not delete non empty directory '{}', presumably because it contained non accessible files/directories. " + "Ignoring and proceeding with recursive delete", dir, e); } return FileVisitResult.CONTINUE; } } private static final class SizeVisitor extends SimpleFileVisitor<Path> { private long size = 0; @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { // size is specified on regular files only // https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/BasicFileAttributes.html#size-- if (attrs.isRegularFile()) { size += attrs.size(); } return FileVisitResult.CONTINUE; } } }
7,897
33.792952
129
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Jmx.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.lang.management.ManagementFactory; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.StandardMBean; import org.slf4j.LoggerFactory; /** * JMX utilities to register MBeans to JMX server */ public class Jmx { private Jmx() { // only statics } /** * Register a MBean to JMX server */ public static void register(String name, Object instance) { try { Class<Object> mbeanInterface = guessMBeanInterface(instance); ManagementFactory.getPlatformMBeanServer().registerMBean(new StandardMBean(instance, mbeanInterface), new ObjectName(name)); } catch (MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException e) { throw new IllegalStateException("Can not register MBean [" + name + "]", e); } } /** * MBeans have multiple conventions, including: * 1. name of interface is suffixed by "MBean" * 2. name of implementation is the name of the interface without "MBean" * 3. implementation and interface must be in the same package * To avoid the last convention, we wrap the mbean within a StandardMBean. That * requires to find the related interface. */ private static Class<Object> guessMBeanInterface(Object instance) { Class<Object> mbeanInterface = null; Class<Object>[] interfaces = (Class<Object>[])instance.getClass().getInterfaces(); for (Class<Object> anInterface : interfaces) { if (anInterface.getName().endsWith("MBean")) { mbeanInterface = anInterface; break; } } if (mbeanInterface == null) { throw new IllegalArgumentException("Can not find the MBean interface of class " + instance.getClass().getName()); } return mbeanInterface; } /** * Unregister a MBean from JMX server. Errors are ignored and logged as warnings. */ public static void unregister(String name) { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(name)); } catch (Exception e) { LoggerFactory.getLogger(Jmx.class).warn("Can not unregister MBean [{}]", name, e); } } }
3,224
35.647727
137
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Lifecycle.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.sonar.process.Lifecycle.State.HARD_STOPPING; import static org.sonar.process.Lifecycle.State.INIT; import static org.sonar.process.Lifecycle.State.OPERATIONAL; import static org.sonar.process.Lifecycle.State.RESTARTING; import static org.sonar.process.Lifecycle.State.STARTED; import static org.sonar.process.Lifecycle.State.STARTING; import static org.sonar.process.Lifecycle.State.STOPPED; import static org.sonar.process.Lifecycle.State.STOPPING; public class Lifecycle { private static final Logger LOG = LoggerFactory.getLogger(Lifecycle.class); public enum State { INIT, STARTING, STARTED, OPERATIONAL, RESTARTING, STOPPING, HARD_STOPPING, STOPPED } private static final Map<State, Set<State>> TRANSITIONS = buildTransitions(); private AtomicReference<State> state = new AtomicReference<>(INIT); private static Map<State, Set<State>> buildTransitions() { Map<State, Set<State>> res = new EnumMap<>(State.class); res.put(INIT, toSet(STARTING)); res.put(STARTING, toSet(STARTED, STOPPING, HARD_STOPPING)); res.put(STARTED, toSet(OPERATIONAL, RESTARTING, STOPPING, HARD_STOPPING)); res.put(OPERATIONAL, toSet(RESTARTING, STOPPING, HARD_STOPPING)); res.put(RESTARTING, toSet(STARTING, HARD_STOPPING)); res.put(STOPPING, toSet(HARD_STOPPING, STOPPED)); res.put(HARD_STOPPING, toSet(STOPPED)); res.put(STOPPED, toSet()); return res; } private static Set<State> toSet(State... states) { if (states.length == 0) { return Collections.emptySet(); } if (states.length == 1) { return Collections.singleton(states[0]); } return EnumSet.copyOf(Arrays.asList(states)); } public boolean isCurrentState(State candidateState) { State currentState = this.state.get(); boolean res = currentState == candidateState; LOG.trace("isCurrentState({}): {} ({})", candidateState, res, currentState); return res; } public boolean tryToMoveTo(State to) { AtomicReference<State> lastFrom = new AtomicReference<>(); State newState = this.state.updateAndGet(from -> { lastFrom.set(from); if (TRANSITIONS.get(from).contains(to)) { return to; } return from; }); boolean updated = newState == to && lastFrom.get() != to; LOG.trace("tryToMoveTo from {} to {} => {}", lastFrom.get(), to, updated); return updated; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Lifecycle lifecycle = (Lifecycle) o; return state.get() == lifecycle.state.get(); } @Override public int hashCode() { return state.get().hashCode(); } }
3,907
32.982609
86
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/MessageException.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; /** * Unchecked exception that is displayed without stacktrace */ public class MessageException extends RuntimeException { public MessageException(String message) { super(message); } /** * Does not fill in the stack trace * * @see Throwable#fillInStackTrace() */ @Override public synchronized Throwable fillInStackTrace() { return this; } }
1,247
30.2
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/MinimumViableSystem.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.IOException; import java.util.Map; import org.apache.commons.lang.StringUtils; import static java.lang.String.format; import static org.sonar.process.FileUtils2.deleteQuietly; public class MinimumViableSystem { /** * Verify that temp directory is writable */ public MinimumViableSystem checkWritableTempDir() { checkWritableDir(System.getProperty("java.io.tmpdir")); return this; } // Visible for testing void checkWritableDir(String tempPath) { try { File tempFile = File.createTempFile("check", "tmp", new File(tempPath)); deleteQuietly(tempFile); } catch (IOException e) { throw new IllegalStateException(format("Temp directory is not writable: %s", tempPath), e); } } public MinimumViableSystem checkRequiredJavaOptions(Map<String, String> requiredJavaOptions) { for (Map.Entry<String, String> entry : requiredJavaOptions.entrySet()) { String value = System.getProperty(entry.getKey()); if (!StringUtils.equals(value, entry.getValue())) { throw new MessageException(format( "JVM option '%s' must be set to '%s'. Got '%s'", entry.getKey(), entry.getValue(), StringUtils.defaultString(value))); } } return this; } }
2,138
34.065574
128
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Monitored.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; /** * Base interface for the processes started by the bootstrap process. * It provides the information and operations required by {@link ProcessEntryPoint} * to handle the lifecycle of the process. */ public interface Monitored { /** * Starts process. No need to block until fully started and operational. */ void start(); /** * @return {@link Status#UP} if the process is done starting, {@link Status#OPERATIONAL} if the service is operation, * {@link Status#FAILED} if the process failed to start, {@link Status#DOWN} otherwise. */ Status getStatus(); enum Status { DOWN, UP, OPERATIONAL, FAILED } /** * Blocks until the process is stopped */ void awaitStop(); /** * Ask process to gracefully stop and wait until then. */ void stop(); /** * Ask process to quickly stop and wait until then. */ void hardStop(); }
1,764
28.915254
119
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/NetworkUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Optional; import java.util.OptionalInt; import java.util.function.Predicate; public interface NetworkUtils { int getNextLoopbackAvailablePort(); OptionalInt getNextAvailablePort(String hostOrAddress); /** * Identifying the localhost machine * It will try to retrieve the hostname * * @return "hostname" */ String getHostname(); /** * Converts a text representation of an IP address or host name to * a {@link InetAddress}. * If text value references an IPv4 or IPv6 address, then DNS is * not used. */ Optional<InetAddress> toInetAddress(String hostOrAddress); boolean isLocal(String hostOrAddress); boolean isLoopback(String hostOrAddress); /** * Returns the machine {@link InetAddress} that matches the specified * predicate. If multiple addresses match then a single one * is picked in a non deterministic way. */ Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate); /** * Returns a local {@link InetAddress} that is IPv4 and not * loopback. If multiple addresses match then a single one * is picked in a non deterministic way. */ default Optional<InetAddress> getLocalNonLoopbackIpv4Address() { return getLocalInetAddress(a -> !a.isLoopbackAddress() && a instanceof Inet4Address); } }
2,253
31.2
89
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/NetworkUtilsImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.annotations.VisibleForTesting; import com.google.common.net.InetAddresses; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; public class NetworkUtilsImpl implements NetworkUtils { private static final Set<Integer> PORTS_ALREADY_ALLOCATED = new HashSet<>(); private static final int PORT_MAX_TRIES = 50; private static final Logger LOG = LoggerFactory.getLogger(NetworkUtilsImpl.class); public static final NetworkUtils INSTANCE = new NetworkUtilsImpl(); NetworkUtilsImpl() { // prevent instantiation } @Override public int getNextLoopbackAvailablePort() { return getNextAvailablePort(InetAddress.getLoopbackAddress(), PortAllocator.INSTANCE); } @Override public OptionalInt getNextAvailablePort(String hostOrAddress) { return OptionalInt.of(toInetAddress(hostOrAddress) .map(t -> getNextAvailablePort(t, PortAllocator.INSTANCE)) .orElseThrow(() -> new IllegalArgumentException(format("Can not resolve address %s", hostOrAddress)))); } /** * Warning - the allocated ports are kept in memory and are never clean-up. Besides the memory consumption, * that means that ports already allocated are never freed. As a consequence * no more than ~64512 calls to this method are allowed. */ @VisibleForTesting static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) { for (int i = 0; i < PORT_MAX_TRIES; i++) { int port = portAllocator.getAvailable(address); if (isValidPort(port)) { PORTS_ALREADY_ALLOCATED.add(port); return port; } } throw new IllegalStateException("Fail to find an available port on " + address); } private static boolean isValidPort(int port) { return port > 1023 && !PORTS_ALREADY_ALLOCATED.contains(port); } static class PortAllocator { private static final PortAllocator INSTANCE = new PortAllocator(); int getAvailable(InetAddress address) { try (ServerSocket socket = new ServerSocket(0, 50, address)) { return socket.getLocalPort(); } catch (IOException e) { throw new IllegalStateException("Fail to find an available port on " + address, e); } } } @Override public String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOG.trace("Failed to get hostname", e); return "unresolved hostname"; } } @Override public Optional<InetAddress> toInetAddress(String hostOrAddress) { try { if (InetAddresses.isInetAddress(hostOrAddress)) { return Optional.of(InetAddresses.forString(hostOrAddress)); } return Optional.of(InetAddress.getByName(hostOrAddress)); } catch (UnknownHostException e) { LOG.trace("toInetAddress({}) failed", hostOrAddress, e); return Optional.empty(); } } @Override public boolean isLocal(String hostOrAddress) { try { Optional<InetAddress> inetAddress = toInetAddress(hostOrAddress); if (inetAddress.isPresent()) { return NetworkInterface.getByInetAddress(inetAddress.get()) != null; } return false; } catch (SocketException e) { LOG.trace("isLocalInetAddress({}) failed", hostOrAddress, e); return false; } } @Override public boolean isLoopback(String hostOrAddress) { return toInetAddress(hostOrAddress) .filter(InetAddress::isLoopbackAddress) .isPresent(); } @Override public Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate) { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .filter(a -> a.getHostAddress() != null) .filter(predicate) .findFirst(); } catch (SocketException e) { LOG.trace("getLocalInetAddress(Predicate<InetAddress>) failed", e); throw new IllegalStateException("Can not retrieve network interfaces", e); } } }
5,311
32.834395
109
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/PluginFileWriteRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.io.FilePermission; import java.nio.file.Path; import java.security.Permission; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class PluginFileWriteRule implements PluginPolicyRule { private static final Set<String> BLOCKED_FILE_ACTIONS = new HashSet<>(Arrays.asList( "write", "delete", "execute" )); private final FilePermission blockedFilePermission; private final FilePermission tmpFilePermission; public PluginFileWriteRule(Path home, Path tmp) { blockedFilePermission = new FilePermission(home.toAbsolutePath().toString() + File.separatorChar + "-", String.join(",", BLOCKED_FILE_ACTIONS)); tmpFilePermission = new FilePermission(tmp.toAbsolutePath().toString() + File.separatorChar + "-", String.join(",", BLOCKED_FILE_ACTIONS)); } @Override public boolean implies(Permission permission) { if (permission instanceof FilePermission requestPermission) { return !blockedFilePermission.implies(requestPermission) || tmpFilePermission.implies(requestPermission); } return true; } }
1,979
36.358491
148
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/PluginPolicyRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.security.Permission; public interface PluginPolicyRule { boolean implies(Permission permission); }
985
35.518519
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/PluginSecurityManager.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.security.Security; import java.util.List; public class PluginSecurityManager { private static final String CACHE_TTL_KEY = "networkaddress.cache.ttl"; private boolean alreadyRan = false; public void restrictPlugins(PluginPolicyRule... rules) { if (alreadyRan) { throw new IllegalStateException("can't run twice"); } alreadyRan = true; SecurityManager sm = new SecurityManager(); Policy.setPolicy(new PluginPolicy(List.of(rules))); System.setSecurityManager(sm); // SONAR-14870 By default, with a security manager installed, the DNS cache never times out. See InetAddressCachePolicy. if (Security.getProperty(CACHE_TTL_KEY) == null) { Security.setProperty(CACHE_TTL_KEY, "30"); } } static class PluginPolicy extends Policy { private final List<PluginPolicyRule> rules; PluginPolicy(List<PluginPolicyRule> rules) { this.rules = rules; } @Override public boolean implies(ProtectionDomain domain, Permission permission) { // classloader used to load plugins String clName = getDomainClassLoaderName(domain); if ("org.sonar.classloader.ClassRealm".equals(clName)) { return rules.stream().allMatch(p -> p.implies(permission)); } return true; } // workaround for SONAR-13559 / JDK-8014008 // borrowed as-is from https://github.com/elastic/elasticsearch/pull/14274 @Override public PermissionCollection getPermissions(CodeSource codesource) { // code should not rely on this method, or at least use it correctly: // https://bugs.openjdk.java.net/browse/JDK-8014008 // return them a new empty permissions object so jvisualvm etc work for (StackTraceElement element : Thread.currentThread().getStackTrace()) { if ("sun.rmi.server.LoaderHandler".equals(element.getClassName()) && "loadClass".equals(element.getMethodName())) { return new Permissions(); } } // return UNSUPPORTED_EMPTY_COLLECTION since it is safe. return super.getPermissions(codesource); } String getDomainClassLoaderName(ProtectionDomain domain) { ClassLoader classLoader = domain.getClassLoader(); return classLoader != null ? classLoader.getClass().getName() : null; } } }
3,379
36.977528
124
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/ProcessEntryPoint.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.util.function.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.sonar.process.Lifecycle.State.STOPPED; public class ProcessEntryPoint { public static final String PROPERTY_PROCESS_KEY = "process.key"; public static final String PROPERTY_PROCESS_INDEX = "process.index"; public static final String PROPERTY_GRACEFUL_STOP_TIMEOUT_MS = "process.gracefulStopTimeout"; public static final String PROPERTY_SHARED_PATH = "process.sharedDir"; // 1 second private static final long HARD_STOP_TIMEOUT_MS = 1_000L; private final Props props; private final ProcessId processId; private final Lifecycle lifecycle = new Lifecycle(); private final ProcessCommands commands; private final SystemExit exit; private final StopWatcher stopWatcher; private final StopWatcher hardStopWatcher; // new Runnable() is important to avoid conflict of call to ProcessEntryPoint#stop() with Thread#stop() private final Runtime runtime; private Monitored monitored; private volatile StopperThread stopperThread; public ProcessEntryPoint(Props props, SystemExit exit, ProcessCommands commands, Runtime runtime) { this.props = props; this.processId = ProcessId.fromKey(props.nonNullValue(PROPERTY_PROCESS_KEY)); this.exit = exit; this.commands = commands; this.stopWatcher = createStopWatcher(commands, this); this.hardStopWatcher = createHardStopWatcher(commands, this); this.runtime = runtime; } public ProcessCommands getCommands() { return commands; } public Props getProps() { return props; } /** * Launch process and waits until it's down */ public void launch(Monitored mp) { if (!lifecycle.tryToMoveTo(Lifecycle.State.STARTING)) { throw new IllegalStateException("Already started"); } monitored = mp; Logger logger = LoggerFactory.getLogger(getClass()); try { launch(logger); } catch (Exception e) { logger.warn("Fail to start {}", processId.getHumanReadableName(), e); hardStop(); } } private void launch(Logger logger) throws InterruptedException { logger.info("Starting {}", processId.getHumanReadableName()); runtime.addShutdownHook(new Thread(() -> { exit.setInShutdownHook(); stop(); })); stopWatcher.start(); hardStopWatcher.start(); monitored.start(); Monitored.Status status = waitForStatus(s -> s != Monitored.Status.DOWN); if (status == Monitored.Status.UP || status == Monitored.Status.OPERATIONAL) { // notify monitor that process is ready commands.setUp(); if (lifecycle.tryToMoveTo(Lifecycle.State.STARTED)) { Monitored.Status newStatus = waitForStatus(s -> s == Monitored.Status.OPERATIONAL || s == Monitored.Status.FAILED); if (newStatus == Monitored.Status.OPERATIONAL && lifecycle.tryToMoveTo(Lifecycle.State.OPERATIONAL)) { commands.setOperational(); } monitored.awaitStop(); } } else { logger.trace("Fail to start. Hard stopping..."); hardStop(); } } private Monitored.Status waitForStatus(Predicate<Monitored.Status> statusPredicate) throws InterruptedException { Monitored.Status status = monitored.getStatus(); while (!statusPredicate.test(status)) { Thread.sleep(20); status = monitored.getStatus(); } return status; } void stop() { stopAsync(); monitored.awaitStop(); } /** * Blocks until stopped in a timely fashion (see {@link HardStopperThread}) */ void hardStop() { hardStopAsync(); monitored.awaitStop(); } private void stopAsync() { if (lifecycle.tryToMoveTo(Lifecycle.State.STOPPING)) { LoggerFactory.getLogger(ProcessEntryPoint.class).info("Gracefully stopping process"); stopWatcher.stopWatching(); long terminationTimeoutMs = Long.parseLong(props.nonNullValue(PROPERTY_GRACEFUL_STOP_TIMEOUT_MS)); stopperThread = new StopperThread(monitored, this::terminate, terminationTimeoutMs); stopperThread.start(); } } private void hardStopAsync() { if (lifecycle.tryToMoveTo(Lifecycle.State.HARD_STOPPING)) { LoggerFactory.getLogger(ProcessEntryPoint.class).info("Hard stopping process"); if (stopperThread != null) { stopperThread.stopIt(); } hardStopWatcher.stopWatching(); stopWatcher.stopWatching(); new HardStopperThread(monitored, this::terminate).start(); } } private void terminate() { lifecycle.tryToMoveTo(STOPPED); hardStopWatcher.stopWatching(); stopWatcher.stopWatching(); commands.endWatch(); } public static ProcessEntryPoint createForArguments(String[] args) { Props props = ConfigurationUtils.loadPropsFromCommandLineArgs(args); File sharedDir = getSharedDir(props); int processNumber = getProcessNumber(props); ProcessCommands commands = DefaultProcessCommands.main(sharedDir, processNumber); return new ProcessEntryPoint(props, new SystemExit(), commands, Runtime.getRuntime()); } private static int getProcessNumber(Props props) { return Integer.parseInt(props.nonNullValue(PROPERTY_PROCESS_INDEX)); } private static File getSharedDir(Props props) { return props.nonNullValueAsFile(PROPERTY_SHARED_PATH); } /** * This watchdog is looking for hard stop to be requested via {@link ProcessCommands#askedForHardStop()}. */ private static StopWatcher createHardStopWatcher(ProcessCommands commands, ProcessEntryPoint processEntryPoint) { return new StopWatcher("HardStop Watcher", processEntryPoint::hardStopAsync, commands::askedForHardStop); } /** * This watchdog is looking for graceful stop to be requested via {@link ProcessCommands#askedForStop()} ()}. */ private static StopWatcher createStopWatcher(ProcessCommands commands, ProcessEntryPoint processEntryPoint) { return new StopWatcher("Stop Watcher", processEntryPoint::stopAsync, commands::askedForStop); } /** * Stops process in a graceful fashion */ private static class StopperThread extends AbstractStopperThread { private StopperThread(Monitored monitored, Runnable postAction, long terminationTimeoutMs) { super("Stopper", () -> { monitored.stop(); postAction.run(); }, terminationTimeoutMs); } } /** * Stops process in a short time fashion */ private static class HardStopperThread extends AbstractStopperThread { private HardStopperThread(Monitored monitored, Runnable postAction) { super( "HardStopper", () -> { monitored.hardStop(); postAction.run(); }, HARD_STOP_TIMEOUT_MS); } } }
7,709
33.266667
123
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/ProcessId.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import static java.lang.String.format; public enum ProcessId { APP("app", 0, "sonar", "SonarQube"), ELASTICSEARCH("es", 1, "es", "ElasticSearch"), WEB_SERVER("web", 2, "web", "Web Server"), COMPUTE_ENGINE("ce", 3, "ce", "Compute Engine"); private final String key; private final int ipcIndex; private final String logFilenamePrefix; private final String humanReadableName; ProcessId(String key, int ipcIndex, String logFilenamePrefix, String humanReadableName) { this.key = key; this.ipcIndex = ipcIndex; this.logFilenamePrefix = logFilenamePrefix; this.humanReadableName = humanReadableName; } public String getKey() { return key; } /** * Index used for inter-process communication */ public int getIpcIndex() { return ipcIndex; } /** * Prefix of log file, for example "web" for file "web.log" */ public String getLogFilenamePrefix() { return logFilenamePrefix; } public String getHumanReadableName() { return humanReadableName; } public static ProcessId fromKey(String key) { for (ProcessId processId : values()) { if (processId.getKey().equals(key)) { return processId; } } throw new IllegalArgumentException(format("Process [%s] does not exist", key)); } }
2,162
27.84
91
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/ProcessProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.collect.ImmutableSet; import java.net.InetAddress; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.core.extension.CoreExtension; import org.sonar.core.extension.ServiceLoaderWrapper; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.ES_PORT; import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; /** * Constants shared by search, web server and app processes. * They are almost all the properties defined in conf/sonar.properties. */ public class ProcessProperties { private static final String DEFAULT_FALSE = Boolean.FALSE.toString(); private final ServiceLoaderWrapper serviceLoaderWrapper; public enum Property { JDBC_URL("sonar.jdbc.url"), JDBC_USERNAME("sonar.jdbc.username", ""), JDBC_PASSWORD("sonar.jdbc.password", ""), JDBC_DRIVER_PATH("sonar.jdbc.driverPath"), JDBC_MAX_ACTIVE("sonar.jdbc.maxActive", "60"), JDBC_MIN_IDLE("sonar.jdbc.minIdle", "10"), JDBC_MAX_WAIT("sonar.jdbc.maxWait", "8000"), JDBC_MAX_IDLE_TIMEOUT("sonar.jdbc.idleTimeout", "600000"), JDBC_MAX_KEEP_ALIVE_TIME("sonar.jdbc.keepaliveTime", "180000"), JDBC_MAX_LIFETIME("sonar.jdbc.maxLifetime", "1800000"), JDBC_VALIDATION_TIMEOUT("sonar.jdbc.validationTimeout", "5000"), JDBC_EMBEDDED_PORT("sonar.embeddedDatabase.port"), PATH_DATA("sonar.path.data", "data"), PATH_HOME("sonar.path.home"), PATH_LOGS("sonar.path.logs", "logs"), PATH_TEMP("sonar.path.temp", "temp"), PATH_WEB("sonar.path.web", "web"), LOG_LEVEL("sonar.log.level"), LOG_LEVEL_APP("sonar.log.level.app"), LOG_LEVEL_WEB("sonar.log.level.web"), LOG_LEVEL_CE("sonar.log.level.ce"), LOG_LEVEL_ES("sonar.log.level.es"), LOG_ROLLING_POLICY("sonar.log.rollingPolicy"), LOG_MAX_FILES("sonar.log.maxFiles"), LOG_CONSOLE("sonar.log.console"), LOG_JSON_OUTPUT("sonar.log.jsonOutput", DEFAULT_FALSE), SEARCH_HOST("sonar.search.host"), SEARCH_PORT("sonar.search.port"), ES_PORT("sonar.es.port"), SEARCH_JAVA_OPTS("sonar.search.javaOpts", "-Xmx512m -Xms512m -XX:MaxDirectMemorySize=256m -XX:+HeapDumpOnOutOfMemoryError"), SEARCH_JAVA_ADDITIONAL_OPTS("sonar.search.javaAdditionalOpts", ""), SEARCH_REPLICAS("sonar.search.replicas"), SEARCH_INITIAL_STATE_TIMEOUT("sonar.search.initialStateTimeout"), SONAR_ES_BOOTSTRAP_CHECKS_DISABLE("sonar.es.bootstrap.checks.disable"), WEB_HOST("sonar.web.host"), WEB_JAVA_OPTS("sonar.web.javaOpts", "-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError"), WEB_JAVA_ADDITIONAL_OPTS("sonar.web.javaAdditionalOpts", ""), WEB_CONTEXT("sonar.web.context"), WEB_PORT("sonar.web.port"), WEB_GRACEFUL_STOP_TIMEOUT("sonar.web.gracefulStopTimeOutInMs", "" + 4 * 60 * 1_000L), WEB_HTTP_MIN_THREADS("sonar.web.http.minThreads"), WEB_HTTP_MAX_THREADS("sonar.web.http.maxThreads"), WEB_HTTP_ACCEPT_COUNT("sonar.web.http.acceptCount"), WEB_HTTP_KEEP_ALIVE_TIMEOUT("sonar.web.http.keepAliveTimeout"), WEB_SESSION_TIMEOUT_IN_MIN("sonar.web.sessionTimeoutInMinutes"), WEB_SYSTEM_PASS_CODE("sonar.web.systemPasscode"), WEB_ACCESSLOGS_ENABLE("sonar.web.accessLogs.enable"), WEB_ACCESSLOGS_PATTERN("sonar.web.accessLogs.pattern"), CE_JAVA_OPTS("sonar.ce.javaOpts", "-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError"), CE_JAVA_ADDITIONAL_OPTS("sonar.ce.javaAdditionalOpts", ""), CE_GRACEFUL_STOP_TIMEOUT("sonar.ce.gracefulStopTimeOutInMs", "" + 6 * 60 * 60 * 1_000L), HTTP_PROXY_HOST("http.proxyHost"), HTTPS_PROXY_HOST("https.proxyHost"), HTTP_PROXY_PORT("http.proxyPort"), HTTPS_PROXY_PORT("https.proxyPort"), HTTP_PROXY_USER("http.proxyUser"), HTTP_PROXY_PASSWORD("http.proxyPassword"), HTTP_NON_PROXY_HOSTS("http.nonProxyHosts", "localhost|127.*|[::1]"), HTTP_AUTH_NTLM_DOMAIN("http.auth.ntlm.domain"), SOCKS_PROXY_HOST("socksProxyHost"), SOCKS_PROXY_PORT("socksProxyPort"), CLUSTER_ENABLED("sonar.cluster.enabled", DEFAULT_FALSE), CLUSTER_KUBERNETES("sonar.cluster.kubernetes", DEFAULT_FALSE), CLUSTER_NODE_TYPE("sonar.cluster.node.type"), CLUSTER_SEARCH_HOSTS("sonar.cluster.search.hosts"), CLUSTER_HZ_HOSTS("sonar.cluster.hosts"), CLUSTER_NODE_HZ_PORT("sonar.cluster.node.port", "9003"), CLUSTER_NODE_HOST("sonar.cluster.node.host"), CLUSTER_NODE_NAME("sonar.cluster.node.name", "sonarqube-" + UUID.randomUUID().toString()), CLUSTER_NAME("sonar.cluster.name", "sonarqube"), CLUSTER_WEB_STARTUP_LEADER("sonar.cluster.web.startupLeader"), CLUSTER_SEARCH_PASSWORD("sonar.cluster.search.password"), CLUSTER_ES_KEYSTORE("sonar.cluster.es.ssl.keystore"), CLUSTER_ES_TRUSTSTORE("sonar.cluster.es.ssl.truststore"), CLUSTER_ES_KEYSTORE_PASSWORD("sonar.cluster.es.ssl.keystorePassword"), CLUSTER_ES_TRUSTSTORE_PASSWORD("sonar.cluster.es.ssl.truststorePassword"), CLUSTER_ES_HTTP_KEYSTORE("sonar.cluster.es.http.ssl.keystore"), CLUSTER_ES_HTTP_KEYSTORE_PASSWORD("sonar.cluster.es.http.ssl.keystorePassword"), // search node only settings CLUSTER_ES_HOSTS("sonar.cluster.es.hosts"), CLUSTER_ES_DISCOVERY_SEED_HOSTS("sonar.cluster.es.discovery.seed.hosts"), CLUSTER_NODE_SEARCH_HOST("sonar.cluster.node.search.host"), CLUSTER_NODE_SEARCH_PORT("sonar.cluster.node.search.port"), CLUSTER_NODE_ES_HOST("sonar.cluster.node.es.host"), CLUSTER_NODE_ES_PORT("sonar.cluster.node.es.port"), AUTH_JWT_SECRET("sonar.auth.jwtBase64Hs256Secret"), SONAR_WEB_SSO_ENABLE("sonar.web.sso.enable", DEFAULT_FALSE), SONAR_WEB_SSO_LOGIN_HEADER("sonar.web.sso.loginHeader", "X-Forwarded-Login"), SONAR_WEB_SSO_NAME_HEADER("sonar.web.sso.nameHeader", "X-Forwarded-Name"), SONAR_WEB_SSO_EMAIL_HEADER("sonar.web.sso.emailHeader", "X-Forwarded-Email"), SONAR_WEB_SSO_GROUPS_HEADER("sonar.web.sso.groupsHeader", "X-Forwarded-Groups"), SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES("sonar.web.sso.refreshIntervalInMinutes", "5"), SONAR_SECURITY_REALM("sonar.security.realm"), SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE("sonar.authenticator.ignoreStartupFailure", DEFAULT_FALSE), LDAP_SERVERS("ldap.servers"), LDAP_URL("ldap.url"), LDAP_BIND_DN("ldap.bindDn"), LDAP_BIND_PASSWORD("ldap.bindPassword"), LDAP_AUTHENTICATION("ldap.authentication"), LDAP_REALM("ldap.realm"), LDAP_CONTEXT_FACTORY_CLASS("ldap.contextFactoryClass"), LDAP_START_TLS("ldap.StartTLS"), LDAP_FOLLOW_REFERRALS("ldap.followReferrals"), LDAP_USER_BASE_DN("ldap.user.baseDn"), LDAP_USER_REQUEST("ldap.user.request"), LDAP_USER_REAL_NAME_ATTRIBUTE("ldap.user.realNameAttribute"), LDAP_USER_EMAIL_ATTRIBUTE("ldap.user.emailAttribute"), LDAP_GROUP_BASE_DN("ldap.group.baseDn"), LDAP_GROUP_REQUEST("ldap.group.request"), LDAP_GROUP_ID_ATTRIBUTE("ldap.group.idAttribute"), SONAR_TELEMETRY_ENABLE("sonar.telemetry.enable", "true"), SONAR_TELEMETRY_URL("sonar.telemetry.url", "https://telemetry.sonarsource.com/sonarqube"), SONAR_TELEMETRY_FREQUENCY_IN_SECONDS("sonar.telemetry.frequencyInSeconds", "10800"), SONAR_TELEMETRY_COMPRESSION("sonar.telemetry.compression", "true"), SONAR_UPDATECENTER_ACTIVATE("sonar.updatecenter.activate", "true"), /** * Used by Orchestrator to ask for shutdown of monitor process */ ENABLE_STOP_COMMAND("sonar.enableStopCommand"), AUTO_DATABASE_UPGRADE("sonar.autoDatabaseUpgrade", DEFAULT_FALSE); /** * Properties that are defined for each LDAP server from the `ldap.servers` property */ public static final Set<String> MULTI_SERVER_LDAP_SETTINGS = ImmutableSet.of( "ldap.*.url", "ldap.*.bindDn", "ldap.*.bindPassword", "ldap.*.authentication", "ldap.*.realm", "ldap.*.contextFactoryClass", "ldap.*.StartTLS", "ldap.*.followReferrals", "ldap.*.user.baseDn", "ldap.*.user.request", "ldap.*.user.realNameAttribute", "ldap.*.user.emailAttribute", "ldap.*.group.baseDn", "ldap.*.group.request", "ldap.*.group.idAttribute"); private final String key; private final String defaultValue; Property(String key, @Nullable String defaultValue) { this.key = key; this.defaultValue = defaultValue; } Property(String key) { this(key, null); } public String getKey() { return key; } public String getDefaultValue() { Objects.requireNonNull(defaultValue, "There's no default value on this property"); return defaultValue; } public boolean hasDefaultValue() { return defaultValue != null; } } public ProcessProperties(ServiceLoaderWrapper serviceLoaderWrapper) { this.serviceLoaderWrapper = serviceLoaderWrapper; } public void completeDefaults(Props props) { // init string properties for (Map.Entry<Object, Object> entry : defaults().entrySet()) { props.setDefault(entry.getKey().toString(), entry.getValue().toString()); } boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false); if (!clusterEnabled) { props.setDefault(SEARCH_HOST.getKey(), InetAddress.getLoopbackAddress().getHostAddress()); props.setDefault(SEARCH_PORT.getKey(), "9001"); fixPortIfZero(props, Property.SEARCH_HOST.getKey(), SEARCH_PORT.getKey()); fixEsTransportPortIfNull(props); } } private Properties defaults() { Properties defaults = new Properties(); defaults.putAll(Arrays.stream(Property.values()) .filter(Property::hasDefaultValue) .collect(Collectors.toMap(Property::getKey, Property::getDefaultValue))); defaults.putAll(loadDefaultsFromExtensions()); return defaults; } private Map<String, String> loadDefaultsFromExtensions() { Map<String, String> propertyDefaults = new HashMap<>(); Set<CoreExtension> extensions = serviceLoaderWrapper.load(); for (CoreExtension ext : extensions) { for (Map.Entry<String, String> property : ext.getExtensionProperties().entrySet()) { if (propertyDefaults.put(property.getKey(), property.getValue()) != null) { throw new IllegalStateException(format("Configuration error: property definition named '%s' found in multiple extensions.", property.getKey())); } } } return propertyDefaults; } private static void fixPortIfZero(Props props, String addressPropertyKey, String portPropertyKey) { String port = props.value(portPropertyKey); if ("0".equals(port)) { String address = props.nonNullValue(addressPropertyKey); int allocatedPort = NetworkUtilsImpl.INSTANCE.getNextAvailablePort(address) .orElseThrow(() -> new IllegalStateException("Cannot resolve address [" + address + "] set by property [" + addressPropertyKey + "]")); props.set(portPropertyKey, String.valueOf(allocatedPort)); } } private static void fixEsTransportPortIfNull(Props props) { String port = props.value(ES_PORT.getKey()); if (port == null) { int allocatedPort = NetworkUtilsImpl.INSTANCE.getNextAvailablePort(InetAddress.getLoopbackAddress().getHostAddress()) .orElseThrow(() -> new IllegalStateException("Cannot resolve address for Elasticsearch TCP transport port")); props.set(ES_PORT.getKey(), String.valueOf(allocatedPort)); } } public static long parseTimeoutMs(Property property, String value) { long l = Long.parseLong(value); checkState(l >= 1, "value of %s must be >= 1", property); return l; } }
12,875
41.49505
143
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Props.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.File; import java.util.Properties; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.internal.Encryption; import static org.sonar.api.CoreProperties.ENCRYPTION_SECRET_KEY_PATH; public class Props { private final Properties properties; private final Encryption encryption; public Props(Properties props) { this.properties = new Properties(); props.forEach((k, v) -> this.properties.put(k.toString().trim(), v == null ? null : v.toString().trim())); this.encryption = new Encryption(props.getProperty(ENCRYPTION_SECRET_KEY_PATH)); } public boolean contains(String key) { return properties.containsKey(key); } @CheckForNull public String value(String key) { String value = properties.getProperty(key); if (value != null && encryption.isEncrypted(value)) { value = encryption.decrypt(value); } return value; } public String nonNullValue(String key) { String value = value(key); if (value == null) { throw new IllegalArgumentException("Missing property: " + key); } return value; } @CheckForNull public String value(String key, @Nullable String defaultValue) { String s = value(key); return s == null ? defaultValue : s; } public boolean valueAsBoolean(String key) { String s = value(key); return s != null && Boolean.parseBoolean(s); } public boolean valueAsBoolean(String key, boolean defaultValue) { String s = value(key); return s != null ? Boolean.parseBoolean(s) : defaultValue; } public File nonNullValueAsFile(String key) { String s = value(key); if (s == null) { throw new IllegalArgumentException("Property " + key + " is not set"); } return new File(s); } @CheckForNull public Integer valueAsInt(String key) { String s = value(key); if (s != null && !"".equals(s)) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new IllegalStateException("Value of property " + key + " is not an integer: " + s, e); } } return null; } public int valueAsInt(String key, int defaultValue) { Integer i = valueAsInt(key); return i == null ? defaultValue : i; } public Properties rawProperties() { return properties; } public Props set(String key, @Nullable String value) { if (value != null) { properties.setProperty(key, value); } return this; } public void setDefault(String key, String value) { String s = properties.getProperty(key); if (StringUtils.isBlank(s)) { properties.setProperty(key, value); } } }
3,590
27.728
110
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/StopWatcher.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import com.google.common.annotations.VisibleForTesting; import java.util.function.BooleanSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StopWatcher extends Thread { private static final Logger LOG = LoggerFactory.getLogger(StopWatcher.class); private final Runnable stopCommand; private final BooleanSupplier shouldStopTest; private final long delayMs; private volatile boolean watching = true; public StopWatcher(String threadName, Runnable stopCommand, BooleanSupplier shouldStopTest) { this(threadName, stopCommand, shouldStopTest, 500L); } @VisibleForTesting StopWatcher(String threadName, Runnable stopCommand, BooleanSupplier shouldStopTest, long delayMs) { super(threadName); this.stopCommand = stopCommand; this.shouldStopTest = shouldStopTest; this.delayMs = delayMs; } @Override public void run() { while (watching) { if (shouldStopTest.getAsBoolean()) { LOG.trace("{} triggering stop command", this.getName()); stopCommand.run(); watching = false; } else { try { Thread.sleep(delayMs); } catch (InterruptedException ignored) { watching = false; // restore interrupted flag Thread.currentThread().interrupt(); } } } } public void stopWatching() { super.interrupt(); watching = false; } }
2,279
31.571429
102
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/Stoppable.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; public interface Stoppable { void stopAsync(); void hardStopAsync(); }
949
31.758621
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/System2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.util.Map; import org.apache.commons.lang.SystemUtils; /** * An interface allowing to wrap around static call to {@link System} class. */ public interface System2 { System2 INSTANCE = new System2() { @Override public Map<String, String> getenv() { return System.getenv(); } @Override public String getenv(String name) { return System.getenv(name); } @Override public boolean isOsWindows() { return SystemUtils.IS_OS_WINDOWS; } }; /** * Proxy to {@link System#getenv()} */ Map<String, String> getenv(); /** * Proxy to {@link System#getenv(String)}. */ String getenv(String name); /** * True if this is MS Windows. */ boolean isOsWindows(); }
1,619
25.557377
76
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/SystemExit.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; /** * Calls {@link System#exit(int)} except from shutdown hooks, to prevent * deadlocks. See http://stackoverflow.com/a/19552359/229031 */ public class SystemExit { private volatile boolean inShutdownHook = false; public void exit(int code) { if (!inShutdownHook) { doExit(code); } } public boolean isInShutdownHook() { return inShutdownHook; } /** * Declarative approach. I don't know how to get this lifecycle state from Java API. */ public void setInShutdownHook() { inShutdownHook = true; } void doExit(int code) { System.exit(code); } }
1,473
27.901961
86
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.process; import javax.annotation.ParametersAreNonnullByDefault;
957
38.916667
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/NodeType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster; import static java.util.Arrays.stream; public enum NodeType { APPLICATION("application"), SEARCH("search"); private final String value; NodeType(String value) { this.value = value; } public String getValue() { return value; } public static NodeType parse(String nodeType) { return stream(values()) .filter(t -> nodeType.equals(t.value)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Invalid value: " + nodeType)); } public static boolean isValid(String nodeType) { return stream(values()) .anyMatch(t -> nodeType.equals(t.value)); } }
1,496
29.55102
85
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.process.cluster; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/HealthStateRefresher.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.spi.exception.RetryableHazelcastException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Startable; public class HealthStateRefresher implements Startable { private static final Logger LOG = LoggerFactory.getLogger(HealthStateRefresher.class); private static final int INITIAL_DELAY = 1; private static final int DELAY = 10; private final HealthStateRefresherExecutorService executorService; private final NodeHealthProvider nodeHealthProvider; private final SharedHealthState sharedHealthState; public HealthStateRefresher(HealthStateRefresherExecutorService executorService, NodeHealthProvider nodeHealthProvider, SharedHealthState sharedHealthState) { this.executorService = executorService; this.nodeHealthProvider = nodeHealthProvider; this.sharedHealthState = sharedHealthState; } public void start() { executorService.scheduleWithFixedDelay(this::refresh, INITIAL_DELAY, DELAY, TimeUnit.SECONDS); } private void refresh() { try { NodeHealth nodeHealth = nodeHealthProvider.get(); sharedHealthState.writeMine(nodeHealth); } catch (HazelcastInstanceNotActiveException | RetryableHazelcastException e) { LOG.debug("Hazelcast is no more active", e); } catch (Throwable t) { LOG.error("An error occurred while attempting to refresh HealthState of the current node in the shared state:", t); } } public void stop() { sharedHealthState.clearMine(); } }
2,491
37.9375
121
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/HealthStateRefresherExecutorService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.util.concurrent.ScheduledExecutorService; public interface HealthStateRefresherExecutorService extends ScheduledExecutorService { }
1,031
38.692308
87
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/NodeDetails.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.google.common.base.Preconditions; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Objects; import static java.util.Objects.requireNonNull; /** * <p>{@link Externalizable} because this class is written to and from Hazelcast.</p> */ public class NodeDetails implements Externalizable { private Type type; private String name; private String host; private int port; private long startedAt; /** * Required for Serialization */ public NodeDetails() { } private NodeDetails(Builder builder) { this.type = builder.type; this.name = builder.name; this.host = builder.host; this.port = builder.port; this.startedAt = builder.startedAt; } public static Builder newNodeDetailsBuilder() { return new Builder(); } public Type getType() { return type; } public String getName() { return name; } public String getHost() { return host; } public int getPort() { return port; } public long getStartedAt() { return startedAt; } @Override public String toString() { return "NodeDetails{" + "type=" + type + ", name='" + name + '\'' + ", host='" + host + '\'' + ", port=" + port + ", startedAt=" + startedAt + '}'; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(type.ordinal()); out.writeUTF(name); out.writeUTF(host); out.writeInt(port); out.writeLong(startedAt); } @Override public void readExternal(ObjectInput in) throws IOException { this.type = Type.values()[in.readInt()]; this.name = in.readUTF(); this.host = in.readUTF(); this.port = in.readInt(); this.startedAt = in.readLong(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NodeDetails that = (NodeDetails) o; return port == that.port && startedAt == that.startedAt && type == that.type && name.equals(that.name) && host.equals(that.host); } @Override public int hashCode() { return Objects.hash(type, name, host, port, startedAt); } public static class Builder { private Type type; private String name; private String host; private int port; private long startedAt; private Builder() { // use static factory method } public Builder setType(Type type) { this.type = checkType(type); return this; } public Builder setName(String name) { this.name = checkString(name, "name"); return this; } public Builder setHost(String host) { this.host = checkString(host, "host"); return this; } public Builder setPort(int port) { checkPort(port); this.port = port; return this; } public Builder setStartedAt(long startedAt) { checkStartedAt(startedAt); this.startedAt = startedAt; return this; } public NodeDetails build() { checkType(type); checkString(name, "name"); checkString(host, "host"); checkPort(port); checkStartedAt(startedAt); return new NodeDetails(this); } private static Type checkType(Type type) { return requireNonNull(type, "type can't be null"); } private static String checkString(String name, String label) { Preconditions.checkNotNull(name, "%s can't be null", label); String value = name.trim(); Preconditions.checkArgument(!value.isEmpty(), "%s can't be empty", label); return value; } private static void checkPort(int port) { Preconditions.checkArgument(port > 0, "port must be > 0"); } private static void checkStartedAt(long startedAt) { Preconditions.checkArgument(startedAt > 0, "startedAt must be > 0"); } } public enum Type { APPLICATION, SEARCH } }
4,905
23.53
85
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/NodeHealth.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashSet; import java.util.Objects; import java.util.Set; import static java.util.Objects.requireNonNull; /** * <p>{@link Externalizable} because this class is written to and from Hazelcast.</p> */ public class NodeHealth implements Externalizable { private Status status; private Set<String> causes; private NodeDetails details; /** * Required for Serialization */ public NodeHealth() { } private NodeHealth(Builder builder) { this.status = builder.status; this.causes = ImmutableSet.copyOf(builder.causes); this.details = builder.details; } public static Builder newNodeHealthBuilder() { return new Builder(); } public Status getStatus() { return status; } public Set<String> getCauses() { return causes; } public NodeDetails getDetails() { return details; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(status.ordinal()); out.writeInt(causes.size()); for (String cause : causes) { out.writeUTF(cause); } out.writeObject(details); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.status = Status.values()[in.readInt()]; int size = in.readInt(); if (size > 0) { Set<String> readCauses = new HashSet<>(size); for (int i = 0; i < size; i++) { readCauses.add(in.readUTF()); } this.causes = ImmutableSet.copyOf(readCauses); } else { this.causes = ImmutableSet.of(); } this.details = (NodeDetails) in.readObject(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NodeHealth that = (NodeHealth) o; return status == that.status && causes.equals(that.causes) && details.equals(that.details); } @Override public int hashCode() { return Objects.hash(status, causes, details); } @Override public String toString() { return "NodeHealth{" + "status=" + status + ", causes=" + causes + ", details=" + details + '}'; } public static class Builder { private static final String STATUS_CANT_BE_NULL = "status can't be null"; private static final String DETAILS_CANT_BE_NULL = "details can't be null"; private Status status; private Set<String> causes = new HashSet<>(0); private NodeDetails details; private Builder() { // use static factory method } public Builder setStatus(Status status) { this.status = requireNonNull(status, STATUS_CANT_BE_NULL); return this; } public Builder clearCauses() { this.causes.clear(); return this; } public Builder addCause(String cause) { requireNonNull(cause, "cause can't be null"); String trimmed = cause.trim(); Preconditions.checkArgument(!trimmed.isEmpty(), "cause can't be empty"); causes.add(cause); return this; } public Builder setDetails(NodeDetails details) { requireNonNull(details, DETAILS_CANT_BE_NULL); this.details = details; return this; } public NodeHealth build() { requireNonNull(status, STATUS_CANT_BE_NULL); requireNonNull(details, DETAILS_CANT_BE_NULL); return new NodeHealth(this); } } public enum Status { GREEN, YELLOW, RED } }
4,538
25.54386
87
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/NodeHealthProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; public interface NodeHealthProvider { /** * Returns the {@link NodeHealth} for the current SonarQube node. * * <p>Implementation must support being called very frequently and from concurrent threads</p> */ NodeHealth get(); }
1,128
36.633333
96
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/SharedHealthState.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.util.Set; public interface SharedHealthState { /** * Writes the {@link NodeHealth} of the current node to the shared health state. */ void writeMine(NodeHealth nodeHealth); /** * Clears the {@link NodeHealth} of the current node in the shared health state (if any). */ void clearMine(); /** * Reads the {@link NodeHealth} of all nodes which shared to the shared health state. */ Set<NodeHealth> readAll(); }
1,339
32.5
91
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/SharedHealthStateImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.Predicate; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.cluster.hz.HazelcastObjects; import static java.util.Objects.requireNonNull; import org.springframework.beans.factory.annotation.Autowired; public class SharedHealthStateImpl implements SharedHealthState { private static final Logger LOG = LoggerFactory.getLogger(SharedHealthStateImpl.class); private static final int TIMEOUT_30_SECONDS = 30 * 1000; private final HazelcastMember hzMember; @Autowired(required = false) public SharedHealthStateImpl(HazelcastMember hzMember) { this.hzMember = hzMember; } @Autowired(required = false) public SharedHealthStateImpl() { this(null); } @Override public void writeMine(NodeHealth nodeHealth) { requireNonNull(nodeHealth, "nodeHealth can't be null"); Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap(); if (LOG.isTraceEnabled()) { LOG.trace("Reading {} and adding {}", new HashMap<>(sqHealthState), nodeHealth); } sqHealthState.put(hzMember.getUuid(), new TimestampedNodeHealth(nodeHealth, hzMember.getClusterTime())); } @Override public void clearMine() { Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap(); UUID clientUUID = hzMember.getUuid(); if (LOG.isTraceEnabled()) { LOG.trace("Reading {} and clearing for {}", new HashMap<>(sqHealthState), clientUUID); } sqHealthState.remove(clientUUID); } @Override public Set<NodeHealth> readAll() { long clusterTime = hzMember.getClusterTime(); long timeout = clusterTime - TIMEOUT_30_SECONDS; Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap(); Set<UUID> hzMemberUUIDs = hzMember.getMemberUuids(); Set<NodeHealth> existingNodeHealths = sqHealthState.entrySet().stream() .filter(outOfDate(timeout)) .filter(ofNonExistentMember(hzMemberUUIDs)) .map(entry -> entry.getValue().getNodeHealth()) .collect(Collectors.toSet()); if (LOG.isTraceEnabled()) { LOG.trace("Reading {} and keeping {}", new HashMap<>(sqHealthState), existingNodeHealths); } return ImmutableSet.copyOf(existingNodeHealths); } private static Predicate<Map.Entry<UUID, TimestampedNodeHealth>> outOfDate(long timeout) { return entry -> { boolean res = entry.getValue().getTimestamp() > timeout; if (!res) { LOG.trace("Ignoring NodeHealth of member {} because it is too old", entry.getKey()); } return res; }; } private static Predicate<Map.Entry<UUID, TimestampedNodeHealth>> ofNonExistentMember(Set<UUID> hzMemberUUIDs) { return entry -> { boolean res = hzMemberUUIDs.contains(entry.getKey()); if (!res) { LOG.trace("Ignoring NodeHealth of member {} because it is not part of the cluster at the moment", entry.getKey()); } return res; }; } private Map<UUID, TimestampedNodeHealth> readReplicatedMap() { return hzMember.getReplicatedMap(HazelcastObjects.SQ_HEALTH_STATE); } }
4,184
35.077586
122
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/TimestampedNodeHealth.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.health; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Objects; public final class TimestampedNodeHealth implements Externalizable { private NodeHealth nodeHealth; private long timestamp; public TimestampedNodeHealth() { // required by Externalizable } public TimestampedNodeHealth(NodeHealth nodeHealth, long timestamp) { this.nodeHealth = nodeHealth; this.timestamp = timestamp; } public NodeHealth getNodeHealth() { return nodeHealth; } public long getTimestamp() { return timestamp; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(timestamp); out.writeObject(nodeHealth); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.timestamp = in.readLong(); this.nodeHealth = (NodeHealth) in.readObject(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimestampedNodeHealth that = (TimestampedNodeHealth) o; return timestamp == that.timestamp && Objects.equals(nodeHealth, that.nodeHealth); } @Override public int hashCode() { return Objects.hash(nodeHealth, timestamp); } @Override public String toString() { return nodeHealth + "@" + timestamp; } }
2,349
26.97619
87
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/health/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.process.cluster.health; import javax.annotation.ParametersAreNonnullByDefault;
972
39.541667
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/DistributedAnswer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.NODE_NAME; /** * Answer of {@link DistributedCall}, aggregating the answers from * all the target members. */ public class DistributedAnswer<T> { private final Map<Member, T> answers = new HashMap<>(); private final Set<Member> timedOutMembers = new HashSet<>(); private final Map<Member, Exception> failedMembers = new HashMap<>(); public Optional<T> getAnswer(Member member) { return Optional.ofNullable(answers.get(member)); } public boolean hasTimedOut(Member member) { return timedOutMembers.contains(member); } public Optional<Exception> getFailed(Member member) { return Optional.ofNullable(failedMembers.get(member)); } public Collection<Member> getMembers() { List<Member> members = new ArrayList<>(); members.addAll(answers.keySet()); members.addAll(timedOutMembers); members.addAll(failedMembers.keySet()); return members; } public void setAnswer(Member member, T answer) { this.answers.put(member, answer); } public void setTimedOut(Member member) { this.timedOutMembers.add(member); } public void setFailed(Member member, Exception e) { failedMembers.put(member, e); } public void propagateExceptions() { if (!failedMembers.isEmpty()) { String failedMemberNames = failedMembers.keySet().stream() .map(m -> m.getAttribute(NODE_NAME.getKey())) .collect(Collectors.joining(", ")); throw new IllegalStateException("Distributed cluster action in cluster nodes " + failedMemberNames + " (other nodes may have timed out)", failedMembers.values().iterator().next()); } if (!timedOutMembers.isEmpty()) { String timedOutMemberNames = timedOutMembers.stream() .map(m -> m.getAttribute(NODE_NAME.getKey())) .collect(Collectors.joining(", ")); throw new IllegalStateException("Distributed cluster action timed out in cluster nodes " + timedOutMemberNames); } } }
3,167
32.702128
143
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/DistributedCall.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import java.io.Serializable; import java.util.concurrent.Callable; public interface DistributedCall<T> extends Callable<T>, Serializable { }
1,024
36.962963
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/DistributedCallback.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import java.util.Map; @FunctionalInterface public interface DistributedCallback<T> { void onComplete(Map<Member, T> response); }
1,051
35.275862
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/HazelcastMember.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Cluster; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.cp.IAtomicReference; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.Lock; import org.sonar.process.ProcessId; public interface HazelcastMember extends AutoCloseable { enum Attribute { /** * The key of the node name attribute of a member */ NODE_NAME("NODE_NAME"), /** * Key of process as defined by {@link ProcessId#getKey()} */ PROCESS_KEY("PROCESS_KEY"); private final String key; Attribute(String key) { this.key = key; } public String getKey() { return key; } } <E> IAtomicReference<E> getAtomicReference(String name); /** * Gets the replicated map shared by the cluster and identified by name. * Result can be casted to {@link com.hazelcast.replicatedmap.ReplicatedMap} if needed to * benefit from listeners. */ <K, V> Map<K, V> getReplicatedMap(String name); UUID getUuid(); /** * The UUIDs of all the members (both members and local clients of these members) currently connected to the * Hazelcast cluster. */ Set<UUID> getMemberUuids(); /** * Gets lock among the cluster, identified by name */ Lock getLock(String name); /** * Retrieves the cluster time which is (almost) identical on all members of the cluster. */ long getClusterTime(); Cluster getCluster(); /** * Runs a distributed query on a set of Hazelcast members. * * @param callable the query that is executed on all target members. Be careful of classloader, don't use classes * that are not available in classpath of target members. * @param memberSelector the subset of members to target. See {@link com.hazelcast.cluster.memberselector.MemberSelectors} * for utilities. * @param timeoutMs the total timeout to get responses from all target members, in milliseconds. If timeout is reached, then * the members that didn't answer on time are marked as timed-out in {@link DistributedAnswer} * @throws java.util.concurrent.RejectedExecutionException if no member is selected */ <T> DistributedAnswer<T> call(DistributedCall<T> callable, MemberSelector memberSelector, long timeoutMs) throws InterruptedException; /** * Runs asynchronously a distributed query on a set of Hazelcast members. * * @param callable the query that is executed on all target members. Be careful of classloader, don't use classes * that are not available in classpath of target members. * @param memberSelector the subset of members to target. See {@link com.hazelcast.cluster.memberselector.MemberSelectors} * for utilities. * @param callback will be called once we get all responses. * @throws java.util.concurrent.RejectedExecutionException if no member is selected */ <T> void callAsync(DistributedCall<T> callable, MemberSelector memberSelector, DistributedCallback<T> callback); @Override void close(); }
4,042
35.098214
131
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/HazelcastMemberBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.config.Config; import com.hazelcast.config.JoinConfig; import com.hazelcast.config.MemberAttributeConfig; import com.hazelcast.config.NetworkConfig; import com.hazelcast.core.Hazelcast; import java.util.List; import java.util.stream.Stream; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.HazelcastMember.Attribute; import static java.lang.String.format; import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.cluster.hz.JoinConfigurationType.KUBERNETES; public class HazelcastMemberBuilder { private String nodeName; private int port; private ProcessId processId; private String networkInterface; private String members; private final JoinConfigurationType type; public HazelcastMemberBuilder(JoinConfigurationType type) { this.type = type; } public HazelcastMemberBuilder setNodeName(String s) { this.nodeName = s; return this; } public HazelcastMemberBuilder setProcessId(ProcessId p) { if (p == ProcessId.ELASTICSEARCH) { throw new IllegalArgumentException("Hazelcast must not be enabled on Elasticsearch node"); } this.processId = p; return this; } public HazelcastMemberBuilder setPort(int i) { this.port = i; return this; } public HazelcastMemberBuilder setNetworkInterface(String s) { this.networkInterface = s; return this; } /** * Adds references to cluster members */ public HazelcastMemberBuilder setMembers(String members) { this.members = members; return this; } public HazelcastMember build() { Config config = new Config(); // do not use the value defined by property sonar.cluster.name. // Hazelcast does not fail when joining a cluster with different name. // Apparently this behavior exists since Hazelcast 3.8.2 (see note // at http://docs.hazelcast.org/docs/3.8.6/manual/html-single/index.html#creating-cluster-groups) config.setClusterName("SonarQube"); // Configure network NetworkConfig netConfig = config.getNetworkConfig(); netConfig .setPort(port) .setPortAutoIncrement(false) .setReuseAddress(true); netConfig.getInterfaces() .setEnabled(true) .setInterfaces(singletonList(requireNonNull(networkInterface, "Network interface is missing"))); JoinConfig joinConfig = netConfig.getJoin(); joinConfig.getAwsConfig().setEnabled(false); joinConfig.getMulticastConfig().setEnabled(false); if (KUBERNETES.equals(type)) { joinConfig.getKubernetesConfig().setEnabled(true) .setProperty("service-dns", requireNonNull(members, "Service DNS is missing")) .setProperty("service-port", CLUSTER_NODE_HZ_PORT.getDefaultValue()); } else { List<String> addressesWithDefaultPorts = Stream.of(this.members.split(",")) .filter(host -> !host.isBlank()) .map(String::trim) .map(HazelcastMemberBuilder::applyDefaultPortToHost) .toList(); joinConfig.getTcpIpConfig().setEnabled(true); joinConfig.getTcpIpConfig().setMembers(requireNonNull(addressesWithDefaultPorts, "Members are missing")); } // We are not using the partition group of Hazelcast, so disabling it config.getPartitionGroupConfig().setEnabled(false); // Tweak HazelCast configuration config // Increase the number of tries .setProperty("hazelcast.tcp.join.port.try.count", "10") // Don't bind on all interfaces .setProperty("hazelcast.socket.bind.any", "false") // Don't phone home .setProperty("hazelcast.phone.home.enabled", "false") // Use slf4j for logging .setProperty("hazelcast.logging.type", "slf4j"); MemberAttributeConfig attributes = config.getMemberAttributeConfig(); attributes.setAttribute(Attribute.NODE_NAME.getKey(), requireNonNull(nodeName, "Node name is missing")); attributes.setAttribute(Attribute.PROCESS_KEY.getKey(), requireNonNull(processId, "Process key is missing").getKey()); return new HazelcastMemberImpl(Hazelcast.newHazelcastInstance(config)); } private static String applyDefaultPortToHost(String host) { return host.contains(":") ? host : format("%s:%s", host, CLUSTER_NODE_HZ_PORT.getDefaultValue()); } }
5,276
35.902098
122
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/HazelcastMemberImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Cluster; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.core.IExecutorService; import com.hazelcast.core.MultiExecutionCallback; import com.hazelcast.cp.IAtomicReference; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Lock; import java.util.stream.Collectors; import org.slf4j.LoggerFactory; class HazelcastMemberImpl implements HazelcastMember { private final HazelcastInstance hzInstance; HazelcastMemberImpl(HazelcastInstance hzInstance) { this.hzInstance = hzInstance; } @Override public <E> IAtomicReference<E> getAtomicReference(String name) { return hzInstance.getCPSubsystem().getAtomicReference(name); } @Override public <K, V> Map<K, V> getReplicatedMap(String s) { return hzInstance.getReplicatedMap(s); } @Override public UUID getUuid() { return hzInstance.getLocalEndpoint().getUuid(); } @Override public Set<UUID> getMemberUuids() { return hzInstance.getCluster().getMembers().stream().map(Member::getUuid).collect(Collectors.toSet()); } @Override public Lock getLock(String s) { return hzInstance.getCPSubsystem().getLock(s); } @Override public long getClusterTime() { return hzInstance.getCluster().getClusterTime(); } @Override public Cluster getCluster() { return hzInstance.getCluster(); } @Override public <T> DistributedAnswer<T> call(DistributedCall<T> callable, MemberSelector memberSelector, long timeoutMs) throws InterruptedException { IExecutorService executor = hzInstance.getExecutorService("default"); Map<Member, Future<T>> futures = executor.submitToMembers(callable, memberSelector); try { DistributedAnswer<T> distributedAnswer = new DistributedAnswer<>(); long maxTime = System.currentTimeMillis() + timeoutMs; for (Map.Entry<Member, Future<T>> entry : futures.entrySet()) { long remainingMs = Math.max(maxTime - System.currentTimeMillis(), 5L); try { T answer = entry.getValue().get(remainingMs, TimeUnit.MILLISECONDS); distributedAnswer.setAnswer(entry.getKey(), answer); } catch (ExecutionException e) { distributedAnswer.setFailed(entry.getKey(), e); } catch (TimeoutException e) { distributedAnswer.setTimedOut(entry.getKey()); } } return distributedAnswer; } finally { futures.values().forEach(f -> f.cancel(true)); } } @Override public <T> void callAsync(DistributedCall<T> callable, MemberSelector memberSelector, DistributedCallback<T> callback) { IExecutorService executor = hzInstance.getExecutorService("default"); // callback doesn't handle failures, so we need to make sure the callable won't fail! executor.submitToMembers(callable, memberSelector, new MultiExecutionCallback() { @Override public void onResponse(Member member, Object value) { // nothing to do when each node responds } @Override public void onComplete(Map<Member, Object> values) { callback.onComplete((Map<Member, T>) values); } }); } @Override public void close() { try { hzInstance.shutdown(); } catch (HazelcastInstanceNotActiveException e) { LoggerFactory.getLogger(getClass()).debug("Unable to shutdown Hazelcast member", e); } } }
4,599
32.576642
122
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/HazelcastMemberSelectors.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.MemberSelector; import java.util.List; import org.sonar.process.ProcessId; import static java.util.Arrays.asList; import static org.sonar.process.ProcessId.fromKey; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.PROCESS_KEY; public class HazelcastMemberSelectors { private HazelcastMemberSelectors() { } public static MemberSelector selectorForProcessIds(ProcessId... processIds) { List<ProcessId> processIdList = asList(processIds); return member -> { ProcessId memberProcessId = fromKey(member.getAttribute(PROCESS_KEY.getKey())); return processIdList.contains(memberProcessId); }; } }
1,557
35.232558
85
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/HazelcastObjects.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; /** * This class holds all object keys accessible via Hazelcast */ public final class HazelcastObjects { /** * The key of replicated map that hold all operational processes */ public static final String OPERATIONAL_PROCESSES = "OPERATIONAL_PROCESSES"; /** * The key of atomic reference holding the leader UUID */ public static final String LEADER = "LEADER"; /** * The key of atomic reference holding the SonarQube version of the cluster */ public static final String SONARQUBE_VERSION = "SONARQUBE_VERSION"; /** * The key of atomic reference holding the name of the cluster (used for precondition checks) */ public static final String CLUSTER_NAME = "CLUSTER_NAME"; /** * The key of replicated map holding the CeWorker UUIDs */ public static final String WORKER_UUIDS = "WORKER_UUIDS"; /** * The key of the lock for executing CE_CLEANING_JOB * {@link CeCleaningSchedulerImpl} */ public static final String CE_CLEANING_JOB_LOCK = "CE_CLEANING_JOB_LOCK"; /** * THe key of the replicated map holding the health state information of all SQ nodes. */ public static final String SQ_HEALTH_STATE = "sq_health_state"; private HazelcastObjects() { // Holder for clustered objects } }
2,142
34.716667
95
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/JoinConfigurationType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.cluster.hz; public enum JoinConfigurationType { TCP_IP, KUBERNETES }
943
35.307692
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/cluster/hz/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.process.cluster.hz; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/AbstractLogHelper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import java.util.Arrays; import javax.annotation.CheckForNull; import org.sonar.process.Props; import static java.lang.String.format; public abstract class AbstractLogHelper { static final Level[] ALLOWED_ROOT_LOG_LEVELS = new Level[] {Level.TRACE, Level.DEBUG, Level.INFO}; private static final String PREFIX_LOG_FORMAT = "%d{yyyy.MM.dd HH:mm:ss} %-5level "; private static final String SUFFIX_LOG_FORMAT = " %msg%n"; private final String loggerNamePattern; protected AbstractLogHelper(String loggerNamePattern) { this.loggerNamePattern = loggerNamePattern; } public abstract String getRootLoggerName(); public String buildLogPattern(RootLoggerConfig config) { return PREFIX_LOG_FORMAT + (config.getNodeNameField().isBlank() ? "" : (config.getNodeNameField() + " ")) + config.getProcessId().getKey() + "[" + config.getThreadIdFieldPattern() + "]" + "[" + loggerNamePattern + "]" + SUFFIX_LOG_FORMAT; } /** * Resolve a log level reading the value of specified properties. * <p> * To compute the applied log level the following rules will be followed: * <ul>the last property with a defined and valid value in the order of the {@code propertyKeys} argument will be applied</ul> * <ul>if there is none, {@link Level#INFO INFO} will be returned</ul> * </p> * * @throws IllegalArgumentException if the value of the specified property is not one of {@link #ALLOWED_ROOT_LOG_LEVELS} */ static Level resolveLevel(Props props, String... propertyKeys) { Level newLevel = Level.INFO; for (String propertyKey : propertyKeys) { Level level = getPropertyValueAsLevel(props, propertyKey); if (level != null) { newLevel = level; } } return newLevel; } @CheckForNull static Level getPropertyValueAsLevel(Props props, String propertyKey) { String value = props.value(propertyKey); if (value == null) { return null; } Level level = Level.toLevel(value, Level.INFO); if (!isAllowed(level)) { throw new IllegalArgumentException(format("log level %s in property %s is not a supported value (allowed levels are %s)", level, propertyKey, Arrays.toString(ALLOWED_ROOT_LOG_LEVELS))); } return level; } static boolean isAllowed(Level level) { for (Level allowedRootLogLevel : ALLOWED_ROOT_LOG_LEVELS) { if (level.equals(allowedRootLogLevel)) { return true; } } return false; } }
3,400
34.427083
128
java
sonarqube
sonarqube-master/server/sonar-process/src/main/java/org/sonar/process/logging/EscapedMessageConverter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.logging; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback.classic.spi.ILoggingEvent; import java.util.regex.Pattern; /** * Escapes log message which contains CR LF sequence */ public class EscapedMessageConverter extends ClassicConverter { private static final Pattern CR_PATTERN = Pattern.compile("\r"); private static final Pattern LF_PATTERN = Pattern.compile("\n"); public String convert(ILoggingEvent event) { String formattedMessage = event.getFormattedMessage(); if (formattedMessage != null) { String result = CR_PATTERN.matcher(formattedMessage).replaceAll("\\\\r"); result = LF_PATTERN.matcher(result).replaceAll("\\\\n"); return result; } return null; } }
1,614
34.888889
79
java