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-ce/src/main/java/org/sonar/ce/CeDistributedInformation.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.ce;
import java.util.Set;
import java.util.concurrent.locks.Lock;
/**
* CeDistributedInformation is the interface to be implemented in order
* to implement information shared by all CE nodes
*/
public interface CeDistributedInformation {
Set<String> getWorkerUUIDs();
/**
* This method must be called once the workers of the current Compute Engine node
* are up so that they are shared with other Compute Engine nodes
*/
void broadcastWorkerUUIDs();
/**
* Acquire a lock among all the Compute Engines
*/
Lock acquireCleanJobLock();
}
| 1,427 | 32.209302 | 83 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/CeDistributedInformationImpl.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.ce;
import com.hazelcast.spi.exception.RetryableHazelcastException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import org.sonar.api.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import org.sonar.process.cluster.hz.HazelcastMember;
import org.sonar.process.cluster.hz.HazelcastObjects;
import static org.sonar.process.cluster.hz.HazelcastObjects.WORKER_UUIDS;
/**
* Provide the set of worker's UUID in a clustered SonarQube instance
*/
public class CeDistributedInformationImpl implements CeDistributedInformation, Startable {
private static final Logger LOGGER = LoggerFactory.getLogger(CeDistributedInformationImpl.class);
private final HazelcastMember hazelcastMember;
private final CeWorkerFactory ceCeWorkerFactory;
public CeDistributedInformationImpl(HazelcastMember hazelcastMember, CeWorkerFactory ceCeWorkerFactory) {
this.hazelcastMember = hazelcastMember;
this.ceCeWorkerFactory = ceCeWorkerFactory;
}
@Override
public Set<String> getWorkerUUIDs() {
Set<UUID> connectedWorkerUUIDs = hazelcastMember.getMemberUuids();
return getClusteredWorkerUUIDs().entrySet().stream()
.filter(e -> connectedWorkerUUIDs.contains(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(Set::stream)
.collect(Collectors.toSet());
}
@Override
public void broadcastWorkerUUIDs() {
Set<CeWorker> workers = ceCeWorkerFactory.getWorkers();
Set<String> workerUuids = workers.stream().map(CeWorker::getUUID).collect(Collectors.toSet());
getClusteredWorkerUUIDs().put(hazelcastMember.getUuid(), workerUuids);
}
@Override
public Lock acquireCleanJobLock() {
return hazelcastMember.getLock(HazelcastObjects.CE_CLEANING_JOB_LOCK);
}
@Override
public void start() {
// Nothing to do here
}
@Override
public void stop() {
try {
// Removing the worker UUIDs
getClusteredWorkerUUIDs().remove(hazelcastMember.getUuid());
} catch (RetryableHazelcastException e) {
LOGGER.debug("Unable to remove worker UUID from the list of active workers", e.getMessage());
}
}
private Map<UUID, Set<String>> getClusteredWorkerUUIDs() {
return hazelcastMember.getReplicatedMap(WORKER_UUIDS);
}
}
| 3,277 | 33.87234 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/CeHttpModule.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.ce;
import org.sonar.ce.httpd.CeHttpServer;
import org.sonar.ce.logging.ChangeLogLevelHttpAction;
import org.sonar.ce.systeminfo.SystemInfoHttpAction;
import org.sonar.core.platform.Module;
public class CeHttpModule extends Module {
@Override
protected void configureModule() {
add(
CeHttpServer.class,
SystemInfoHttpAction.class,
ChangeLogLevelHttpAction.class);
}
}
| 1,259 | 34 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/CeQueueModule.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.ce;
import org.sonar.ce.monitoring.CeTasksMBeanImpl;
import org.sonar.ce.queue.CeQueueInitializer;
import org.sonar.ce.queue.InternalCeQueueImpl;
import org.sonar.ce.queue.NextPendingTaskPicker;
import org.sonar.core.platform.Module;
public class CeQueueModule extends Module {
@Override
protected void configureModule() {
add(
// queue state
InternalCeQueueImpl.class,
NextPendingTaskPicker.class,
// queue monitoring
CeTasksMBeanImpl.class,
// init queue state and queue processing
CeQueueInitializer.class);
}
}
| 1,432 | 32.325581 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/CeTaskCommonsModule.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.ce;
import org.sonar.ce.task.projectanalysis.purge.IndexPurgeListener;
import org.sonar.ce.task.projectanalysis.purge.ProjectCleaner;
import org.sonar.core.platform.Module;
import org.sonar.db.purge.period.DefaultPeriodCleaner;
/**
* Globally available components in CE for tasks to use.
*/
public class CeTaskCommonsModule extends Module {
@Override
protected void configureModule() {
add(
DefaultPeriodCleaner.class,
ProjectCleaner.class,
IndexPurgeListener.class);
}
}
| 1,365 | 34.025641 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngine.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.ce;
/**
* The Compute Engine program.
*/
public interface ComputeEngine {
/**
* @throws IllegalStateException when called more than once
*/
void startup();
/**
* Terminates all CE workers and blocks until then.
*
* @throws IllegalStateException if {@link #startup()} has never been called
* @throws IllegalStateException if called after {@link #shutdown()}
* @throws IllegalStateException when called more than once
*/
void stopProcessing();
/**
* Terminates all CE workers and stops the Compute Engine releasing all resources, and blocks until then.
*
* @throws IllegalStateException if {@link #startup()} has never been called
* @throws IllegalStateException when called more than once
*/
void shutdown();
}
| 1,628 | 32.244898 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngineImpl.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.ce;
import org.sonar.ce.container.ComputeEngineStatus;
import org.sonar.ce.container.ComputeEngineContainer;
import org.sonar.process.Props;
import static com.google.common.base.Preconditions.checkState;
public class ComputeEngineImpl implements ComputeEngine, ComputeEngineStatus {
private final Props props;
private final ComputeEngineContainer computeEngineContainer;
private Status status = Status.INIT;
public ComputeEngineImpl(Props props, ComputeEngineContainer computeEngineContainer) {
this.props = props;
this.computeEngineContainer = computeEngineContainer;
computeEngineContainer.setComputeEngineStatus(this);
}
@Override
public void startup() {
checkState(this.status == Status.INIT, "startup() can not be called multiple times");
try {
this.status = Status.STARTING;
this.computeEngineContainer.start(props);
} finally {
this.status = Status.STARTED;
}
}
@Override
public void stopProcessing() {
checkState(this.status.ordinal() >= Status.STARTED.ordinal(), "stopProcessing() must not be called before startup()");
checkState(this.status.ordinal() <= Status.STOPPING.ordinal(), "stopProcessing() can not be called after shutdown()");
checkState(this.status.ordinal() <= Status.STOPPING_WORKERS.ordinal(), "stopProcessing() can not be called multiple times");
try {
this.status = Status.STOPPING_WORKERS;
this.computeEngineContainer.stopWorkers();
} finally {
this.status = Status.WORKERS_STOPPED;
}
}
@Override
public void shutdown() {
checkState(this.status.ordinal() >= Status.STARTED.ordinal(), "shutdown() must not be called before startup()");
checkState(this.status.ordinal() <= Status.STOPPING.ordinal(), "shutdown() can not be called multiple times");
try {
this.status = Status.STOPPING;
this.computeEngineContainer.stop();
} finally {
this.status = Status.STOPPED;
}
}
@Override
public Status getStatus() {
return status;
}
}
| 2,885 | 34.195122 | 128 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/StandaloneCeDistributedInformation.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.ce;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import static com.google.common.base.Preconditions.checkState;
/**
* Provide the set of worker's UUID in a non clustered SonarQube instance
*/
public class StandaloneCeDistributedInformation implements CeDistributedInformation {
private final CeWorkerFactory ceCeWorkerFactory;
private Set<String> workerUUIDs;
private Lock cleanJobLock = new NonConcurrentLock();
public StandaloneCeDistributedInformation(CeWorkerFactory ceCeWorkerFactory) {
this.ceCeWorkerFactory = ceCeWorkerFactory;
}
@Override
public Set<String> getWorkerUUIDs() {
checkState(workerUUIDs != null, "Invalid call, broadcastWorkerUUIDs() must be called first.");
return workerUUIDs;
}
@Override
public void broadcastWorkerUUIDs() {
Set<CeWorker> workers = ceCeWorkerFactory.getWorkers();
workerUUIDs = workers.stream().map(CeWorker::getUUID).collect(Collectors.toSet());
}
/**
* Since StandaloneCeDistributedInformation in fact does not provide any distribution support, the lock returned by
* this method provides no concurrency support at all.
*/
@Override
public Lock acquireCleanJobLock() {
return cleanJobLock;
}
private static class NonConcurrentLock implements Lock {
@Override
public void lock() {
// return immediately and never block
}
@Override
public void lockInterruptibly() {
// return immediately and never block
}
@Override
public boolean tryLock() {
// always succeed
return true;
}
@Override
public boolean tryLock(long time, TimeUnit unit) {
// always succeed
return true;
}
@Override
public void unlock() {
// nothing to do
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("newCondition not supported");
}
}
}
| 2,980 | 28.81 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/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.ce;
import javax.annotation.ParametersAreNonnullByDefault;
| 952 | 38.708333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningExecutorService.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.ce.analysis.cache.cleaning;
import java.util.concurrent.ScheduledExecutorService;
public interface AnalysisCacheCleaningExecutorService extends ScheduledExecutorService {
}
| 1,036 | 38.884615 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningExecutorServiceImpl.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.ce.analysis.cache.cleaning;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl;
public class AnalysisCacheCleaningExecutorServiceImpl extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService>
implements AnalysisCacheCleaningExecutorService {
public AnalysisCacheCleaningExecutorServiceImpl() {
super(Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("Analysis_cache_cleaning-%d")
.build()));
}
}
| 1,555 | 39.947368 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningModule.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.ce.analysis.cache.cleaning;
import org.sonar.core.platform.Module;
public class AnalysisCacheCleaningModule extends Module {
@Override protected void configureModule() {
add(
AnalysisCacheCleaningExecutorServiceImpl.class,
AnalysisCacheCleaningSchedulerImpl.class
);
}
}
| 1,158 | 35.21875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningScheduler.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.ce.analysis.cache.cleaning;
import org.sonar.api.platform.ServerStartHandler;
public interface AnalysisCacheCleaningScheduler extends ServerStartHandler {
}
| 1,020 | 38.269231 | 76 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningSchedulerImpl.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.ce.analysis.cache.cleaning;
import com.google.common.annotations.VisibleForTesting;
import java.time.Duration;
import java.time.LocalDateTime;
import org.sonar.api.platform.Server;
import org.sonar.db.DbClient;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;
public class AnalysisCacheCleaningSchedulerImpl implements AnalysisCacheCleaningScheduler {
private final AnalysisCacheCleaningExecutorService executorService;
private final DbClient dbClient;
public AnalysisCacheCleaningSchedulerImpl(AnalysisCacheCleaningExecutorService executorService, DbClient dbClient) {
this.executorService = executorService;
this.dbClient = dbClient;
}
@Override public void onServerStart(Server server) {
LocalDateTime now = LocalDateTime.now();
// schedule run at midnight everyday
LocalDateTime nextRun = now.plusDays(1).withHour(0).withMinute(0).withSecond(0);
long initialDelay = Duration.between(now, nextRun).getSeconds();
executorService.scheduleAtFixedRate(this::clean, initialDelay, DAYS.toSeconds(1), SECONDS);
}
@VisibleForTesting
void clean() {
try (var dbSession = dbClient.openSession(false)) {
dbClient.scannerAnalysisCacheDao().cleanOlderThan7Days(dbSession);
dbSession.commit();
}
}
}
| 2,175 | 37.857143 | 118 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/analysis/cache/cleaning/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.ce.analysis.cache.cleaning;
import javax.annotation.ParametersAreNonnullByDefault;
| 976 | 39.708333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/app/CeSecurityManager.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.ce.app;
import org.sonar.ce.security.PluginCeRule;
import org.sonar.process.PluginFileWriteRule;
import org.sonar.process.PluginSecurityManager;
import org.sonar.process.ProcessProperties;
import org.sonar.process.Props;
public class CeSecurityManager {
private final PluginSecurityManager pluginSecurityManager;
private final Props props;
private boolean applied;
public CeSecurityManager(PluginSecurityManager pluginSecurityManager, Props props) {
this.pluginSecurityManager = pluginSecurityManager;
this.props = props;
}
public void apply() {
if (applied) {
throw new IllegalStateException("can't apply twice");
}
applied = true;
PluginFileWriteRule writeRule = new PluginFileWriteRule(
props.nonNullValueAsFile(ProcessProperties.Property.PATH_HOME.getKey()).toPath(),
props.nonNullValueAsFile(ProcessProperties.Property.PATH_TEMP.getKey()).toPath());
PluginCeRule ceRule = new PluginCeRule();
pluginSecurityManager.restrictPlugins(writeRule, ceRule);
}
}
| 1,890 | 35.365385 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/app/CeServer.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.ce.app;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.ComputeEngine;
import org.sonar.ce.ComputeEngineImpl;
import org.sonar.ce.container.ComputeEngineContainerImpl;
import org.sonar.ce.logging.CeProcessLogging;
import org.sonar.process.MinimumViableSystem;
import org.sonar.process.Monitored;
import org.sonar.process.PluginSecurityManager;
import org.sonar.process.ProcessEntryPoint;
import org.sonar.process.Props;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.process.ProcessId.COMPUTE_ENGINE;
/**
* The Compute Engine server which starts a daemon thread to run the {@link ComputeEngineImpl} when it's {@link #start()}
* method is called.
* <p>
* This is the class to call to run a standalone {@link ComputeEngineImpl} (see {@link #main(String[])}).
* </p>
*/
public class CeServer implements Monitored {
private static final Logger LOG = LoggerFactory.getLogger(CeServer.class);
private static final String CE_MAIN_THREAD_NAME = "ce-main";
private final CountDownLatch awaitStop = new CountDownLatch(1);
private final ComputeEngine computeEngine;
@Nullable
private CeMainThread ceMainThread = null;
@VisibleForTesting
protected CeServer(ComputeEngine computeEngine, MinimumViableSystem mvs, CeSecurityManager securityManager) {
securityManager.apply();
this.computeEngine = computeEngine;
mvs
.checkWritableTempDir()
.checkRequiredJavaOptions(ImmutableMap.of("file.encoding", "UTF-8"));
}
@Override
public void start() {
checkState(ceMainThread == null, "start() can not be called twice");
// start main thread
ceMainThread = new CeMainThread();
ceMainThread.start();
}
@Override
public Status getStatus() {
checkState(ceMainThread != null, "getStatus() can not be called before start()");
if (ceMainThread.isStarted()) {
return ceMainThread.isOperational() ? Status.OPERATIONAL : Status.FAILED;
}
return Status.DOWN;
}
@Override
public void awaitStop() {
checkState(ceMainThread != null, "awaitStop() must not be called before start()");
while (true) {
try {
awaitStop.await();
return;
} catch (InterruptedException e) {
// abort waiting
}
}
}
@Override
public void stop() {
if (ceMainThread != null) {
ceMainThread.stopIt();
awaitStop();
}
}
@Override
public void hardStop() {
if (ceMainThread != null) {
ceMainThread.stopItNow();
awaitStop();
}
}
/**
* Can't be started as is. Needs to be bootstrapped by sonar-application
*/
public static void main(String[] args) {
ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);
Props props = entryPoint.getProps();
new CeProcessLogging().configure(props);
CeServer server = new CeServer(
new ComputeEngineImpl(props, new ComputeEngineContainerImpl()),
new MinimumViableSystem(),
new CeSecurityManager(new PluginSecurityManager(), props));
entryPoint.launch(server);
}
private class CeMainThread extends Thread {
private final CountDownLatch stopSignal = new CountDownLatch(1);
private volatile boolean started = false;
private volatile boolean operational = false;
private volatile boolean hardStop = false;
private volatile boolean dontInterrupt = false;
public CeMainThread() {
super(CE_MAIN_THREAD_NAME);
}
@Override
public void run() {
boolean startupSuccessful = attemptStartup();
this.operational = startupSuccessful;
this.started = true;
try {
if (startupSuccessful) {
try {
stopSignal.await();
} catch (InterruptedException e) {
// don't restore interrupt flag since it would be unset in attemptShutdown anyway
}
attemptShutdown();
}
} finally {
// release thread(s) waiting for CeServer to stop
signalAwaitStop();
}
}
private boolean attemptStartup() {
try {
LOG.info("{} starting up...", COMPUTE_ENGINE.getHumanReadableName());
computeEngine.startup();
LOG.info("{} is started", COMPUTE_ENGINE.getHumanReadableName());
return true;
} catch (org.sonar.api.utils.MessageException | org.sonar.process.MessageException e) {
LOG.error("{} startup failed: {}", COMPUTE_ENGINE.getHumanReadableName(), e.getMessage());
return false;
} catch (Throwable e) {
LOG.error("{} startup failed", COMPUTE_ENGINE.getHumanReadableName(), e);
return false;
}
}
private void attemptShutdown() {
try {
LOG.info("{} is stopping...", COMPUTE_ENGINE.getHumanReadableName());
if (!hardStop) {
computeEngine.stopProcessing();
}
dontInterrupt = true;
// make sure that interrupt flag is unset because we don't want to interrupt shutdown of pico container
interrupted();
computeEngine.shutdown();
LOG.info("{} is stopped", COMPUTE_ENGINE.getHumanReadableName());
} catch (Throwable e) {
LOG.error("{} failed to stop", COMPUTE_ENGINE.getHumanReadableName(), e);
}
}
public boolean isStarted() {
return started;
}
public boolean isOperational() {
return operational;
}
public void stopIt() {
stopSignal.countDown();
}
public void stopItNow() {
hardStop = true;
stopSignal.countDown();
// interrupt current thread unless it's already performing shutdown
if (!dontInterrupt) {
interrupt();
}
}
private void signalAwaitStop() {
awaitStop.countDown();
}
}
}
| 6,793 | 30.022831 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/app/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.ce.app;
import javax.annotation.ParametersAreNonnullByDefault;
| 956 | 38.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/async/SynchronousAsyncExecution.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.ce.async;
import org.sonar.server.async.AsyncExecution;
public class SynchronousAsyncExecution implements AsyncExecution {
@Override
public void addToQueue(Runnable r) {
r.run();
}
}
| 1,056 | 34.233333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/async/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.ce.async;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 38.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningExecutorService.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.ce.cleaning;
import java.util.concurrent.ScheduledExecutorService;
public interface CeCleaningExecutorService extends ScheduledExecutorService {
}
| 1,010 | 37.884615 | 77 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningExecutorServiceImpl.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.ce.cleaning;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl;
public class CeCleaningExecutorServiceImpl
extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService>
implements CeCleaningExecutorService {
public CeCleaningExecutorServiceImpl() {
super(Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setDaemon(false)
.setNameFormat("CE_cleaning-%d")
.build()));
}
}
| 1,498 | 37.435897 | 81 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningModule.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.ce.cleaning;
import org.sonar.core.platform.Module;
public class CeCleaningModule extends Module {
@Override
protected void configureModule() {
add(
CeCleaningExecutorServiceImpl.class,
CeCleaningSchedulerImpl.class);
}
}
| 1,107 | 33.625 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningScheduler.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.ce.cleaning;
public interface CeCleaningScheduler {
void startScheduling();
}
| 942 | 36.72 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningSchedulerImpl.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.ce.cleaning;
import java.util.concurrent.locks.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.CeDistributedInformation;
import org.sonar.ce.configuration.CeConfiguration;
import org.sonar.ce.queue.InternalCeQueue;
import static java.util.concurrent.TimeUnit.MINUTES;
public class CeCleaningSchedulerImpl implements CeCleaningScheduler {
private static final Logger LOG = LoggerFactory.getLogger(CeCleaningSchedulerImpl.class);
private final CeCleaningExecutorService executorService;
private final CeConfiguration ceConfiguration;
private final InternalCeQueue internalCeQueue;
private final CeDistributedInformation ceDistributedInformation;
public CeCleaningSchedulerImpl(CeCleaningExecutorService executorService, CeConfiguration ceConfiguration,
InternalCeQueue internalCeQueue, CeDistributedInformation ceDistributedInformation) {
this.executorService = executorService;
this.internalCeQueue = internalCeQueue;
this.ceConfiguration = ceConfiguration;
this.ceDistributedInformation = ceDistributedInformation;
}
@Override
public void startScheduling() {
executorService.scheduleWithFixedDelay(this::cleanCeQueue,
ceConfiguration.getCleanTasksInitialDelay(),
ceConfiguration.getCleanTasksDelay(),
MINUTES);
}
private void cleanCeQueue() {
Lock ceCleaningJobLock = ceDistributedInformation.acquireCleanJobLock();
// If we cannot lock that means that another job is running
// So we skip resetting and cancelling tasks in queue
if (ceCleaningJobLock.tryLock()) {
try {
resetTasksWithUnknownWorkerUUIDs();
cancelWornOuts();
} finally {
ceCleaningJobLock.unlock();
}
}
}
private void resetTasksWithUnknownWorkerUUIDs() {
try {
LOG.trace("Resetting state of tasks with unknown worker UUIDs");
internalCeQueue.resetTasksWithUnknownWorkerUUIDs(ceDistributedInformation.getWorkerUUIDs());
} catch (Exception e) {
LOG.warn("Failed to reset tasks with unknown worker UUIDs", e);
}
}
private void cancelWornOuts() {
try {
LOG.trace("Cancelling any worn out task");
internalCeQueue.cancelWornOuts();
} catch (Exception e) {
LOG.warn("Failed to cancel worn out tasks", e);
}
}
}
| 3,172 | 35.056818 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/cleaning/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.ce.cleaning;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 39.083333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/configuration/CeConfiguration.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.ce.configuration;
public interface CeConfiguration {
/**
* The maximum number of workers to process CeTasks concurrently, integer strictly greater than 0.
*/
int getWorkerMaxCount();
/**
* The number of workers to process CeTasks concurrently, integer strictly greater than 0.
*/
int getWorkerCount();
/**
* The delay in millisecond before a {@link org.sonar.ce.taskprocessor.CeWorker} shall try and find a task
* to process when it's previous execution had nothing to do.
*/
long getQueuePollingDelay();
/**
* Delay before running job that cleans CE tasks for the first time (in minutes).
*/
long getCleanTasksInitialDelay();
/**
* Delay between the end of a run and the start of the next one of the job that cleans CE tasks (in minutes).
*/
long getCleanTasksDelay();
/**
* Delay before stopping workers during a graceful timeout using milliseconds unit.
*/
long getGracefulStopTimeoutInMs();
}
| 1,829 | 31.678571 | 111 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/configuration/CeConfigurationImpl.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.ce.configuration;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.springframework.beans.factory.annotation.Autowired;
import static java.lang.String.format;
import static org.sonar.process.ProcessProperties.Property.CE_GRACEFUL_STOP_TIMEOUT;
/**
* Immutable implementation of {@link CeConfiguration} initialized at startup from {@link Configuration}.
*/
public class CeConfigurationImpl implements CeConfiguration {
private static final int DEFAULT_WORKER_THREAD_COUNT = 1;
private static final int MAX_WORKER_THREAD_COUNT = 10;
private static final int DEFAULT_WORKER_COUNT = 1;
// 2 seconds
private static final long DEFAULT_QUEUE_POLLING_DELAY = 2 * 1000L;
// 0 minute
private static final long CANCEL_WORN_OUTS_INITIAL_DELAY = 0;
// 2 minutes
private static final long CANCEL_WORN_OUTS_DELAY = 2;
@CheckForNull
private final WorkerCountProvider workerCountProvider;
private final int workerThreadCount;
private final long gracefulStopTimeoutInMs;
private int workerCount;
@Autowired(required = false)
public CeConfigurationImpl(Configuration configuration) {
this(configuration, null);
}
@Autowired(required = false)
public CeConfigurationImpl(Configuration configuration, @Nullable WorkerCountProvider workerCountProvider) {
this.workerCountProvider = workerCountProvider;
this.gracefulStopTimeoutInMs = configuration.getLong(CE_GRACEFUL_STOP_TIMEOUT.getKey())
.orElse(Long.parseLong(CE_GRACEFUL_STOP_TIMEOUT.getDefaultValue()));
if (workerCountProvider == null) {
this.workerCount = DEFAULT_WORKER_COUNT;
this.workerThreadCount = DEFAULT_WORKER_THREAD_COUNT;
} else {
this.workerCount = readWorkerCount(workerCountProvider);
this.workerThreadCount = MAX_WORKER_THREAD_COUNT;
}
}
private static synchronized int readWorkerCount(WorkerCountProvider workerCountProvider) {
int value = workerCountProvider.get();
if (value < DEFAULT_WORKER_COUNT || value > MAX_WORKER_THREAD_COUNT) {
throw parsingError(value);
}
return value;
}
private static MessageException parsingError(int value) {
return MessageException.of(format(
"Worker count '%s' is invalid. It must be an integer strictly greater than 0 and less or equal to 10",
value));
}
@Override
public int getWorkerMaxCount() {
return workerThreadCount;
}
@Override
public int getWorkerCount() {
if (workerCountProvider != null) {
workerCount = readWorkerCount(workerCountProvider);
}
return workerCount;
}
@Override
public long getQueuePollingDelay() {
return DEFAULT_QUEUE_POLLING_DELAY;
}
@Override
public long getCleanTasksInitialDelay() {
return CANCEL_WORN_OUTS_INITIAL_DELAY;
}
@Override
public long getCleanTasksDelay() {
return CANCEL_WORN_OUTS_DELAY;
}
@Override
public long getGracefulStopTimeoutInMs() {
return gracefulStopTimeoutInMs;
}
}
| 3,920 | 32.228814 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/configuration/CeWorkerCountSettingWarning.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.ce.configuration;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Displays a warning in the logs if property "sonar.ce.workerCount" is defined as it has been replaced
* by an internal property (see SONAR-9507).
*/
public class CeWorkerCountSettingWarning implements Startable {
private static final String PROPERTY_SONAR_CE_WORKER_COUNT = "sonar.ce.workerCount";
private static final Logger LOG = LoggerFactory.getLogger(CeWorkerCountSettingWarning.class);
private final Configuration configuration;
public CeWorkerCountSettingWarning(Configuration configuration) {
this.configuration = configuration;
}
@Override
public void start() {
configuration.get(PROPERTY_SONAR_CE_WORKER_COUNT)
.ifPresent(workerCount -> LOG.warn("Property {} is not supported anymore and will be ignored." +
" Remove it from sonar.properties to remove this warning.",
PROPERTY_SONAR_CE_WORKER_COUNT));
}
@Override
public void stop() {
// nothing to do
}
}
| 1,947 | 35.074074 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/configuration/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.ce.configuration;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 39.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/CePluginJarExploder.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.ce.container;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.sonar.server.platform.ServerFileSystem;
import org.sonar.api.utils.ZipUtils;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginJarExploder;
/**
* Explodes the plugin JARs of extensions/plugins or lib/extensions into a temporary directory
* dedicated to compute engine.
*/
public class CePluginJarExploder extends PluginJarExploder {
private static final String TEMP_RELATIVE_PATH = "ce-exploded-plugins";
private final ServerFileSystem fs;
public CePluginJarExploder(ServerFileSystem fs) {
this.fs = fs;
}
@Override
public ExplodedPlugin explode(PluginInfo pluginInfo) {
File tempDir = new File(fs.getTempDir(), TEMP_RELATIVE_PATH);
File toDir = new File(tempDir, pluginInfo.getKey());
try {
org.sonar.core.util.FileUtils.cleanDirectory(toDir);
File jarSource = pluginInfo.getNonNullJarFile();
File jarTarget = new File(toDir, jarSource.getName());
FileUtils.copyFile(jarSource, jarTarget);
ZipUtils.unzip(jarSource, toDir, newLibFilter());
return explodeFromUnzippedDir(pluginInfo, jarTarget, toDir);
} catch (Exception e) {
throw new IllegalStateException(String.format(
"Fail to unzip plugin [%s] %s to %s", pluginInfo.getKey(), pluginInfo.getNonNullJarFile().getAbsolutePath(), toDir.getAbsolutePath()), e);
}
}
}
| 2,339 | 37.360656 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/CePluginRepository.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.ce.container;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.sonar.api.Plugin;
import org.sonar.api.Startable;
import org.slf4j.LoggerFactory;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.server.platform.ServerFileSystem;
import org.sonar.server.plugins.PluginRequirementsValidator;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
/**
* Entry point to load plugins on startup. It assumes that plugins
* have been correctly installed/uninstalled/updated during web server startup
*/
public class CePluginRepository implements PluginRepository, Startable {
private static final String[] JAR_FILE_EXTENSIONS = new String[] {"jar"};
private static final String NOT_STARTED_YET = "not started yet";
private final ServerFileSystem fs;
private final PluginClassLoader loader;
private final CePluginJarExploder cePluginJarExploder;
private final AtomicBoolean started = new AtomicBoolean(false);
// following fields are available after startup
private final Map<String, PluginInfo> pluginInfosByKeys = new HashMap<>();
private final Map<String, Plugin> pluginInstancesByKeys = new HashMap<>();
public CePluginRepository(ServerFileSystem fs, PluginClassLoader loader, CePluginJarExploder cePluginJarExploder) {
this.fs = fs;
this.loader = loader;
this.cePluginJarExploder = cePluginJarExploder;
}
@Override
public void start() {
LoggerFactory.getLogger(getClass()).info("Load plugins");
registerPluginsFromDir(fs.getInstalledBundledPluginsDir());
registerPluginsFromDir(fs.getInstalledExternalPluginsDir());
PluginRequirementsValidator.unloadIncompatiblePlugins(pluginInfosByKeys);
Map<String, ExplodedPlugin> explodedPluginsByKey = extractPlugins(pluginInfosByKeys);
pluginInstancesByKeys.putAll(loader.load(explodedPluginsByKey));
started.set(true);
}
private void registerPluginsFromDir(File pluginsDir) {
for (File file : listJarFiles(pluginsDir)) {
PluginInfo info = PluginInfo.create(file);
pluginInfosByKeys.put(info.getKey(), info);
}
}
private Map<String, ExplodedPlugin> extractPlugins(Map<String, PluginInfo> pluginsByKey) {
return pluginsByKey.values().stream()
.map(cePluginJarExploder::explode)
.collect(Collectors.toMap(ExplodedPlugin::getKey, p -> p));
}
@Override
public void stop() {
// close classloaders
loader.unload(pluginInstancesByKeys.values());
pluginInstancesByKeys.clear();
pluginInfosByKeys.clear();
started.set(false);
}
@Override
public Collection<PluginInfo> getPluginInfos() {
checkState(started.get(), NOT_STARTED_YET);
return Set.copyOf(pluginInfosByKeys.values());
}
@Override
public PluginInfo getPluginInfo(String key) {
checkState(started.get(), NOT_STARTED_YET);
PluginInfo info = pluginInfosByKeys.get(key);
if (info == null) {
throw new IllegalArgumentException(format("Plugin [%s] does not exist", key));
}
return info;
}
@Override
public Plugin getPluginInstance(String key) {
checkState(started.get(), NOT_STARTED_YET);
Plugin plugin = pluginInstancesByKeys.get(key);
checkArgument(plugin != null, "Plugin [%s] does not exist", key);
return plugin;
}
@Override
public Collection<Plugin> getPluginInstances() {
return pluginInstancesByKeys.values();
}
@Override
public boolean hasPlugin(String key) {
checkState(started.get(), NOT_STARTED_YET);
return pluginInfosByKeys.containsKey(key);
}
private static Collection<File> listJarFiles(File dir) {
if (dir.exists()) {
return FileUtils.listFiles(dir, JAR_FILE_EXTENSIONS, false);
}
return Collections.emptyList();
}
}
| 5,057 | 33.643836 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainer.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.ce.container;
import org.sonar.process.Props;
public interface ComputeEngineContainer {
void setComputeEngineStatus(ComputeEngineStatus computeEngineStatus);
ComputeEngineContainer start(Props props);
ComputeEngineContainer stopWorkers();
ComputeEngineContainer stop();
}
| 1,146 | 33.757576 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.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.ce.container;
import com.google.common.annotations.VisibleForTesting;
import java.time.Clock;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.internal.MetadataLoader;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.profiles.XMLProfileParser;
import org.sonar.api.profiles.XMLProfileSerializer;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.rules.AnnotationRuleParser;
import org.sonar.api.server.profile.BuiltInQualityProfileAnnotationLoader;
import org.sonar.api.server.rule.RulesDefinitionXmlLoader;
import org.sonar.api.utils.Durations;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.UriReader;
import org.sonar.api.utils.Version;
import org.slf4j.LoggerFactory;
import org.sonar.ce.CeConfigurationModule;
import org.sonar.ce.CeDistributedInformationImpl;
import org.sonar.ce.CeHttpModule;
import org.sonar.ce.CeQueueModule;
import org.sonar.ce.CeTaskCommonsModule;
import org.sonar.ce.StandaloneCeDistributedInformation;
import org.sonar.ce.analysis.cache.cleaning.AnalysisCacheCleaningModule;
import org.sonar.ce.async.SynchronousAsyncExecution;
import org.sonar.ce.cleaning.CeCleaningModule;
import org.sonar.ce.db.ReadOnlyPropertiesDao;
import org.sonar.ce.issue.index.NoAsyncIssueIndexing;
import org.sonar.ce.logging.CeProcessLogging;
import org.sonar.ce.monitoring.CEQueueStatusImpl;
import org.sonar.ce.platform.CECoreExtensionsInstaller;
import org.sonar.ce.platform.ComputeEngineExtensionInstaller;
import org.sonar.ce.platform.DatabaseCompatibility;
import org.sonar.ce.queue.PurgeCeActivities;
import org.sonar.ce.task.projectanalysis.ProjectAnalysisTaskModule;
import org.sonar.ce.task.projectanalysis.analysis.ProjectConfigurationFactory;
import org.sonar.ce.task.projectanalysis.issue.AdHocRuleCreator;
import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationModule;
import org.sonar.ce.task.projectanalysis.taskprocessor.AuditPurgeTaskModule;
import org.sonar.ce.task.projectanalysis.taskprocessor.IssueSyncTaskModule;
import org.sonar.ce.taskprocessor.CeProcessingScheduler;
import org.sonar.ce.taskprocessor.CeTaskProcessorModule;
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.documentation.DefaultDocumentationLinkGenerator;
import org.sonar.core.extension.CoreExtensionRepositoryImpl;
import org.sonar.core.extension.CoreExtensionsLoader;
import org.sonar.core.language.LanguagesProvider;
import org.sonar.core.platform.Container;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginClassloaderFactory;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DBSessionsImpl;
import org.sonar.db.DaoModule;
import org.sonar.db.DbClient;
import org.sonar.db.DefaultDatabase;
import org.sonar.db.MyBatis;
import org.sonar.db.StartMyBatis;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.process.NetworkUtilsImpl;
import org.sonar.process.Props;
import org.sonar.process.logging.LogbackHelper;
import org.sonar.server.component.index.EntityDefinitionIndexer;
import org.sonar.server.config.ConfigurationProvider;
import org.sonar.server.es.EsModule;
import org.sonar.server.es.IndexersImpl;
import org.sonar.server.extension.CoreExtensionBootstraper;
import org.sonar.server.extension.CoreExtensionStopper;
import org.sonar.server.favorite.FavoriteUpdater;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.IssueStorage;
import org.sonar.server.issue.index.IssueIndexer;
import org.sonar.server.issue.index.IssueIteratorFactory;
import org.sonar.server.issue.notification.IssuesChangesNotificationModule;
import org.sonar.server.issue.notification.MyNewIssuesEmailTemplate;
import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler;
import org.sonar.server.issue.notification.NewIssuesEmailTemplate;
import org.sonar.server.issue.notification.NewIssuesNotificationHandler;
import org.sonar.server.issue.workflow.FunctionExecutor;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.l18n.ServerI18n;
import org.sonar.server.log.ServerLogging;
import org.sonar.server.measure.index.ProjectMeasuresIndexer;
import org.sonar.server.metric.MetricFinder;
import org.sonar.server.metric.UnanalyzedLanguageMetrics;
import org.sonar.server.notification.DefaultNotificationManager;
import org.sonar.server.notification.NotificationService;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.platform.DefaultNodeInformation;
import org.sonar.server.platform.OfficialDistribution;
import org.sonar.server.platform.ServerFileSystemImpl;
import org.sonar.server.platform.ServerImpl;
import org.sonar.server.platform.ServerLifecycleNotifier;
import org.sonar.server.platform.StartupMetadataProvider;
import org.sonar.server.platform.TempFolderProvider;
import org.sonar.server.platform.UrlSettings;
import org.sonar.server.platform.db.migration.MigrationConfigurationModule;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import org.sonar.server.platform.monitoring.DbSection;
import org.sonar.server.platform.monitoring.cluster.ProcessInfoProvider;
import org.sonar.server.platform.serverid.JdbcUrlSanitizer;
import org.sonar.server.platform.serverid.ServerIdChecksum;
import org.sonar.server.plugins.InstalledPluginReferentialFactory;
import org.sonar.server.plugins.ServerExtensionInstaller;
import org.sonar.server.project.DefaultBranchNameResolver;
import org.sonar.server.property.InternalPropertiesImpl;
import org.sonar.server.qualitygate.QualityGateEvaluatorImpl;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonar.server.qualitygate.notification.QGChangeEmailTemplate;
import org.sonar.server.qualitygate.notification.QGChangeNotificationHandler;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.DefaultRuleFinder;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.setting.DatabaseSettingLoader;
import org.sonar.server.setting.DatabaseSettingsEnabler;
import org.sonar.server.setting.ThreadLocalSettings;
import org.sonar.server.util.OkHttpClientProvider;
import org.sonar.server.util.Paths2Impl;
import org.sonar.server.view.index.ViewIndex;
import org.sonar.server.view.index.ViewIndexer;
import org.sonar.server.webhook.WebhookModule;
import org.sonarqube.ws.Rules;
import static java.util.Objects.requireNonNull;
import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter;
import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel;
import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel4OrNone;
import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED;
public class ComputeEngineContainerImpl implements ComputeEngineContainer {
private ComputeEngineStatus computeEngineStatus = null;
@CheckForNull
private SpringComponentContainer level1 = null;
@CheckForNull
private SpringComponentContainer level4 = null;
@Override
public void setComputeEngineStatus(ComputeEngineStatus computeEngineStatus) {
this.computeEngineStatus = computeEngineStatus;
}
@Override
public ComputeEngineContainer start(Props props) {
this.level1 = new SpringComponentContainer();
populateLevel1(this.level1, props, requireNonNull(computeEngineStatus));
startLevel1(this.level1);
SpringComponentContainer level2 = this.level1.createChild();
populateLevel2(level2);
startLevel2(level2);
SpringComponentContainer level3 = level2.createChild();
populateLevel3(level3);
startLevel3(level3);
this.level4 = level3.createChild();
populateLevel4(this.level4, props);
startLevel4(this.level4);
startupTasks();
return this;
}
private static void startLevel1(SpringComponentContainer level1) {
level1.startComponents();
level1.getComponentByType(CoreExtensionsLoader.class)
.load();
level1.getComponentByType(CECoreExtensionsInstaller.class)
.install(level1, hasPlatformLevel(1), noAdditionalSideFilter());
}
private static void startLevel2(SpringComponentContainer level2) {
level2.getParent().getComponentByType(CECoreExtensionsInstaller.class)
.install(level2, hasPlatformLevel(2), noAdditionalSideFilter());
level2.startComponents();
}
private static void startLevel3(SpringComponentContainer level3) {
level3.getParent().getComponentByType(CECoreExtensionsInstaller.class)
.install(level3, hasPlatformLevel(3), noAdditionalSideFilter());
level3.startComponents();
}
private static void startLevel4(SpringComponentContainer level4) {
level4.getParent().getComponentByType(CECoreExtensionsInstaller.class)
.install(level4, hasPlatformLevel4OrNone(), noAdditionalSideFilter());
level4.getParent().getComponentByType(ServerExtensionInstaller.class)
.installExtensions(level4);
level4.startComponents();
PlatformEditionProvider editionProvider = level4.getComponentByType(PlatformEditionProvider.class);
LoggerFactory.getLogger(ComputeEngineContainerImpl.class)
.info("Running {} edition", editionProvider.get().map(EditionProvider.Edition::getLabel).orElse(""));
}
private void startupTasks() {
SpringComponentContainer startupLevel = this.level4.createChild();
startupLevel.add(startupComponents());
startupLevel.startComponents();
// done in PlatformLevelStartup
ServerLifecycleNotifier serverLifecycleNotifier = startupLevel.getComponentByType(ServerLifecycleNotifier.class);
if (serverLifecycleNotifier != null) {
serverLifecycleNotifier.notifyStart();
}
startupLevel.stopComponents();
}
@Override
public ComputeEngineContainer stopWorkers() {
if (level4 != null) {
// try to graceful stop in-progress tasks
CeProcessingScheduler ceProcessingScheduler = level4.getComponentByType(CeProcessingScheduler.class);
ceProcessingScheduler.gracefulStopScheduling();
}
return this;
}
@Override
public ComputeEngineContainer stop() {
if (level4 != null) {
// try to graceful but quick stop in-progress tasks
CeProcessingScheduler ceProcessingScheduler = level4.getComponentByType(CeProcessingScheduler.class);
ceProcessingScheduler.hardStopScheduling();
}
this.level1.stopComponents();
return this;
}
@VisibleForTesting
protected SpringComponentContainer getComponentContainer() {
return level4;
}
private static void populateLevel1(Container container, Props props, ComputeEngineStatus computeEngineStatus) {
Version apiVersion = MetadataLoader.loadApiVersion(System2.INSTANCE);
Version sqVersion = MetadataLoader.loadSQVersion(System2.INSTANCE);
SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE);
container.add(
props.rawProperties(),
ThreadLocalSettings.class,
new ConfigurationProvider(),
new SonarQubeVersion(sqVersion),
SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.COMPUTE_ENGINE, edition),
CeProcessLogging.class,
UuidFactoryImpl.INSTANCE,
NetworkUtilsImpl.INSTANCE,
DefaultNodeInformation.class,
LogbackHelper.class,
DefaultDatabase.class,
MyBatis.class,
StartMyBatis.class,
PurgeProfiler.class,
ServerFileSystemImpl.class,
new TempFolderProvider(),
System2.INSTANCE,
Paths2Impl.getInstance(),
Clock.systemDefaultZone(),
// DB
new DaoModule(),
ReadOnlyPropertiesDao.class,
DBSessionsImpl.class,
DbClient.class,
// Elasticsearch
new EsModule(),
// rules/qprofiles
RuleIndex.class,
new OkHttpClientProvider(),
computeEngineStatus,
NoOpAuditPersister.class,
CoreExtensionRepositoryImpl.class,
CoreExtensionsLoader.class,
CECoreExtensionsInstaller.class);
container.add(toArray(CorePropertyDefinitions.all()));
}
private static void populateLevel2(Container container) {
container.add(
new MigrationConfigurationModule(),
DatabaseVersion.class,
DatabaseCompatibility.class,
DatabaseSettingLoader.class,
DatabaseSettingsEnabler.class,
UrlSettings.class,
// add ReadOnlyPropertiesDao at level2 again so that it shadows PropertiesDao
ReadOnlyPropertiesDao.class,
// plugins
PluginClassloaderFactory.class,
CePluginJarExploder.class,
PluginClassLoader.class,
CePluginRepository.class,
InstalledPluginReferentialFactory.class,
ComputeEngineExtensionInstaller.class,
// depends on plugins
ServerI18n.class, // used by RuleI18nManager
Durations.class // used in Web Services and DebtCalculator
);
}
private static void populateLevel3(Container container) {
container.add(
new StartupMetadataProvider(),
JdbcUrlSanitizer.class,
ServerIdChecksum.class,
UriReader.class,
ServerImpl.class,
SynchronousAsyncExecution.class);
}
private static void populateLevel4(Container container, Props props) {
container.add(
RuleDescriptionFormatter.class,
ResourceTypes.class,
DefaultResourceTypes.get(),
// quality profile
ActiveRuleIndexer.class,
XMLProfileParser.class,
XMLProfileSerializer.class,
BuiltInQualityProfileAnnotationLoader.class,
Rules.QProfiles.class,
// rule
AnnotationRuleParser.class,
DefaultRuleFinder.class,
RulesDefinitionXmlLoader.class,
AdHocRuleCreator.class,
RuleIndexer.class,
// languages
// used by CommonRuleDefinitionsImpl
LanguagesProvider.class,
// measure
MetricFinder.class,
UnanalyzedLanguageMetrics.class,
// components,
FavoriteUpdater.class,
IndexersImpl.class,
QGChangeNotificationHandler.class,
QGChangeNotificationHandler.newMetadata(),
ProjectMeasuresIndexer.class,
EntityDefinitionIndexer.class,
// views
ViewIndexer.class,
ViewIndex.class,
// issues
IssueStorage.class,
NoAsyncIssueIndexing.class,
IssueIndexer.class,
IssueIteratorFactory.class,
IssueFieldsSetter.class, // used in Web Services and CE's DebtCalculator
FunctionExecutor.class, // used by IssueWorkflow
IssueWorkflow.class, // used in Web Services and CE's DebtCalculator
NewIssuesEmailTemplate.class,
MyNewIssuesEmailTemplate.class,
NewIssuesNotificationHandler.class,
NewIssuesNotificationHandler.newMetadata(),
MyNewIssuesNotificationHandler.class,
MyNewIssuesNotificationHandler.newMetadata(),
new IssuesChangesNotificationModule(),
// Notifications
QGChangeEmailTemplate.class,
EmailSettings.class,
NotificationService.class,
DefaultNotificationManager.class,
EmailNotificationChannel.class,
new ReportAnalysisFailureNotificationModule(),
// System
ServerLogging.class,
CEQueueStatusImpl.class,
// SonarSource editions
PlatformEditionProvider.class,
// privileged plugins
CoreExtensionBootstraper.class,
CoreExtensionStopper.class,
// Compute engine (must be after Views and Developer Cockpit)
new CeConfigurationModule(),
new CeQueueModule(),
new CeHttpModule(),
new CeTaskCommonsModule(),
new ProjectAnalysisTaskModule(),
new IssueSyncTaskModule(),
new AuditPurgeTaskModule(),
new CeTaskProcessorModule(),
OfficialDistribution.class,
InternalPropertiesImpl.class,
ProjectConfigurationFactory.class,
DefaultBranchNameResolver.class,
// webhooks
new WebhookModule(),
QualityGateFinder.class,
QualityGateEvaluatorImpl.class,
new AnalysisCacheCleaningModule(),
DefaultDocumentationLinkGenerator.class
);
if (props.valueAsBoolean(CLUSTER_ENABLED.getKey())) {
container.add(
new CeCleaningModule(),
// system health
CeDistributedInformationImpl.class,
// system info
DbSection.class,
ProcessInfoProvider.class);
} else {
container.add(
new CeCleaningModule(),
StandaloneCeDistributedInformation.class);
}
}
private static Object[] startupComponents() {
return new Object[] {
ServerLifecycleNotifier.class,
PurgeCeActivities.class
};
}
private static Object[] toArray(List<?> list) {
return list.toArray(new Object[list.size()]);
}
}
| 18,018 | 36.229339 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineStatus.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.ce.container;
/**
* Status of the Compute Engine local node, but not of cluster of Compute Engine nodes.
*/
public interface ComputeEngineStatus {
/**
* This status will be consumed by multiple processes, hence the implementation of the method must be threadsafe
*/
Status getStatus();
enum Status {
INIT, STARTING, STARTED, STOPPING_WORKERS, WORKERS_STOPPED, STOPPING, STOPPED
}
}
| 1,266 | 34.194444 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/container/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.ce.container;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 39.125 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/db/ReadOnlyPropertiesDao.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.ce.db;
import javax.annotation.Nullable;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
/**
* Compute Engine specific override of {@link PropertiesDao} and {@link org.sonar.db.property.PropertiesDao} which
* implements no write method (ie. insert/update/delete) because updating the Properties is the Web Server responsibility
* alone.
* <p>
* This ugly trick is required because licensed plugin bundle {@link com.sonarsource.license.api.internal.ServerLicenseVerifierImpl}
* which update license properties by calling {@link PropertiesDao} directly and this can not be disabled.
* </p>
*/
public class ReadOnlyPropertiesDao extends PropertiesDao {
public ReadOnlyPropertiesDao(MyBatis mybatis, System2 system2, UuidFactory uuidFactory) {
super(mybatis, system2, uuidFactory, new NoOpAuditPersister());
}
@Override
public void saveProperty(DbSession session, PropertyDto property, @Nullable String userLogin,
@Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) {
// do nothing
}
@Override
public void saveProperty(PropertyDto property) {
// do nothing
}
@Override
public void deleteProjectProperty(DbSession session, String key, String projectUuid, String projectKey,
String projectName, String qualifier) {
// do nothing
}
@Override
public void deleteGlobalProperty(String key, DbSession session) {
// do nothing
}
@Override
public void renamePropertyKey(String oldKey, String newKey) {
// do nothing
}
}
| 2,605 | 34.69863 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/db/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.ce.db;
import javax.annotation.ParametersAreNonnullByDefault;
| 955 | 38.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/httpd/CeHttpServer.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.ce.httpd;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.Properties;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.http.impl.bootstrap.ServerBootstrap;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.slf4j.LoggerFactory;
import org.sonar.api.Startable;
import org.sonar.process.sharedmemoryfile.DefaultProcessCommands;
import static java.lang.Integer.parseInt;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH;
/**
* This HTTP server exports data required for display of System Info page (and the related web service).
* It listens on loopback address only, so it does not need to be secure (no HTTPS, no authentication).
*/
public class CeHttpServer implements Startable {
private final Properties processProps;
private final List<HttpAction> actions;
private HttpServer httpServer;
public CeHttpServer(Properties processProps, List<HttpAction> actions) {
this.processProps = processProps;
this.actions = actions;
}
@Override
public void start() {
try {
this.httpServer = buildHttpServer();
httpServer.start();
registerServerUrl();
} catch (IOException e) {
throw new IllegalStateException("Can not start local HTTP server for System Info monitoring", e);
}
}
private HttpServer buildHttpServer() {
ServerBootstrap serverBootstrap = ServerBootstrap.bootstrap();
serverBootstrap.setLocalAddress(InetAddress.getLoopbackAddress());
actions.forEach(httpAction -> serverBootstrap.registerHandler(httpAction.getContextPath(), httpAction));
serverBootstrap.registerHandler("/*", new NotFoundHttpRequestHandler());
return serverBootstrap.create();
}
private void registerServerUrl() {
int processNumber = parseInt(processProps.getProperty(PROPERTY_PROCESS_INDEX));
File shareDir = new File(processProps.getProperty(PROPERTY_SHARED_PATH));
try (DefaultProcessCommands commands = DefaultProcessCommands.secondary(shareDir, processNumber)) {
String url = getUrl();
commands.setHttpUrl(url);
LoggerFactory.getLogger(getClass()).debug("System Info HTTP server listening at {}", url);
}
}
@Override
public void stop() {
this.httpServer.stop();
}
// visible for testing
String getUrl() {
return "http://" + this.httpServer.getInetAddress().getHostAddress() + ":" + this.httpServer.getLocalPort();
}
private static class NotFoundHttpRequestHandler implements HttpRequestHandler {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) {
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND);
}
}
}
| 3,869 | 36.572816 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/httpd/HttpAction.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.ce.httpd;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
/**
* A Http action of the CE's HTTP server handles a request for a specified path.
*/
public interface HttpAction extends HttpRequestHandler {
/**
* Provides a context path to be registered on.
* It must not be empty and start with a '/'.
* @return the context path as a String
*/
String getContextPath();
void handle(HttpRequest request, HttpResponse response);
default void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException {
try {
this.handle(request, response);
// catch Throwable because we want to respond a clean 500 to client even on Error
} catch (Throwable t) {
throw new HttpException(t.getMessage(), t);
}
}
}
| 1,807 | 34.45098 | 87 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/httpd/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.ce.httpd;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 38.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/issue/index/NoAsyncIssueIndexing.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.ce.issue.index;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.server.issue.index.AsyncIssueIndexing;
@ComputeEngineSide
public class NoAsyncIssueIndexing implements AsyncIssueIndexing {
@Override
public void triggerOnIndexCreation() {
throw new IllegalStateException("Async issue indexing should not be triggered in Compute Engine");
}
@Override
public void triggerForProject(String projectUuid) {
throw new IllegalStateException("Async issue indexing should not be triggered in Compute Engine");
}
}
| 1,399 | 36.837838 | 102 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/issue/index/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.ce.issue.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/logging/CeProcessLogging.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.ce.logging;
import ch.qos.logback.classic.Level;
import org.sonar.process.ProcessId;
import org.sonar.process.logging.LogDomain;
import org.sonar.process.logging.LogLevelConfig;
import org.sonar.server.log.ServerProcessLogging;
import static org.sonar.ce.task.log.CeTaskLogging.MDC_CE_TASK_UUID;
/**
* Configure logback for the Compute Engine process. Logs are written to file "ce.log" in SQ's log directory.
*/
public class CeProcessLogging extends ServerProcessLogging {
public CeProcessLogging() {
super(ProcessId.COMPUTE_ENGINE, "%X{" + MDC_CE_TASK_UUID + "}");
}
@Override
protected void extendLogLevelConfiguration(LogLevelConfig.Builder logLevelConfigBuilder) {
logLevelConfigBuilder.levelByDomain("sql", ProcessId.COMPUTE_ENGINE, LogDomain.SQL);
logLevelConfigBuilder.levelByDomain("es", ProcessId.COMPUTE_ENGINE, LogDomain.ES);
JMX_RMI_LOGGER_NAMES.forEach(loggerName -> logLevelConfigBuilder.levelByDomain(loggerName, ProcessId.COMPUTE_ENGINE, LogDomain.JMX));
LOGGER_NAMES_TO_TURN_OFF.forEach(loggerName -> logLevelConfigBuilder.immutableLevel(loggerName, Level.OFF));
}
@Override
protected void extendConfigure() {
// nothing to do
}
}
| 2,057 | 38.576923 | 137 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/logging/ChangeLogLevelHttpAction.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.ce.logging;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.sonar.api.utils.log.LoggerLevel;
import org.slf4j.LoggerFactory;
import org.sonar.ce.httpd.HttpAction;
import org.sonar.server.log.ServerLogging;
import static java.lang.String.format;
public class ChangeLogLevelHttpAction implements HttpAction {
private static final String PATH = "/changeLogLevel";
private static final String PARAM_LEVEL = "level";
private final ServerLogging logging;
public ChangeLogLevelHttpAction(ServerLogging logging) {
this.logging = logging;
}
@Override
public String getContextPath() {
return PATH;
}
@Override
public void handle(HttpRequest request, HttpResponse response) {
if (!"POST".equals(request.getRequestLine().getMethod())) {
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_METHOD_NOT_ALLOWED);
return;
}
HttpEntityEnclosingRequest postRequest = (HttpEntityEnclosingRequest) request;
final URI requestUri;
try {
requestUri = new URI(postRequest.getRequestLine().getUri());
} catch (URISyntaxException e) {
throw new IllegalStateException("the request URI can't be syntactically invalid", e);
}
List<NameValuePair> requestParams = URLEncodedUtils.parse(requestUri, StandardCharsets.UTF_8);
Optional<String> levelRequested = requestParams.stream()
.filter(nvp -> PARAM_LEVEL.equals(nvp.getName()))
.map(NameValuePair::getValue)
.findFirst();
final String levelStr;
if (levelRequested.isEmpty()) {
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST);
response.setEntity(new StringEntity(format("Parameter '%s' is missing", PARAM_LEVEL), StandardCharsets.UTF_8));
return;
} else {
levelStr = levelRequested.get();
}
try {
LoggerLevel level = LoggerLevel.valueOf(levelStr);
logging.changeLevel(level);
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
} catch (IllegalArgumentException e) {
LoggerFactory.getLogger(ChangeLogLevelHttpAction.class).debug("Value '{}' for parameter '" + PARAM_LEVEL + "' is invalid: {}", levelStr, e);
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST);
response.setEntity(
new StringEntity(format("Value '%s' for parameter '%s' is invalid", levelStr, PARAM_LEVEL), StandardCharsets.UTF_8));
}
}
}
| 3,707 | 36.08 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/logging/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.ce.logging;
import javax.annotation.ParametersAreNonnullByDefault;
| 960 | 39.041667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CEQueueStatus.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.ce.monitoring;
import java.util.Optional;
import org.sonar.api.ce.ComputeEngineSide;
@ComputeEngineSide
public interface CEQueueStatus {
/**
* Adds 1 to the count of batch reports under processing and removes 1 from the count of batch reports waiting for
* processing.
*
* @return the new count of batch reports under processing
*
* @see #getInProgressCount()
*/
long addInProgress();
/**
* Adds 1 to the count of batch reports which processing ended successfully and removes 1 from the count of batch
* reports under processing. Adds the specified time to the processing time counter.
*
* @param processingTime duration of processing in ms
*
* @return the new count of batch reports which processing ended successfully
*
* @see #getSuccessCount()
* @see #getInProgressCount()
*
* @throws IllegalArgumentException if processingTime is < 0
*/
long addSuccess(long processingTime);
/**
* Adds 1 to the count of tasks which processing ended with an error and removes 1 from the count of tasks
* under processing. Adds the specified time to the processing time counter.
*
* @param processingTime duration of processing in ms
*
* @return the new count of tasks which processing ended with an error
*
* @see #getErrorCount()
* @see #getInProgressCount()
*
* @throws IllegalArgumentException if processingTime is < 0
*/
long addError(long processingTime);
/**
* Number of pending tasks, including tasks received before instance startup.
*/
long getPendingCount();
/**
* The age, in ms, of the oldest pending task.
*/
Optional<Long> getLongestTimePending();
/**
* Count of tasks under processing.
*/
long getInProgressCount();
/**
* Count of tasks which processing ended with an error since instance startup.
*/
long getErrorCount();
/**
* Count of tasks which processing ended successfully since instance startup.
*/
long getSuccessCount();
/**
* Time spent processing tasks since startup, in milliseconds.
*/
long getProcessingTime();
boolean areWorkersPaused();
}
| 2,999 | 29 | 116 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CEQueueStatusImpl.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.ce.monitoring;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.server.property.InternalProperties;
import static com.google.common.base.Preconditions.checkArgument;
public class CEQueueStatusImpl implements CEQueueStatus {
private final DbClient dbClient;
private final System2 system;
private final AtomicLong inProgress = new AtomicLong(0);
private final AtomicLong error = new AtomicLong(0);
private final AtomicLong success = new AtomicLong(0);
private final AtomicLong processingTime = new AtomicLong(0);
public CEQueueStatusImpl(DbClient dbClient, System2 system) {
this.dbClient = dbClient;
this.system = system;
}
@Override
public long addInProgress() {
return inProgress.incrementAndGet();
}
@Override
public long addError(long processingTimeInMs) {
addProcessingTime(processingTimeInMs);
inProgress.decrementAndGet();
return error.incrementAndGet();
}
@Override
public long addSuccess(long processingTimeInMs) {
addProcessingTime(processingTimeInMs);
inProgress.decrementAndGet();
return success.incrementAndGet();
}
private void addProcessingTime(long ms) {
checkArgument(ms >= 0, "Processing time can not be < 0");
processingTime.addAndGet(ms);
}
@Override
public long getPendingCount() {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.PENDING);
}
}
@Override
public Optional<Long> getLongestTimePending() {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.ceQueueDao().selectCreationDateOfOldestPendingByEntityUuid(dbSession, null)
.map(creationDate -> system.now() - creationDate);
}
}
@Override
public boolean areWorkersPaused() {
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<String> val = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.COMPUTE_ENGINE_PAUSE);
return "true".equals(val.orElse(null));
}
}
@Override
public long getInProgressCount() {
return inProgress.get();
}
@Override
public long getErrorCount() {
return error.get();
}
@Override
public long getSuccessCount() {
return success.get();
}
@Override
public long getProcessingTime() {
return processingTime.get();
}
}
| 3,402 | 29.115044 | 126 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CeDatabaseMBean.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.ce.monitoring;
public interface CeDatabaseMBean {
int getPoolActiveConnections();
int getPoolMaxConnections();
int getPoolTotalConnections();
int getPoolIdleConnections();
int getPoolMinIdleConnections();
long getPoolMaxLifeTimeMillis();
long getPoolMaxWaitMillis();
}
| 1,153 | 28.589744 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CeDatabaseMBeanImpl.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.ce.monitoring;
import org.sonar.db.DatabaseMBean;
import org.sonar.db.DbClient;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
public class CeDatabaseMBeanImpl extends DatabaseMBean implements CeDatabaseMBean {
private static final String OBJECT_NAME = "ComputeEngineDatabaseConnection";
public CeDatabaseMBeanImpl(DbClient dbClient) {
super(dbClient);
}
@Override
protected String name() {
return OBJECT_NAME;
}
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder builder = ProtobufSystemInfo.Section.newBuilder();
builder.setName("Compute Engine Database Connection");
builder.addAttributesBuilder().setKey("Pool Total Connections").setLongValue(getPoolTotalConnections()).build();
builder.addAttributesBuilder().setKey("Pool Active Connections").setLongValue(getPoolActiveConnections()).build();
builder.addAttributesBuilder().setKey("Pool Idle Connections").setLongValue(getPoolIdleConnections()).build();
builder.addAttributesBuilder().setKey("Pool Max Connections").setLongValue(getPoolMaxConnections()).build();
builder.addAttributesBuilder().setKey("Pool Min Idle Connections").setLongValue(getPoolMinIdleConnections()).build();
builder.addAttributesBuilder().setKey("Pool Max Wait (ms)").setLongValue(getPoolMaxWaitMillis()).build();
builder.addAttributesBuilder().setKey("Pool Max Lifetime (ms)").setLongValue(getPoolMaxLifeTimeMillis()).build();
return builder.build();
}
}
| 2,378 | 43.886792 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CeTasksMBean.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.ce.monitoring;
import java.util.List;
public interface CeTasksMBean {
String OBJECT_NAME = "SonarQube:name=ComputeEngineTasks";
/**
* Number of pending tasks, including tasks received before instance startup.
*/
long getPendingCount();
/**
* The age, in ms, of the oldest pending task.
*/
long getLongestTimePending();
/**
* Count of tasks under processing.
*/
long getInProgressCount();
/**
* Count of tasks which processing ended with an error since instance startup.
*/
long getErrorCount();
/**
* Count of tasks which processing ended successfully since instance startup.
*/
long getSuccessCount();
/**
* Time spent processing tasks since startup, in milliseconds.
*/
long getProcessingTime();
/**
* Configured maximum number of workers.
*/
int getWorkerMaxCount();
/**
* Configured number of Workers.
*/
int getWorkerCount();
List<String> getWorkerUuids();
List<String> getEnabledWorkerUuids();
}
| 1,862 | 24.875 | 80 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/CeTasksMBeanImpl.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.ce.monitoring;
import java.util.List;
import java.util.Set;
import org.sonar.api.Startable;
import org.sonar.ce.configuration.CeConfiguration;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerController;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import org.sonar.process.Jmx;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
public class CeTasksMBeanImpl implements CeTasksMBean, Startable, SystemInfoSection {
private final CEQueueStatus queueStatus;
private final CeConfiguration ceConfiguration;
private final CeWorkerFactory ceWorkerFactory;
private final CeWorkerController ceWorkerController;
public CeTasksMBeanImpl(CEQueueStatus queueStatus, CeConfiguration ceConfiguration, CeWorkerFactory ceWorkerFactory, CeWorkerController CeWorkerController) {
this.queueStatus = queueStatus;
this.ceConfiguration = ceConfiguration;
this.ceWorkerFactory = ceWorkerFactory;
this.ceWorkerController = CeWorkerController;
}
@Override
public void start() {
Jmx.register(OBJECT_NAME, this);
}
/**
* Unregister, if needed
*/
@Override
public void stop() {
Jmx.unregister(OBJECT_NAME);
}
@Override
public long getPendingCount() {
return queueStatus.getPendingCount();
}
@Override
public long getLongestTimePending() {
return queueStatus.getLongestTimePending().orElse(0L);
}
@Override
public long getInProgressCount() {
return queueStatus.getInProgressCount();
}
@Override
public long getErrorCount() {
return queueStatus.getErrorCount();
}
@Override
public long getSuccessCount() {
return queueStatus.getSuccessCount();
}
@Override
public long getProcessingTime() {
return queueStatus.getProcessingTime();
}
@Override
public int getWorkerMaxCount() {
return ceConfiguration.getWorkerMaxCount();
}
@Override
public int getWorkerCount() {
return ceConfiguration.getWorkerCount();
}
@Override
public List<String> getWorkerUuids() {
Set<CeWorker> workers = ceWorkerFactory.getWorkers();
return workers.stream()
.map(CeWorker::getUUID)
.sorted()
.toList();
}
@Override
public List<String> getEnabledWorkerUuids() {
Set<CeWorker> workers = ceWorkerFactory.getWorkers();
return workers.stream()
.filter(ceWorkerController::isEnabled)
.map(CeWorker::getUUID)
.sorted()
.toList();
}
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder builder = ProtobufSystemInfo.Section.newBuilder();
builder.setName("Compute Engine Tasks");
builder.addAttributesBuilder().setKey("Pending").setLongValue(getPendingCount()).build();
builder.addAttributesBuilder().setKey("Longest Time Pending (ms)").setLongValue(getLongestTimePending()).build();
builder.addAttributesBuilder().setKey("In Progress").setLongValue(getInProgressCount()).build();
builder.addAttributesBuilder().setKey("Processed With Error").setLongValue(getErrorCount()).build();
builder.addAttributesBuilder().setKey("Processed With Success").setLongValue(getSuccessCount()).build();
builder.addAttributesBuilder().setKey("Processing Time (ms)").setLongValue(getProcessingTime()).build();
builder.addAttributesBuilder().setKey("Worker Count").setLongValue(getWorkerCount()).build();
builder.addAttributesBuilder().setKey("Max Worker Count").setLongValue(getWorkerMaxCount()).build();
builder.addAttributesBuilder().setKey("Workers Paused").setBooleanValue(queueStatus.areWorkersPaused()).build();
return builder.build();
}
}
| 4,552 | 32.977612 | 159 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/monitoring/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.ce.monitoring;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListener.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.ce.notification;
import java.time.Duration;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotification;
import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationBuilder;
import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationSerializer;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.RowNotFoundException;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.notification.NotificationService;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Collections.singleton;
public class ReportAnalysisFailureNotificationExecutionListener implements CeWorker.ExecutionListener {
private final NotificationService notificationService;
private final DbClient dbClient;
private final ReportAnalysisFailureNotificationSerializer taskFailureNotificationSerializer;
private final System2 system2;
public ReportAnalysisFailureNotificationExecutionListener(NotificationService notificationService, DbClient dbClient,
ReportAnalysisFailureNotificationSerializer taskFailureNotificationSerializer, System2 system2) {
this.notificationService = notificationService;
this.dbClient = dbClient;
this.taskFailureNotificationSerializer = taskFailureNotificationSerializer;
this.system2 = system2;
}
@Override
public void onStart(CeTask ceTask) {
// nothing to do
}
@Override
public void onEnd(CeTask ceTask, CeActivityDto.Status status, Duration duration, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
if (status == CeActivityDto.Status.SUCCESS) {
return;
}
String branchUuid = ceTask.getComponent().map(CeTask.Component::getUuid).orElse(null);
if (!CeTaskTypes.REPORT.equals(ceTask.getType()) || branchUuid == null) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
BranchDto branchDto = dbClient.branchDao().selectByUuid(dbSession, branchUuid)
.orElseThrow(() -> new IllegalStateException("Could not find a branch with uuid %s".formatted(branchUuid)));
if (notificationService.hasProjectSubscribersForTypes(branchDto.getProjectUuid(), singleton(ReportAnalysisFailureNotification.class))) {
ProjectDto projectDto = dbClient.projectDao().selectByUuid(dbSession, branchDto.getProjectUuid())
.orElseThrow(() -> new IllegalStateException("Could not find project uuid %s".formatted(branchDto.getProjectUuid())));
checkQualifier(projectDto);
CeActivityDto ceActivityDto = dbClient.ceActivityDao().selectByUuid(dbSession, ceTask.getUuid())
.orElseThrow(() -> new RowNotFoundException(format("CeActivity with uuid '%s' not found", ceTask.getUuid())));
ReportAnalysisFailureNotificationBuilder taskFailureNotification = buildNotification(ceActivityDto, projectDto, branchDto, error);
ReportAnalysisFailureNotification notification = taskFailureNotificationSerializer.toNotification(taskFailureNotification);
notificationService.deliverEmails(singleton(notification));
// compatibility with old API
notificationService.deliver(notification);
}
}
}
/**
* @throws IllegalArgumentException if specified {@link ComponentDto} is not a project.
*/
private static void checkQualifier(ProjectDto projectDto) {
String qualifier = projectDto.getQualifier();
checkArgument(qualifier.equals(Qualifiers.PROJECT), "Component %s must be a project (qualifier=%s)", projectDto.getUuid(), qualifier);
}
private ReportAnalysisFailureNotificationBuilder buildNotification(CeActivityDto ceActivityDto, ProjectDto projectDto, BranchDto branchDto,
@Nullable Throwable error) {
String projectBranch = branchDto.isMain() ? null : branchDto.getBranchKey();
Long executedAt = ceActivityDto.getExecutedAt();
return new ReportAnalysisFailureNotificationBuilder(
new ReportAnalysisFailureNotificationBuilder.Project(
projectDto.getUuid(),
projectDto.getKey(),
projectDto.getName(),
projectBranch),
new ReportAnalysisFailureNotificationBuilder.Task(
ceActivityDto.getUuid(),
ceActivityDto.getSubmittedAt(),
executedAt == null ? system2.now() : executedAt),
error == null ? null : error.getMessage());
}
}
| 5,665 | 46.216667 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/notification/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.ce.notification;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 39.25 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/platform/CECoreExtensionsInstaller.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.ce.platform;
import org.sonar.api.SonarRuntime;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.extension.CoreExtensionsInstaller;
@ComputeEngineSide
public class CECoreExtensionsInstaller extends CoreExtensionsInstaller {
public CECoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository) {
super(sonarRuntime, coreExtensionRepository, ComputeEngineSide.class);
}
}
| 1,354 | 40.060606 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/platform/ComputeEngineExtensionInstaller.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.ce.platform;
import org.sonar.api.SonarRuntime;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.core.platform.PluginRepository;
import org.sonar.server.plugins.ServerExtensionInstaller;
import static java.util.Collections.singleton;
public class ComputeEngineExtensionInstaller extends ServerExtensionInstaller {
public ComputeEngineExtensionInstaller(Configuration configuration, SonarRuntime sonarRuntime, PluginRepository pluginRepository) {
super(configuration, sonarRuntime, pluginRepository, singleton(ComputeEngineSide.class));
}
}
| 1,467 | 39.777778 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/platform/DatabaseCompatibility.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.ce.platform;
import org.sonar.api.Startable;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.FRESH_INSTALL;
import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Status.UP_TO_DATE;
public class DatabaseCompatibility implements Startable {
private final DatabaseVersion version;
public DatabaseCompatibility(DatabaseVersion version) {
this.version = version;
}
@Override
public void start() {
DatabaseVersion.Status status = version.getStatus();
checkState(status == UP_TO_DATE || status == FRESH_INSTALL, "Compute Engine can't start unless Database is up to date");
}
@Override
public void stop() {
// do nothing
}
}
| 1,712 | 34.6875 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/platform/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.ce.platform;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 39.083333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/CeQueueInitializer.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.ce.queue;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.platform.Server;
import org.sonar.api.platform.ServerStartHandler;
import org.sonar.ce.cleaning.CeCleaningScheduler;
import org.sonar.ce.taskprocessor.CeProcessingScheduler;
import org.sonar.ce.CeDistributedInformation;
/**
* Cleans-up the queue, initializes JMX counters then schedule
* the execution of workers. That allows to not prevent workers
* from peeking the queue before it's ready.
*/
@ComputeEngineSide
public class CeQueueInitializer implements ServerStartHandler {
private final CeProcessingScheduler processingScheduler;
private final CeCleaningScheduler cleaningScheduler;
private final CeDistributedInformation ceDistributedInformation;
private boolean done = false;
public CeQueueInitializer(CeProcessingScheduler processingScheduler, CeCleaningScheduler cleaningScheduler,
CeDistributedInformation ceDistributedInformation) {
this.processingScheduler = processingScheduler;
this.cleaningScheduler = cleaningScheduler;
this.ceDistributedInformation = ceDistributedInformation;
}
@Override
public void onServerStart(Server server) {
if (!done) {
initCe();
this.done = true;
}
}
private void initCe() {
ceDistributedInformation.broadcastWorkerUUIDs();
processingScheduler.startScheduling();
cleaningScheduler.startScheduling();
}
}
| 2,263 | 34.936508 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/InternalCeQueue.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.ce.queue;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.db.ce.CeActivityDto.Status;
/**
* Queue of pending Compute Engine tasks. Both producer and consumer actions
* are implemented.
* <p>
* This class is decoupled from the regular task type {@link org.sonar.db.ce.CeTaskTypes#REPORT}.
* </p>
*/
public interface InternalCeQueue extends CeQueue {
/**
* Peek the oldest task in status {@link org.sonar.db.ce.CeQueueDto.Status#PENDING}.
* The task status is changed to {@link org.sonar.db.ce.CeQueueDto.Status#IN_PROGRESS}.
* Does not return anything if workers are paused or being paused (see {@link #getWorkersPauseStatus()}.
*
* @param excludeIndexationJob change the underlying request to exclude indexation tasks.
*
* <p>Only a single task can be peeked by project.</p>
*
* <p>An unchecked exception may be thrown on technical errors (db connection, ...).</p>
*
* <p>Tasks which have been executed twice already but are still {@link org.sonar.db.ce.CeQueueDto.Status#PENDING}
* are ignored</p>
*/
Optional<CeTask> peek(String workerUuid, boolean excludeIndexationJob);
/**
* Removes a task from the queue and registers it to past activities. This method
* is called by Compute Engine workers when task is processed and can include an option {@link CeTaskResult} object.
*
* @throws IllegalStateException if the task does not exist in the queue
* @throws IllegalArgumentException if {@code error} is non {@code null} but {@code status} is not {@link Status#FAILED}
*/
void remove(CeTask task, Status status, @Nullable CeTaskResult taskResult, @Nullable Throwable error);
void cancelWornOuts();
void resetTasksWithUnknownWorkerUUIDs(Set<String> knownWorkerUUIDs);
}
| 2,737 | 39.865672 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/InternalCeQueueImpl.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.ce.queue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.utils.System2;
import org.sonar.ce.container.ComputeEngineStatus;
import org.sonar.ce.monitoring.CEQueueStatus;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.TypedException;
import org.sonar.ce.task.projectanalysis.component.VisitException;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeTaskCharacteristicDto;
import org.sonar.server.platform.NodeInformation;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
@ComputeEngineSide
public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue {
private static final Logger LOG = LoggerFactory.getLogger(InternalCeQueueImpl.class);
private final DbClient dbClient;
private final CEQueueStatus queueStatus;
private final ComputeEngineStatus computeEngineStatus;
private final NextPendingTaskPicker nextPendingTaskPicker;
public InternalCeQueueImpl(System2 system2, DbClient dbClient, UuidFactory uuidFactory, CEQueueStatus queueStatus,
ComputeEngineStatus computeEngineStatus, NextPendingTaskPicker nextPendingTaskPicker, NodeInformation nodeInformation) {
super(system2, dbClient, uuidFactory, nodeInformation);
this.dbClient = dbClient;
this.queueStatus = queueStatus;
this.computeEngineStatus = computeEngineStatus;
this.nextPendingTaskPicker = nextPendingTaskPicker;
}
@Override
public Optional<CeTask> peek(String workerUuid, boolean excludeIndexationJob) {
requireNonNull(workerUuid, "workerUuid can't be null");
if (computeEngineStatus.getStatus() != ComputeEngineStatus.Status.STARTED || getWorkersPauseStatus() != WorkersPauseStatus.RESUMED) {
return Optional.empty();
}
try (DbSession dbSession = dbClient.openSession(false)) {
resetNotPendingTasks(workerUuid, dbSession);
Optional<CeQueueDto> opt = nextPendingTaskPicker.findPendingTask(workerUuid, dbSession, excludeIndexationJob);
if (opt.isEmpty()) {
return Optional.empty();
}
CeQueueDto taskDto = opt.get();
Map<String, String> characteristics = dbClient.ceTaskCharacteristicsDao().selectByTaskUuids(dbSession, singletonList(taskDto.getUuid())).stream()
.collect(Collectors.toMap(CeTaskCharacteristicDto::getKey, CeTaskCharacteristicDto::getValue));
CeTask task = convertToTask(dbSession, taskDto, characteristics);
queueStatus.addInProgress();
return Optional.of(task);
}
}
private void resetNotPendingTasks(String workerUuid, DbSession dbSession) {
List<CeQueueDto> notPendingTasks = dbClient.ceQueueDao().selectNotPendingForWorker(dbSession, workerUuid);
if (!notPendingTasks.isEmpty()) {
for (CeQueueDto pendingTask : notPendingTasks) {
dbClient.ceQueueDao().resetToPendingByUuid(dbSession, pendingTask.getUuid());
}
dbSession.commit();
LOG.debug("{} in progress tasks reset for worker uuid {}", notPendingTasks.size(), workerUuid);
}
}
@Override
public void remove(CeTask task, CeActivityDto.Status status, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
checkArgument(error == null || status == CeActivityDto.Status.FAILED, "Error can be provided only when status is FAILED");
long executionTimeInMs = 0L;
try (DbSession dbSession = dbClient.openSession(false)) {
CeQueueDto queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, task.getUuid())
.orElseThrow(() -> new IllegalStateException("Task does not exist anymore: " + task));
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setNodeName(nodeInformation.getNodeName().orElse(null));
activityDto.setStatus(status);
executionTimeInMs = updateExecutionFields(activityDto);
updateTaskResult(activityDto, taskResult);
updateError(activityDto, error);
remove(dbSession, queueDto, activityDto);
} finally {
updateQueueStatus(status, executionTimeInMs);
}
}
private void updateQueueStatus(CeActivityDto.Status status, long executionTimeInMs) {
if (status == CeActivityDto.Status.SUCCESS) {
queueStatus.addSuccess(executionTimeInMs);
} else {
queueStatus.addError(executionTimeInMs);
}
}
private static void updateTaskResult(CeActivityDto activityDto, @Nullable CeTaskResult taskResult) {
if (taskResult != null) {
Optional<String> analysisUuid = taskResult.getAnalysisUuid();
analysisUuid.ifPresent(activityDto::setAnalysisUuid);
}
}
private static void updateError(CeActivityDto activityDto, @Nullable Throwable error) {
if (error == null) {
return;
}
if (error instanceof VisitException && error.getCause() != null) {
activityDto.setErrorMessage(format("%s (%s)", error.getCause().getMessage(), error.getMessage()));
} else {
activityDto.setErrorMessage(error.getMessage());
}
String stacktrace = getStackTraceForPersistence(error);
if (stacktrace != null) {
activityDto.setErrorStacktrace(stacktrace);
}
if (error instanceof TypedException typedException) {
activityDto.setErrorType(typedException.getType());
}
}
@CheckForNull
private static String getStackTraceForPersistence(Throwable error) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
LineReturnEnforcedPrintStream printStream = new LineReturnEnforcedPrintStream(out)) {
error.printStackTrace(printStream);
printStream.flush();
return out.toString();
} catch (IOException e) {
LOG.debug("Failed to getStacktrace out of error", e);
return null;
}
}
@Override
public void cancelWornOuts() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<CeQueueDto> wornOutTasks = dbClient.ceQueueDao().selectWornout(dbSession);
wornOutTasks.forEach(queueDto -> {
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setNodeName(nodeInformation.getNodeName().orElse(null));
activityDto.setStatus(CeActivityDto.Status.CANCELED);
updateExecutionFields(activityDto);
remove(dbSession, queueDto, activityDto);
});
}
}
@Override
public void resetTasksWithUnknownWorkerUUIDs(Set<String> knownWorkerUUIDs) {
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.ceQueueDao().resetTasksWithUnknownWorkerUUIDs(dbSession, knownWorkerUUIDs);
dbSession.commit();
}
}
/**
* A {@link PrintWriter} subclass which enforces that line returns are {@code \n} whichever the platform.
*/
private static class LineReturnEnforcedPrintStream extends PrintWriter {
LineReturnEnforcedPrintStream(OutputStream out) {
super(out);
}
@Override
public void println() {
super.print('\n');
}
@Override
public void println(boolean x) {
super.print(x);
println();
}
@Override
public void println(char x) {
super.print(x);
println();
}
@Override
public void println(int x) {
super.print(x);
println();
}
@Override
public void println(long x) {
super.print(x);
println();
}
@Override
public void println(float x) {
super.print(x);
println();
}
@Override
public void println(double x) {
super.print(x);
println();
}
@Override
public void println(char[] x) {
super.print(x);
println();
}
@Override
public void println(String x) {
super.print(x);
println();
}
@Override
public void println(Object x) {
super.print(x);
println();
}
}
}
| 9,241 | 33.614232 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.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.ce.queue;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang.ObjectUtils;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.config.ComputeEngineProperties;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeQueueDao;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeTaskDtoLight;
import org.sonar.db.ce.PrOrBranchTask;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY;
import static org.sonar.db.ce.CeTaskCharacteristicDto.PULL_REQUEST;
@ComputeEngineSide
public class NextPendingTaskPicker {
private static final Logger LOG = LoggerFactory.getLogger(NextPendingTaskPicker.class);
private final Configuration config;
private final CeQueueDao ceQueueDao;
public NextPendingTaskPicker(Configuration config, DbClient dbClient) {
this.config = config;
this.ceQueueDao = dbClient.ceQueueDao();
}
Optional<CeQueueDto> findPendingTask(String workerUuid, DbSession dbSession, boolean prioritizeAnalysisAndRefresh) {
// try to find tasks including indexation job & excluding app/portfolio and if no match, try the opposite
// when prioritizeAnalysisAndRefresh is false, search first excluding indexation jobs and including app/portfolio, then the opposite
Optional<CeTaskDtoLight> eligibleForPeek = ceQueueDao.selectEligibleForPeek(dbSession, prioritizeAnalysisAndRefresh, !prioritizeAnalysisAndRefresh);
Optional<CeTaskDtoLight> eligibleForPeekInParallel = eligibleForPeekInParallel(dbSession);
if (eligibleForPeek.isPresent() || eligibleForPeekInParallel.isPresent()) {
return submitOldest(dbSession, workerUuid, eligibleForPeek.orElse(null), eligibleForPeekInParallel.orElse(null));
}
eligibleForPeek = ceQueueDao.selectEligibleForPeek(dbSession, !prioritizeAnalysisAndRefresh, prioritizeAnalysisAndRefresh);
if (eligibleForPeek.isPresent()) {
return ceQueueDao.tryToPeek(dbSession, eligibleForPeek.get().getCeTaskUuid(), workerUuid);
}
return Optional.empty();
}
/**
* priority is always given to the task that is waiting longer - to avoid starvation
*/
private Optional<CeQueueDto> submitOldest(DbSession session, String workerUuid, @Nullable CeTaskDtoLight eligibleForPeek, @Nullable CeTaskDtoLight eligibleForPeekInParallel) {
CeTaskDtoLight oldest = (CeTaskDtoLight) ObjectUtils.min(eligibleForPeek, eligibleForPeekInParallel);
Optional<CeQueueDto> ceQueueDto = ceQueueDao.tryToPeek(session, oldest.getCeTaskUuid(), workerUuid);
if (!Objects.equals(oldest, eligibleForPeek)) {
ceQueueDto.ifPresent(t -> LOG.info("Task [uuid = " + t.getUuid() + "] will be run concurrently with other tasks for the same project"));
}
return ceQueueDto;
}
Optional<CeTaskDtoLight> eligibleForPeekInParallel(DbSession dbSession) {
Optional<Boolean> parallelProjectTasksEnabled = config.getBoolean(ComputeEngineProperties.CE_PARALLEL_PROJECT_TASKS_ENABLED);
if (parallelProjectTasksEnabled.isPresent() && Boolean.TRUE.equals(parallelProjectTasksEnabled.get())) {
return findPendingConcurrentCandidateTasks(ceQueueDao, dbSession);
}
return Optional.empty();
}
/**
* Some of the tasks of the same project (mostly PRs) can be assigned and executed on workers at the same time/concurrently.
* We look for them in this method.
*/
private static Optional<CeTaskDtoLight> findPendingConcurrentCandidateTasks(CeQueueDao ceQueueDao, DbSession session) {
List<PrOrBranchTask> queuedPrOrBranches = filterOldestPerProject(ceQueueDao.selectOldestPendingPrOrBranch(session));
List<PrOrBranchTask> inProgressTasks = ceQueueDao.selectInProgressWithCharacteristics(session);
for (PrOrBranchTask task : queuedPrOrBranches) {
if ((Objects.equals(task.getBranchType(), PULL_REQUEST) && canRunPr(task, inProgressTasks))
|| (Objects.equals(task.getBranchType(), BRANCH_KEY) && canRunBranch(task, inProgressTasks))) {
return Optional.of(task);
}
}
return Optional.empty();
}
private static List<PrOrBranchTask> filterOldestPerProject(List<PrOrBranchTask> queuedPrOrBranches) {
Set<String> entityUuidsSeen = new HashSet<>();
return queuedPrOrBranches.stream().filter(t -> entityUuidsSeen.add(t.getEntityUuid())).toList();
}
/**
* Branches cannot be run concurrently at this moment with other branches. And branches can already be returned in
* {@link CeQueueDao#selectEligibleForPeek(org.sonar.db.DbSession, boolean, boolean)}. But we need this method because branches can be
* assigned to a worker in a situation where the only type of in-progress tasks for a given project are {@link #PULLREQUEST_TYPE}.
* <p>
* This method returns the longest waiting branch in the queue which can be scheduled concurrently with pull requests.
*/
private static boolean canRunBranch(PrOrBranchTask task, List<PrOrBranchTask> inProgress) {
String entityUuid = task.getEntityUuid();
List<PrOrBranchTask> sameComponentTasks = inProgress.stream()
.filter(t -> t.getEntityUuid().equals(entityUuid))
.toList();
//we can peek branch analysis task only if all the other in progress tasks for this component uuid are pull requests
return sameComponentTasks.stream().map(PrOrBranchTask::getBranchType).allMatch(s -> Objects.equals(s, PULL_REQUEST));
}
/**
* Queued pull requests can almost always be assigned to worker unless there is already PR running with the same ID (text_value column)
* and for the same project. We look for the one that waits for the longest time.
*/
private static boolean canRunPr(PrOrBranchTask task, List<PrOrBranchTask> inProgress) {
// return true unless the same PR is already in progress
return inProgress.stream()
.noneMatch(pr -> pr.getEntityUuid().equals(task.getEntityUuid()) && Objects.equals(pr.getBranchType(), PULL_REQUEST) &&
Objects.equals(pr.getComponentUuid(), (task.getComponentUuid())));
}
}
| 7,061 | 48.732394 | 177 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/PurgeCeActivities.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.ce.queue;
import org.sonar.api.Startable;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.purge.PurgeProfiler;
@ComputeEngineSide
public class PurgeCeActivities implements Startable {
private final DbClient dbClient;
private final PurgeProfiler profiler;
public PurgeCeActivities(DbClient dbClient, PurgeProfiler profiler) {
this.dbClient = dbClient;
this.profiler = profiler;
}
@Override
public void start() {
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.purgeDao().purgeCeActivities(dbSession, profiler);
dbClient.purgeDao().purgeCeScannerContexts(dbSession, profiler);
dbSession.commit();
}
}
@Override
public void stop() {
// nothing to do
}
}
| 1,671 | 30.54717 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/queue/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.ce.queue;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 38.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/security/PluginCeRule.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.ce.security;
import java.security.Permission;
import java.security.SecurityPermission;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.sonar.process.PluginPolicyRule;
public class PluginCeRule implements PluginPolicyRule {
private static final Set<String> BLOCKED_RUNTIME_PERMISSIONS = new HashSet<>(Arrays.asList(
"createClassLoader",
"getClassLoader",
"setContextClassLoader",
"enableContextClassLoaderOverride",
"closeClassLoader",
"setSecurityManager",
"createSecurityManager"
));
private static final Set<String> BLOCKED_SECURITY_PERMISSIONS = new HashSet<>(Arrays.asList(
"createAccessControlContext",
"setPolicy"
));
@Override public boolean implies(Permission permission) {
if (permission instanceof RuntimePermission && BLOCKED_RUNTIME_PERMISSIONS.contains(permission.getName())) {
return false;
}
if (permission instanceof SecurityPermission && BLOCKED_SECURITY_PERMISSIONS.contains(permission.getName())) {
return false;
}
return true;
}
}
| 1,931 | 34.777778 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/security/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.ce.security;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 37.52 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/systeminfo/SystemInfoHttpAction.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.ce.systeminfo;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.sonar.ce.httpd.HttpAction;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
public class SystemInfoHttpAction implements HttpAction {
private static final String PATH = "/systemInfo";
private static final String PROTOBUF_MIME_TYPE = "application/x-protobuf";
private final List<SystemInfoSection> sectionProviders;
public SystemInfoHttpAction(List<SystemInfoSection> sectionProviders) {
this.sectionProviders = sectionProviders;
}
@Override
public String getContextPath() {
return PATH;
}
@Override
public void handle(HttpRequest request, HttpResponse response) {
if (!"GET".equals(request.getRequestLine().getMethod())) {
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_METHOD_NOT_ALLOWED);
response.setEntity(new StringEntity("Only GET is allowed", StandardCharsets.UTF_8));
return;
}
ProtobufSystemInfo.SystemInfo.Builder infoBuilder = ProtobufSystemInfo.SystemInfo.newBuilder();
sectionProviders.stream()
.map(SystemInfoSection::toProtobuf)
.forEach(infoBuilder::addSections);
byte[] bytes = infoBuilder.build().toByteArray();
response.setEntity(new ByteArrayEntity(bytes, ContentType.create(PROTOBUF_MIME_TYPE)));
response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
}
}
| 2,595 | 37.176471 | 99 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/systeminfo/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.ce.systeminfo;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeLoggingWorkerExecutionListener.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.ce.taskprocessor;
import java.time.Duration;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.log.CeTaskLogging;
import org.sonar.db.ce.CeActivityDto;
/**
* {@link CeWorker.ExecutionListener} responsible of calling {@link CeTaskLogging#initForTask(CeTask)} and
* {@link CeTaskLogging#clearForTask()}.
*/
public class CeLoggingWorkerExecutionListener implements CeWorker.ExecutionListener {
private final CeTaskLogging ceTaskLogging;
public CeLoggingWorkerExecutionListener(CeTaskLogging ceTaskLogging) {
this.ceTaskLogging = ceTaskLogging;
}
@Override
public void onStart(CeTask ceTask) {
ceTaskLogging.initForTask(ceTask);
}
@Override
public void onEnd(CeTask ceTask, CeActivityDto.Status status, Duration duration, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
ceTaskLogging.clearForTask();
}
}
| 1,796 | 34.94 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeProcessingScheduler.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.ce.taskprocessor;
public interface CeProcessingScheduler {
void startScheduling();
void gracefulStopScheduling();
void hardStopScheduling();
}
| 1,014 | 32.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeProcessingSchedulerExecutorService.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.ce.taskprocessor;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import org.sonar.server.util.StoppableExecutorService;
/**
* The {@link java.util.concurrent.ExecutorService} responsible for running {@link CeWorkerImpl}.
*/
public interface CeProcessingSchedulerExecutorService extends StoppableExecutorService, ListeningScheduledExecutorService {
}
| 1,244 | 40.5 | 123 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeProcessingSchedulerExecutorServiceImpl.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.ce.taskprocessor;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableScheduledFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.sonar.ce.configuration.CeConfiguration;
import org.sonar.server.util.AbstractStoppableExecutorService;
public class CeProcessingSchedulerExecutorServiceImpl extends AbstractStoppableExecutorService<ListeningScheduledExecutorService>
implements CeProcessingSchedulerExecutorService {
private static final String THREAD_NAME_PREFIX = "ce-worker-";
public CeProcessingSchedulerExecutorServiceImpl(CeConfiguration ceConfiguration) {
super(
MoreExecutors.listeningDecorator(
Executors.newScheduledThreadPool(ceConfiguration.getWorkerMaxCount(),
new ThreadFactoryBuilder()
.setNameFormat(THREAD_NAME_PREFIX + "%d")
.setPriority(Thread.MIN_PRIORITY)
.build())));
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
return delegate.submit(task);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return delegate.submit(task, result);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return delegate.submit(task);
}
@Override
public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return delegate.schedule(command, delay, unit);
}
@Override
public <V> ListenableScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return delegate.schedule(callable, delay, unit);
}
@Override
public ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
}
| 3,182 | 37.817073 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeProcessingSchedulerImpl.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.ce.taskprocessor;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableScheduledFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.configuration.CeConfiguration;
import static com.google.common.util.concurrent.Futures.addCallback;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class CeProcessingSchedulerImpl implements CeProcessingScheduler {
private static final Logger LOG = LoggerFactory.getLogger(CeProcessingSchedulerImpl.class);
// 30 seconds
private static final long DELAY_BETWEEN_DISABLED_TASKS = 30 * 1000L;
private final CeProcessingSchedulerExecutorService executorService;
private final long delayBetweenEnabledTasks;
private final TimeUnit timeUnit;
private final ChainingCallback[] chainingCallbacks;
private final CeWorkerController ceWorkerController;
private final long gracefulStopTimeoutInMs;
public CeProcessingSchedulerImpl(CeConfiguration ceConfiguration,
CeProcessingSchedulerExecutorService processingExecutorService, CeWorkerFactory ceCeWorkerFactory,
CeWorkerController ceWorkerController) {
this.executorService = processingExecutorService;
this.delayBetweenEnabledTasks = ceConfiguration.getQueuePollingDelay();
this.gracefulStopTimeoutInMs = ceConfiguration.getGracefulStopTimeoutInMs();
this.ceWorkerController = ceWorkerController;
this.timeUnit = MILLISECONDS;
int threadWorkerCount = ceConfiguration.getWorkerMaxCount();
this.chainingCallbacks = new ChainingCallback[threadWorkerCount];
for (int i = 0; i < threadWorkerCount; i++) {
CeWorker worker = ceCeWorkerFactory.create(i);
chainingCallbacks[i] = new ChainingCallback(worker);
}
}
@Override
public void startScheduling() {
for (ChainingCallback chainingCallback : chainingCallbacks) {
ListenableScheduledFuture<CeWorker.Result> future = executorService.schedule(chainingCallback.worker, delayBetweenEnabledTasks, timeUnit);
addCallback(future, chainingCallback, MoreExecutors.directExecutor());
}
}
/**
* This method is stopping all the workers and giving them a very large delay before killing them.
* <p>
* It supports being interrupted (eg. by a hard stop).
*/
public void gracefulStopScheduling() {
LOG.info("Gracefully stopping workers...");
requestAllWorkersToStop();
try {
waitForInProgressWorkersToFinish(gracefulStopTimeoutInMs);
if (ceWorkerController.hasAtLeastOneProcessingWorker()) {
LOG.info("Graceful stop period ended but some in-progress task did not finish. Tasks will be interrupted.");
}
interruptAllWorkers();
} catch (InterruptedException e) {
LOG.debug("Graceful stop was interrupted");
Thread.currentThread().interrupt();
}
}
/**
* This method is stopping all the workers and hardly giving them a delay before killing them.
* <p>
* If interrupted, it will interrupt any worker still in-progress before returning.
*/
public void hardStopScheduling() {
// nothing to do if graceful stop went through
if (Arrays.stream(chainingCallbacks).allMatch(ChainingCallback::isInterrupted)) {
return;
}
LOG.info("Hard stopping workers...");
requestAllWorkersToStop();
try {
waitForInProgressWorkersToFinish(350);
} catch (InterruptedException e) {
LOG.debug("Grace period of hard stop has been interrupted: {}", e.getMessage(), e);
Thread.currentThread().interrupt();
}
if (ceWorkerController.hasAtLeastOneProcessingWorker()) {
LOG.info("Some in-progress tasks are getting killed.");
}
// Interrupting the tasks
interruptAllWorkers();
}
private void interruptAllWorkers() {
// Interrupting the tasks
Arrays.stream(chainingCallbacks).forEach(t -> t.stop(true));
}
private void waitForInProgressWorkersToFinish(long shutdownTimeoutInMs) throws InterruptedException {
// Workers have some time to complete their in progress tasks
long until = System.currentTimeMillis() + shutdownTimeoutInMs;
LOG.debug("Waiting for workers to finish in-progress tasks for at most {}ms", shutdownTimeoutInMs);
while (System.currentTimeMillis() < until && ceWorkerController.hasAtLeastOneProcessingWorker()) {
Thread.sleep(200L);
}
}
private void requestAllWorkersToStop() {
// Requesting all workers to stop
Arrays.stream(chainingCallbacks).forEach(t -> t.stop(false));
}
private class ChainingCallback implements FutureCallback<CeWorker.Result> {
private volatile boolean keepRunning = true;
private volatile boolean interrupted = false;
private final CeWorker worker;
@CheckForNull
private ListenableFuture<CeWorker.Result> workerFuture;
public ChainingCallback(CeWorker worker) {
this.worker = worker;
}
@Override
public void onSuccess(@Nullable CeWorker.Result result) {
if (keepRunning) {
if (result == null) {
chainWithEnabledTaskDelay();
} else {
switch (result) {
case DISABLED:
chainWithDisabledTaskDelay();
break;
case NO_TASK:
chainWithEnabledTaskDelay();
break;
case TASK_PROCESSED:
default:
chainWithoutDelay();
}
}
}
}
@Override
public void onFailure(Throwable t) {
if (t instanceof Error) {
LOG.error("Compute Engine execution failed. Scheduled processing interrupted.", t);
} else if (keepRunning) {
chainWithoutDelay();
}
}
private void chainWithoutDelay() {
workerFuture = executorService.submit(worker);
addCallback();
}
private void chainWithEnabledTaskDelay() {
workerFuture = executorService.schedule(worker, delayBetweenEnabledTasks, timeUnit);
addCallback();
}
private void chainWithDisabledTaskDelay() {
workerFuture = executorService.schedule(worker, DELAY_BETWEEN_DISABLED_TASKS, timeUnit);
addCallback();
}
private void addCallback() {
if (workerFuture != null) {
Futures.addCallback(workerFuture, this, MoreExecutors.directExecutor());
}
}
public void stop(boolean interrupt) {
keepRunning = false;
interrupted = true;
if (workerFuture != null) {
workerFuture.cancel(interrupt);
}
}
public boolean isInterrupted() {
return interrupted;
}
}
}
| 7,709 | 33.886878 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProvider.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.ce.taskprocessor;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTaskInterrupter;
import org.springframework.context.annotation.Bean;
import static com.google.common.base.Preconditions.checkState;
public class CeTaskInterrupterProvider {
private static final String PROPERTY_CE_TASK_TIMEOUT = "sonar.ce.task.timeoutSeconds";
@Bean("CeTaskInterrupter")
public CeTaskInterrupter provide(Configuration configuration, CeWorkerController ceWorkerController, System2 system2) {
return configuration.getLong(PROPERTY_CE_TASK_TIMEOUT)
.filter(timeOutInSeconds -> {
checkState(timeOutInSeconds >= 1, "The property '%s' must be a long value >= 1. Got '%s'", PROPERTY_CE_TASK_TIMEOUT, timeOutInSeconds);
return true;
})
.map(timeOutInSeconds -> (CeTaskInterrupter) new TimeoutCeTaskInterrupter(timeOutInSeconds * 1_000L, ceWorkerController, system2))
.orElseGet(SimpleCeTaskInterrupter::new);
}
}
| 1,862 | 42.325581 | 143 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListener.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.ce.taskprocessor;
import java.time.Duration;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskInterrupter;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.db.ce.CeActivityDto;
public class CeTaskInterrupterWorkerExecutionListener implements CeWorker.ExecutionListener {
private final CeTaskInterrupter interrupter;
public CeTaskInterrupterWorkerExecutionListener(CeTaskInterrupter interrupter) {
this.interrupter = interrupter;
}
@Override
public void onStart(CeTask ceTask) {
interrupter.onStart(ceTask);
}
@Override
public void onEnd(CeTask ceTask, CeActivityDto.Status status, Duration duration, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
interrupter.onEnd(ceTask);
}
}
| 1,647 | 34.826087 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeTaskProcessorModule.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.ce.taskprocessor;
import org.sonar.ce.notification.ReportAnalysisFailureNotificationExecutionListener;
import org.sonar.core.platform.Module;
public class CeTaskProcessorModule extends Module {
@Override
protected void configureModule() {
add(
CeTaskProcessorRepositoryImpl.class,
CeLoggingWorkerExecutionListener.class,
ReportAnalysisFailureNotificationExecutionListener.class,
new CeTaskInterrupterProvider(),
CeTaskInterrupterWorkerExecutionListener.class,
CeWorkerFactoryImpl.class,
CeWorkerControllerImpl.class,
CeProcessingSchedulerExecutorServiceImpl.class,
CeProcessingSchedulerImpl.class
);
}
}
| 1,536 | 35.595238 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepository.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.ce.taskprocessor;
import java.util.Optional;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
public interface CeTaskProcessorRepository {
/**
* @throws NullPointerException if the specified {@link CeTask} is {@code null}
* @throws IllegalStateException if there is no {@link CeTaskProcessor} for the specified {@link CeTask} in the repository
*/
Optional<CeTaskProcessor> getForCeTask(CeTask ceTask);
}
| 1,322 | 36.8 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImpl.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.ce.taskprocessor;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
import static java.lang.String.format;
/**
* {@link CeTaskProcessorRepository} implementation which provides access to the {@link CeTaskProcessor} existing in the
* ioc container the current object belongs to.
*/
public class CeTaskProcessorRepositoryImpl implements CeTaskProcessorRepository {
private final Map<String, CeTaskProcessor> taskProcessorByCeTaskType;
public CeTaskProcessorRepositoryImpl(CeTaskProcessor[] taskProcessors) {
this.taskProcessorByCeTaskType = indexTaskProcessors(taskProcessors);
}
@Override
public Optional<CeTaskProcessor> getForCeTask(CeTask ceTask) {
return Optional.ofNullable(taskProcessorByCeTaskType.get(ceTask.getType()));
}
private static Map<String, CeTaskProcessor> indexTaskProcessors(CeTaskProcessor[] taskProcessors) {
Multimap<String, CeTaskProcessor> permissiveIndex = buildPermissiveCeTaskProcessorIndex(taskProcessors);
checkUniqueHandlerPerCeTaskType(permissiveIndex);
return permissiveIndex.asMap().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, y -> CeTaskProcessorCollectionToFirstElement.INSTANCE.apply(y.getValue())));
}
private static Multimap<String, CeTaskProcessor> buildPermissiveCeTaskProcessorIndex(CeTaskProcessor[] taskProcessors) {
Multimap<String, CeTaskProcessor> permissiveIndex = ArrayListMultimap.create(taskProcessors.length, 1);
for (CeTaskProcessor taskProcessor : taskProcessors) {
for (String ceTaskType : taskProcessor.getHandledCeTaskTypes()) {
permissiveIndex.put(ceTaskType, taskProcessor);
}
}
return permissiveIndex;
}
private static void checkUniqueHandlerPerCeTaskType(Multimap<String, CeTaskProcessor> permissiveIndex) {
for (Map.Entry<String, Collection<CeTaskProcessor>> entry : permissiveIndex.asMap().entrySet()) {
checkArgument(
entry.getValue().size() == 1,
format(
"There can be only one CeTaskProcessor instance registered as the processor for CeTask type %s. " +
"More than one found. Please fix your configuration: %s",
entry.getKey(),
entry.getValue().stream().map(ToClassName.INSTANCE).sorted(CASE_INSENSITIVE_ORDER).collect(Collectors.joining(", "))));
}
}
private enum ToClassName implements Function<Object, String> {
INSTANCE;
@Override
@Nonnull
public String apply(@Nonnull Object input) {
return input.getClass().getName();
}
}
private enum CeTaskProcessorCollectionToFirstElement implements Function<Collection<CeTaskProcessor>, CeTaskProcessor> {
INSTANCE;
@Override
@Nonnull
public CeTaskProcessor apply(@Nonnull Collection<CeTaskProcessor> input) {
return input.iterator().next();
}
}
}
| 4,102 | 39.623762 | 175 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorker.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.ce.taskprocessor;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.ce.queue.CeQueue;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.db.ce.CeActivityDto;
/**
* Marker interface of the runnable in charge of polling the {@link CeQueue} and executing {@link CeTask}.
* {@link Callable#call()} returns a Boolean which is {@code true} when some a {@link CeTask} was processed,
* {@code false} otherwise.
*/
public interface CeWorker extends Callable<CeWorker.Result> {
enum Result {
/** Worker is disabled */
DISABLED,
/** Worker found no task to process */
NO_TASK,
/** Worker found a task and processed it (either successfully or not) */
TASK_PROCESSED
}
/**
* Position of the current CeWorker among all the running workers, starts with 0.
*/
int getOrdinal();
/**
* UUID of the current CeWorker.
*/
String getUUID();
/**
* @return {@code true} if this CeWorker currently being executed by the specified {@link Thread}.
*/
boolean isExecutedBy(Thread thread);
/**
* @return the {@link CeTask} currently being executed by this worker, if any.
*/
Optional<CeTask> getCurrentTask();
/**
* Classes implementing will be called a task start and finishes executing.
* All classes implementing this interface are guaranteed to be called for each event, even if another implementation
* failed when called.
*/
@ComputeEngineSide
interface ExecutionListener {
/**
* Called when starting executing a {@link CeTask} (which means: after it's been picked for processing, but before
* the execution of the task by the {@link org.sonar.ce.task.taskprocessor.CeTaskProcessor#process(CeTask)}).
*/
void onStart(CeTask ceTask);
/**
* Called when the processing of the task is finished (which means: after it's been moved to history).
*/
void onEnd(CeTask ceTask, CeActivityDto.Status status, Duration duration, @Nullable CeTaskResult taskResult, @Nullable Throwable error);
}
}
| 3,037 | 33.91954 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerController.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.ce.taskprocessor;
import java.util.Optional;
/**
* This class is responsible of knowing/deciding which {@link CeWorker} is enabled and should actually try and find a
* task to process.
*/
public interface CeWorkerController {
interface ProcessingRecorderHook extends AutoCloseable {
/**
* Override to not declare any exception thrown.
*/
@Override
void close();
}
/**
* Registers to the controller that the specified {@link CeWorker}
*/
ProcessingRecorderHook registerProcessingFor(CeWorker ceWorker);
/**
* Returns {@code true} if the specified {@link CeWorker} is enabled
*/
boolean isEnabled(CeWorker ceWorker);
/**
* @return the {@link CeWorker} running in the specified {@link Thread}, if any.
*/
Optional<CeWorker> getCeWorkerIn(Thread thread);
/**
* Whether at least one worker is processing a task or not.
*
* @return {@code false} when all workers are waiting for tasks or are being stopped.
*/
boolean hasAtLeastOneProcessingWorker();
}
| 1,889 | 31.033898 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerControllerImpl.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.ce.taskprocessor;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.LoggerFactory;
import org.sonar.ce.configuration.CeConfiguration;
public class CeWorkerControllerImpl implements CeWorkerController {
private final ConcurrentHashMap<CeWorker, Status> workerStatuses = new ConcurrentHashMap<>();
private final CeConfiguration ceConfiguration;
enum Status {
PROCESSING, PAUSED
}
public CeWorkerControllerImpl(CeConfiguration ceConfiguration) {
this.ceConfiguration = ceConfiguration;
logEnabledWorkerCount();
}
private void logEnabledWorkerCount() {
int workerCount = ceConfiguration.getWorkerCount();
if (workerCount > 1) {
LoggerFactory.getLogger(CeWorkerController.class).info("Compute Engine will use {} concurrent workers to process tasks", workerCount);
}
}
@Override
public Optional<CeWorker> getCeWorkerIn(Thread thread) {
return workerStatuses.keySet().stream()
.filter(t -> t.isExecutedBy(thread))
.findFirst();
}
@Override
public ProcessingRecorderHook registerProcessingFor(CeWorker ceWorker) {
return new ProcessingRecorderHookImpl(ceWorker);
}
@Override
public boolean hasAtLeastOneProcessingWorker() {
return workerStatuses.entrySet().stream().anyMatch(e -> e.getValue() == Status.PROCESSING);
}
/**
* Returns {@code true} if {@link CeWorker#getOrdinal() worker ordinal} is strictly less than
* {@link CeConfiguration#getWorkerCount()}.
*
* This method does not fail if ordinal is invalid (ie. < 0).
*/
@Override
public boolean isEnabled(CeWorker ceWorker) {
return ceWorker.getOrdinal() < ceConfiguration.getWorkerCount();
}
private class ProcessingRecorderHookImpl implements ProcessingRecorderHook {
private final CeWorker ceWorker;
private ProcessingRecorderHookImpl(CeWorker ceWorker) {
this.ceWorker = ceWorker;
workerStatuses.put(this.ceWorker, Status.PROCESSING);
}
@Override
public void close() {
workerStatuses.put(ceWorker, Status.PAUSED);
}
}
}
| 2,946 | 32.11236 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerFactory.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.ce.taskprocessor;
import java.util.Set;
/**
* A factory that will create the CeWorkerFactory with an UUID
*/
public interface CeWorkerFactory {
/**
* Create a new CeWorker object with the specified ordinal.
* Each {@link CeWorker} returned by this method will have a different UUID from the others.
* All returned {@link CeWorker} will be returned by {@link #getWorkers()}.
*
* @return the CeWorker
*/
CeWorker create(int ordinal);
/**
* @return each {@link CeWorker} object returned by {@link #create}.
*/
Set<CeWorker> getWorkers();
}
| 1,435 | 33.190476 | 94 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerFactoryImpl.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.ce.taskprocessor;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.ce.queue.InternalCeQueue;
import org.sonar.core.util.UuidFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class CeWorkerFactoryImpl implements CeWorkerFactory {
private final UuidFactory uuidFactory;
private final InternalCeQueue queue;
private final CeTaskProcessorRepository taskProcessorRepository;
private final CeWorkerController ceWorkerController;
private final CeWorker.ExecutionListener[] executionListeners;
private Set<CeWorker> ceWorkers = Collections.emptySet();
/**
* Used by the ioc container when there is no {@link CeWorker.ExecutionListener} in the container.
*/
@Autowired(required = false)
public CeWorkerFactoryImpl(InternalCeQueue queue, CeTaskProcessorRepository taskProcessorRepository, UuidFactory uuidFactory, CeWorkerController ceWorkerController) {
this(queue, taskProcessorRepository, uuidFactory, ceWorkerController, new CeWorker.ExecutionListener[0]);
}
@Autowired(required = false)
public CeWorkerFactoryImpl(InternalCeQueue queue, CeTaskProcessorRepository taskProcessorRepository, UuidFactory uuidFactory, CeWorkerController ceWorkerController,
CeWorker.ExecutionListener[] executionListeners) {
this.queue = queue;
this.taskProcessorRepository = taskProcessorRepository;
this.uuidFactory = uuidFactory;
this.ceWorkerController = ceWorkerController;
this.executionListeners = executionListeners;
}
@Override
public CeWorker create(int ordinal) {
String uuid = uuidFactory.create();
CeWorkerImpl ceWorker = new CeWorkerImpl(ordinal, uuid, queue, taskProcessorRepository, ceWorkerController, executionListeners);
ceWorkers = Stream.concat(ceWorkers.stream(), Stream.of(ceWorker)).collect(Collectors.toSet());
return ceWorker;
}
@Override
public Set<CeWorker> getWorkers() {
return ceWorkers;
}
}
| 2,872 | 40.637681 | 168 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/CeWorkerImpl.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.ce.taskprocessor;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.queue.InternalCeQueue;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskInterruptedException;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import org.sonar.core.util.logs.Profiler;
import org.sonar.db.ce.CeActivityDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.ce.task.CeTaskInterruptedException.isTaskInterruptedException;
import static org.sonar.ce.taskprocessor.CeWorker.Result.DISABLED;
import static org.sonar.ce.taskprocessor.CeWorker.Result.NO_TASK;
import static org.sonar.ce.taskprocessor.CeWorker.Result.TASK_PROCESSED;
import static org.sonar.db.ce.CeActivityDto.Status.FAILED;
public class CeWorkerImpl implements CeWorker {
private static final Logger LOG = LoggerFactory.getLogger(CeWorkerImpl.class);
private final int ordinal;
private final String uuid;
private final InternalCeQueue queue;
private final CeTaskProcessorRepository taskProcessorRepository;
private final CeWorkerController ceWorkerController;
private final List<ExecutionListener> listeners;
private final AtomicReference<RunningState> runningState = new AtomicReference<>();
private boolean excludeIndexationJob;
public CeWorkerImpl(int ordinal, String uuid,
InternalCeQueue queue, CeTaskProcessorRepository taskProcessorRepository,
CeWorkerController ceWorkerController,
ExecutionListener... listeners) {
this.ordinal = checkOrdinal(ordinal);
this.uuid = uuid;
this.queue = queue;
this.taskProcessorRepository = taskProcessorRepository;
this.ceWorkerController = ceWorkerController;
this.listeners = Arrays.asList(listeners);
this.excludeIndexationJob = true;
}
private static int checkOrdinal(int ordinal) {
checkArgument(ordinal >= 0, "Ordinal must be >= 0");
return ordinal;
}
@Override
public Result call() {
try (TrackRunningState trackRunningState = new TrackRunningState(this::findAndProcessTask)) {
return trackRunningState.get();
}
}
@Override
public int getOrdinal() {
return ordinal;
}
@Override
public String getUUID() {
return uuid;
}
@Override
public boolean isExecutedBy(Thread thread) {
return Optional.ofNullable(runningState.get())
.filter(state -> state.runningThread.equals(thread))
.isPresent();
}
@Override
public Optional<CeTask> getCurrentTask() {
return Optional.ofNullable(runningState.get())
.flatMap(RunningState::getTask);
}
private class TrackRunningState implements AutoCloseable, Supplier<Result> {
private final RunningState localRunningState;
private final Function<RunningState, Result> delegate;
private final String oldName;
private TrackRunningState(Function<RunningState, Result> delegate) {
Thread currentThread = Thread.currentThread();
localRunningState = new RunningState(currentThread);
if (!runningState.compareAndSet(null, localRunningState)) {
LOG.warn("Worker {} (UUID=%s) starts executing with new Thread {} while running state isn't null. " +
"Forcefully updating Workers's running state to new Thread.",
getOrdinal(), getUUID(), currentThread);
runningState.set(localRunningState);
}
this.delegate = delegate;
this.oldName = currentThread.getName();
}
@Override
public Result get() {
localRunningState.runningThread.setName(String.format("Worker %s (UUID=%s) on %s", getOrdinal(), getUUID(), oldName));
return delegate.apply(localRunningState);
}
@Override
public void close() {
localRunningState.runningThread.setName(oldName);
if (!runningState.compareAndSet(localRunningState, null)) {
LOG.warn("Worker {} (UUID=%s) ending execution in Thread {} while running state has already changed." +
" Keeping this new state.",
getOrdinal(), getUUID(), localRunningState.runningThread);
}
}
}
private Result findAndProcessTask(RunningState localRunningState) {
if (!ceWorkerController.isEnabled(this)) {
return DISABLED;
}
Optional<CeTask> ceTask = tryAndFindTaskToExecute();
if (!ceTask.isPresent()) {
return NO_TASK;
}
try (CeWorkerController.ProcessingRecorderHook processing = ceWorkerController.registerProcessingFor(this);
ExecuteTask executeTask = new ExecuteTask(localRunningState, ceTask.get())) {
executeTask.run();
} catch (Exception e) {
LOG.error(format("An error occurred while executing task with uuid '%s'", ceTask.get().getUuid()), e);
}
return TASK_PROCESSED;
}
private Optional<CeTask> tryAndFindTaskToExecute() {
excludeIndexationJob = !excludeIndexationJob;
try {
return queue.peek(uuid, excludeIndexationJob);
} catch (Exception e) {
LOG.error("Failed to pop the queue of analysis reports", e);
}
return Optional.empty();
}
private final class ExecuteTask implements Runnable, AutoCloseable {
private final CeTask task;
private final RunningState localRunningState;
private final Profiler ceProfiler;
private CeActivityDto.Status status = FAILED;
private CeTaskResult taskResult = null;
private Throwable error = null;
private ExecuteTask(RunningState localRunningState, CeTask task) {
this.task = task;
this.localRunningState = localRunningState;
this.ceProfiler = startLogProfiler(task);
}
@Override
public void run() {
beforeExecute();
executeTask();
}
@Override
public void close() {
afterExecute();
}
private void beforeExecute() {
localRunningState.setTask(task);
callListeners(t -> t.onStart(task));
}
private void executeTask() {
try {
// TODO delegate the message to the related task processor, according to task type
Optional<CeTaskProcessor> taskProcessor = taskProcessorRepository.getForCeTask(task);
if (taskProcessor.isPresent()) {
taskResult = taskProcessor.get().process(task);
status = CeActivityDto.Status.SUCCESS;
} else {
LOG.error("No CeTaskProcessor is defined for task of type {}. Plugin configuration may have changed", task.getType());
status = FAILED;
}
} catch (MessageException e) {
// error
error = e;
} catch (Throwable e) {
Optional<CeTaskInterruptedException> taskInterruptedException = isTaskInterruptedException(e);
if (taskInterruptedException.isPresent()) {
LOG.trace("Task interrupted", e);
CeTaskInterruptedException exception = taskInterruptedException.get();
CeActivityDto.Status interruptionStatus = exception.getStatus();
status = interruptionStatus;
error = (interruptionStatus == FAILED ? exception : null);
} else {
// error
LOG.error("Failed to execute task {}", task.getUuid(), e);
error = e;
}
}
}
private void afterExecute() {
localRunningState.setTask(null);
finalizeTask(task, ceProfiler, status, taskResult, error);
}
private void finalizeTask(CeTask task, Profiler ceProfiler, CeActivityDto.Status status,
@Nullable CeTaskResult taskResult, @Nullable Throwable error) {
try {
queue.remove(task, status, taskResult, error);
} catch (Exception e) {
if (error != null) {
e.addSuppressed(error);
}
LOG.error(format("Failed to finalize task with uuid '%s' and persist its state to db", task.getUuid()), e);
} finally {
ceProfiler.addContext("status", status.name());
long durationMs = ceProfiler.stopInfo("Executed task");
Duration duration = Duration.of(durationMs, ChronoUnit.MILLIS);
callListeners(t -> t.onEnd(task, status, duration, taskResult, error));
}
}
private void callListeners(Consumer<ExecutionListener> call) {
listeners.forEach(listener -> {
try {
call.accept(listener);
} catch (Throwable t) {
LOG.error(format("Call to listener %s failed.", listener.getClass().getSimpleName()), t);
}
});
}
}
private static Profiler startLogProfiler(CeTask task) {
Profiler profiler = Profiler.create(LOG)
.logTimeLast(true)
.addContext("project", task.getEntity().flatMap(CeTask.Component::getKey).orElse(null))
.addContext("type", task.getType());
for (Map.Entry<String, String> characteristic : task.getCharacteristics().entrySet()) {
profiler.addContext(characteristic.getKey(), characteristic.getValue());
}
return profiler
.addContext("id", task.getUuid())
.addContext("submitter", submitterOf(task))
.startInfo("Execute task");
}
@CheckForNull
private static String submitterOf(CeTask task) {
CeTask.User submitter = task.getSubmitter();
if (submitter == null) {
return null;
}
String submitterLogin = submitter.login();
if (submitterLogin != null) {
return submitterLogin;
} else {
return submitter.uuid();
}
}
private static final class RunningState {
private final Thread runningThread;
private CeTask task;
private RunningState(Thread runningThread) {
this.runningThread = runningThread;
}
public Optional<CeTask> getTask() {
return Optional.ofNullable(task);
}
public void setTask(@Nullable CeTask task) {
this.task = task;
}
}
}
| 10,980 | 33.75 | 128 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupter.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.ce.taskprocessor;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskCanceledException;
import org.sonar.ce.task.CeTaskInterruptedException;
import org.sonar.ce.task.CeTaskInterrupter;
/**
* An implementation of {@link CeTaskInterrupter} which will only interrupt the processing if the current thread
* has been interrupted.
*
* @see Thread#isInterrupted()
*/
public class SimpleCeTaskInterrupter implements CeTaskInterrupter {
@Override
public void check(Thread currentThread) throws CeTaskInterruptedException {
if (currentThread.isInterrupted()) {
throw new CeTaskCanceledException(currentThread);
}
}
@Override
public void onStart(CeTask ceTask) {
// nothing to do
}
@Override
public void onEnd(CeTask ceTask) {
// nothing to do
}
}
| 1,660 | 31.568627 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupter.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.ce.taskprocessor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskInterruptedException;
import org.sonar.ce.task.CeTaskTimeoutException;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
/**
* An implementation of {@link org.sonar.ce.task.CeTaskInterrupter} which interrupts the processing of the task
* if:
* <ul>
* <li>the thread has been interrupted</li>
* <li>it's been running for more than a certain, configurable, amount of time</li>
* </ul>
*/
public class TimeoutCeTaskInterrupter extends SimpleCeTaskInterrupter {
private static final Logger LOG = LoggerFactory.getLogger(TimeoutCeTaskInterrupter.class);
private final long taskTimeoutThreshold;
private final CeWorkerController ceWorkerController;
private final System2 system2;
private final Map<String, Long> startTimestampByCeTaskUuid = new HashMap<>();
public TimeoutCeTaskInterrupter(long taskTimeoutThreshold, CeWorkerController ceWorkerController, System2 system2) {
checkArgument(taskTimeoutThreshold >= 1, "threshold must be >= 1");
LOG.info("Compute Engine Task timeout enabled: {} ms", taskTimeoutThreshold);
this.taskTimeoutThreshold = taskTimeoutThreshold;
this.ceWorkerController = ceWorkerController;
this.system2 = system2;
}
@Override
public void check(Thread currentThread) throws CeTaskInterruptedException {
super.check(currentThread);
computeTimeOutOf(taskOf(currentThread))
.ifPresent(timeout -> {
throw new CeTaskTimeoutException(format("Execution of task timed out after %s ms", timeout));
});
}
private Optional<Long> computeTimeOutOf(CeTask ceTask) {
Long startTimestamp = startTimestampByCeTaskUuid.get(ceTask.getUuid());
checkState(startTimestamp != null, "No start time recorded for task %s", ceTask.getUuid());
long duration = system2.now() - startTimestamp;
return Optional.of(duration)
.filter(t -> t > taskTimeoutThreshold);
}
private CeTask taskOf(Thread currentThread) {
return ceWorkerController.getCeWorkerIn(currentThread)
.flatMap(CeWorker::getCurrentTask)
.orElseThrow(() -> new IllegalStateException(format("Could not find the CeTask being executed in thread '%s'", currentThread.getName())));
}
@Override
public void onStart(CeTask ceTask) {
long now = system2.now();
Long existingTimestamp = startTimestampByCeTaskUuid.put(ceTask.getUuid(), now);
if (existingTimestamp != null) {
LOG.warn(
"Notified of start of execution of task {} but start had already been recorded at {}. Recording new start at {}",
ceTask.getUuid(),
existingTimestamp,
now);
}
}
@Override
public void onEnd(CeTask ceTask) {
Long startTimestamp = startTimestampByCeTaskUuid.remove(ceTask.getUuid());
if (startTimestamp == null) {
LOG.warn("Notified of end of execution of task {} but start wasn't recorded", ceTask.getUuid());
}
}
}
| 4,093 | 37.261682 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/taskprocessor/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.ce.taskprocessor;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 39.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/CeDistributedInformationImplTest.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.ce;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import org.sonar.process.cluster.hz.HazelcastMember;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.process.cluster.hz.HazelcastObjects.WORKER_UUIDS;
public class CeDistributedInformationImplTest {
private final UUID clientUUID1 = UUID.randomUUID();
private final UUID clientUUID2 = UUID.randomUUID();
private final UUID clientUUID3 = UUID.randomUUID();
private final String w1 = UUID.randomUUID().toString();
private final String w2 = UUID.randomUUID().toString();
private final String w3 = UUID.randomUUID().toString();
private final String w4 = UUID.randomUUID().toString();
private final String w5 = UUID.randomUUID().toString();
private final String w6 = UUID.randomUUID().toString();
private final Map<UUID, Set<String>> workerMap = ImmutableMap.of(
clientUUID1, ImmutableSet.of(w1, w2),
clientUUID2, ImmutableSet.of(w3),
clientUUID3, ImmutableSet.of(w4, w5, w6));
private final HazelcastMember hzClientWrapper = mock(HazelcastMember.class);
@Test
public void getWorkerUUIDs_returns_union_of_workers_uuids_of_local_and_cluster_worker_uuids() {
when(hzClientWrapper.getUuid()).thenReturn(clientUUID1);
when(hzClientWrapper.getMemberUuids()).thenReturn(ImmutableSet.of(clientUUID1, clientUUID2, clientUUID3));
when(hzClientWrapper.<UUID, Set<String>>getReplicatedMap(WORKER_UUIDS)).thenReturn(workerMap);
CeDistributedInformation ceDistributedInformation = new CeDistributedInformationImpl(hzClientWrapper, mock(CeWorkerFactory.class));
assertThat(ceDistributedInformation.getWorkerUUIDs()).containsExactlyInAnyOrder(w1, w2, w3, w4, w5, w6);
}
@Test
public void getWorkerUUIDs_must_filter_absent_client() {
when(hzClientWrapper.getUuid()).thenReturn(clientUUID1);
when(hzClientWrapper.getMemberUuids()).thenReturn(ImmutableSet.of(clientUUID1, clientUUID2));
when(hzClientWrapper.<UUID, Set<String>>getReplicatedMap(WORKER_UUIDS)).thenReturn(workerMap);
CeDistributedInformation ceDistributedInformation = new CeDistributedInformationImpl(hzClientWrapper, mock(CeWorkerFactory.class));
assertThat(ceDistributedInformation.getWorkerUUIDs()).containsExactlyInAnyOrder(w1, w2, w3);
}
@Test
public void broadcastWorkerUUIDs_adds_local_workerUUIDs_to_shared_map_under_key_of_localendpoint_uuid() {
Set<UUID> connectedClients = new HashSet<>();
Map<UUID, Set<String>> modifiableWorkerMap = new HashMap<>();
connectedClients.add(clientUUID1);
connectedClients.add(clientUUID2);
when(hzClientWrapper.getUuid()).thenReturn(clientUUID1);
when(hzClientWrapper.getMemberUuids()).thenReturn(connectedClients);
when(hzClientWrapper.<UUID, Set<String>>getReplicatedMap(WORKER_UUIDS)).thenReturn(modifiableWorkerMap);
CeWorkerFactory ceWorkerFactory = mock(CeWorkerFactory.class);
Set<CeWorker> ceWorkers = Stream.of("a10", "a11").map(uuid -> {
CeWorker res = mock(CeWorker.class);
when(res.getUUID()).thenReturn(uuid);
return res;
}).collect(Collectors.toSet());
when(ceWorkerFactory.getWorkers()).thenReturn(ceWorkers);
CeDistributedInformationImpl ceDistributedInformation = new CeDistributedInformationImpl(hzClientWrapper, ceWorkerFactory);
try {
ceDistributedInformation.broadcastWorkerUUIDs();
assertThat(modifiableWorkerMap).containsExactly(
entry(clientUUID1, ImmutableSet.of("a10", "a11")));
} finally {
ceDistributedInformation.stop();
}
}
@Test
public void stop_must_remove_local_workerUUIDs() {
Set<UUID> connectedClients = new HashSet<>();
connectedClients.add(clientUUID1);
connectedClients.add(clientUUID2);
connectedClients.add(clientUUID3);
Map<UUID, Set<String>> modifiableWorkerMap = new HashMap<>(workerMap);
when(hzClientWrapper.getUuid()).thenReturn(clientUUID1);
when(hzClientWrapper.getMemberUuids()).thenReturn(connectedClients);
when(hzClientWrapper.<UUID, Set<String>>getReplicatedMap(WORKER_UUIDS)).thenReturn(modifiableWorkerMap);
CeDistributedInformationImpl ceDistributedInformation = new CeDistributedInformationImpl(hzClientWrapper, mock(CeWorkerFactory.class));
ceDistributedInformation.stop();
assertThat(modifiableWorkerMap).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of(clientUUID2, ImmutableSet.of(w3), clientUUID3, ImmutableSet.of(w4, w5, w6)));
}
}
| 5,783 | 44.1875 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/ComputeEngineImplTest.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.ce;
import java.util.Properties;
import org.junit.Test;
import org.sonar.ce.container.ComputeEngineContainer;
import org.sonar.ce.container.ComputeEngineStatus;
import org.sonar.process.Props;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ComputeEngineImplTest {
private final ComputeEngineContainer computeEngineContainer = new NoOpComputeEngineContainer();
private final ComputeEngine underTest = new ComputeEngineImpl(new Props(new Properties()), computeEngineContainer);
@Test
public void startup_throws_ISE_when_called_twice() {
underTest.startup();
assertThatThrownBy(underTest::startup)
.isInstanceOf(IllegalStateException.class)
.hasMessage("startup() can not be called multiple times");
}
@Test
public void stopProcessing_throws_ISE_if_startup_was_not_called_before() {
assertThatThrownBy(underTest::stopProcessing)
.isInstanceOf(IllegalStateException.class)
.hasMessage("stopProcessing() must not be called before startup()");
}
@Test
public void stopProcessing_throws_ISE_if_called_after_shutdown() {
underTest.startup();
underTest.shutdown();
assertThatThrownBy(underTest::stopProcessing)
.isInstanceOf(IllegalStateException.class)
.hasMessage("stopProcessing() can not be called after shutdown()");
}
@Test
public void stopProcessing_throws_ISE_if_called_twice() {
underTest.startup();
underTest.stopProcessing();
assertThatThrownBy(underTest::stopProcessing)
.isInstanceOf(IllegalStateException.class)
.hasMessage("stopProcessing() can not be called multiple times");
}
@Test
public void shutdown_throws_ISE_if_startup_was_not_called_before() {
assertThatThrownBy(underTest::shutdown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("shutdown() must not be called before startup()");
}
@Test
public void shutdown_throws_ISE_if_called_twice() {
underTest.startup();
underTest.shutdown();
assertThatThrownBy(underTest::shutdown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("shutdown() can not be called multiple times");
}
private static class NoOpComputeEngineContainer implements ComputeEngineContainer {
@Override
public void setComputeEngineStatus(ComputeEngineStatus computeEngineStatus) {
}
@Override
public ComputeEngineContainer start(Props props) {
return this;
}
@Override
public ComputeEngineContainer stopWorkers() {
return this;
}
@Override
public ComputeEngineContainer stop() {
return this;
}
}
}
| 3,488 | 31.009174 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/StandaloneCeDistributedInformationTest.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.ce;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import org.sonar.ce.taskprocessor.CeWorker;
import org.sonar.ce.taskprocessor.CeWorkerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StandaloneCeDistributedInformationTest {
@Test
public void broadcastWorkerUUIDs_must_retrieve_from_ceworkerfactory() {
CeWorkerFactory ceWorkerFactory = mock(CeWorkerFactory.class);
StandaloneCeDistributedInformation ceCluster = new StandaloneCeDistributedInformation(ceWorkerFactory);
ceCluster.broadcastWorkerUUIDs();
verify(ceWorkerFactory).getWorkers();
}
@Test
public void getWorkerUUIDs_must_be_retrieved_from_ceworkerfactory() {
CeWorkerFactory ceWorkerFactory = mock(CeWorkerFactory.class);
CeWorker[] ceWorkers = IntStream.range(0, new Random().nextInt(10))
.mapToObj(i -> {
CeWorker ceWorker = mock(CeWorker.class);
when(ceWorker.getUUID()).thenReturn("uuid_" + i);
return ceWorker;
})
.toArray(CeWorker[]::new);
when(ceWorkerFactory.getWorkers()).thenReturn(ImmutableSet.copyOf(ceWorkers));
StandaloneCeDistributedInformation ceCluster = new StandaloneCeDistributedInformation(ceWorkerFactory);
ceCluster.broadcastWorkerUUIDs();
assertThat(ceCluster.getWorkerUUIDs()).isEqualTo(Arrays.stream(ceWorkers).map(CeWorker::getUUID).collect(Collectors.toSet()));
}
@Test
public void getWorkerUUIDs_throws_ISE_if_broadcastWorkerUUIDs_has_not_been_called_before() {
CeWorkerFactory ceWorkerFactory = mock(CeWorkerFactory.class);
StandaloneCeDistributedInformation ceCluster = new StandaloneCeDistributedInformation(ceWorkerFactory);
assertThatThrownBy(ceCluster::getWorkerUUIDs)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Invalid call, broadcastWorkerUUIDs() must be called first.");
}
@Test
public void acquireCleanJobLock_returns_a_non_current_lock() {
StandaloneCeDistributedInformation underTest = new StandaloneCeDistributedInformation(mock(CeWorkerFactory.class));
Lock lock = underTest.acquireCleanJobLock();
IntStream.range(0, 5 + Math.abs(new Random().nextInt(50)))
.forEach(i -> {
try {
assertThat(lock.tryLock()).isTrue();
assertThat(lock.tryLock(1, TimeUnit.MINUTES)).isTrue();
lock.lock();
lock.lockInterruptibly();
lock.unlock();
} catch (InterruptedException e) {
fail("no InterruptedException should be thrown");
}
try {
lock.newCondition();
fail("a UnsupportedOperationException should have been thrown");
} catch (UnsupportedOperationException e) {
assertThat(e.getMessage()).isEqualTo("newCondition not supported");
}
});
}
}
| 4,105 | 38.104762 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningExecutorServiceImplTest.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.ce.analysis.cache.cleaning;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class AnalysisCacheCleaningExecutorServiceImplTest {
@Test
public void constructor_createsExecutorDelegateThatIsReadyToAct() {
AnalysisCacheCleaningExecutorServiceImpl underTest = new AnalysisCacheCleaningExecutorServiceImpl();
assertThat(underTest.isShutdown()).isFalse();
assertThat(underTest.isTerminated()).isFalse();
}
}
| 1,326 | 35.861111 | 104 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningModuleTest.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.ce.analysis.cache.cleaning;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class AnalysisCacheCleaningModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new AnalysisCacheCleaningModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(2);
}
}
| 1,298 | 36.114286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/app/CeSecurityManagerTest.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.ce.app;
import java.util.Properties;
import org.junit.Test;
import org.sonar.ce.security.PluginCeRule;
import org.sonar.process.PluginFileWriteRule;
import org.sonar.process.PluginSecurityManager;
import org.sonar.process.Props;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.process.ProcessProperties.Property.PATH_HOME;
import static org.sonar.process.ProcessProperties.Property.PATH_TEMP;
public class CeSecurityManagerTest {
private final PluginSecurityManager pluginSecurityManager = mock(PluginSecurityManager.class);
@Test
public void apply_calls_PluginSecurityManager() {
Properties properties = new Properties();
properties.setProperty(PATH_HOME.getKey(), "home");
properties.setProperty(PATH_TEMP.getKey(), "temp");
Props props = new Props(properties);
CeSecurityManager ceSecurityManager = new CeSecurityManager(pluginSecurityManager, props);
ceSecurityManager.apply();
verify(pluginSecurityManager).restrictPlugins(any(PluginFileWriteRule.class), any(PluginCeRule.class));
}
@Test
public void fail_if_runs_twice() {
Properties properties = new Properties();
properties.setProperty(PATH_HOME.getKey(), "home");
properties.setProperty(PATH_TEMP.getKey(), "temp");
Props props = new Props(properties);
CeSecurityManager ceSecurityManager = new CeSecurityManager(pluginSecurityManager, props);
ceSecurityManager.apply();
assertThrows(IllegalStateException.class, ceSecurityManager::apply);
}
}
| 2,491 | 39.193548 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/app/CeServerTest.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.ce.app;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.junit.After;
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.junit.runner.RunWith;
import org.mockito.Mockito;
import org.sonar.ce.ComputeEngine;
import org.sonar.process.MessageException;
import org.sonar.process.MinimumViableSystem;
import org.sonar.process.Monitored;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(DataProviderRunner.class)
public class CeServerTest {
@Rule
public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60));
private CeServer underTest = null;
private Thread waitingThread = null;
private MinimumViableSystem minimumViableSystem = mock(MinimumViableSystem.class, Mockito.RETURNS_MOCKS);
private CeSecurityManager ceSecurityManager = mock(CeSecurityManager.class);
@After
public void tearDown() throws Exception {
if (underTest != null) {
underTest.hardStop();
}
Thread waitingThread = this.waitingThread;
this.waitingThread = null;
if (waitingThread != null) {
waitingThread.join();
}
}
@Test
public void constructor_does_not_start_a_new_Thread() {
int activeCount = Thread.activeCount();
newCeServer();
assertThat(Thread.activeCount()).isSameAs(activeCount);
}
@Test
public void constructor_calls_ceSecurityManager() {
newCeServer();
verify(ceSecurityManager).apply();
}
@Test
public void awaitStop_throws_ISE_if_called_before_start() {
CeServer ceServer = newCeServer();
assertThatThrownBy(ceServer::awaitStop)
.isInstanceOf(IllegalStateException.class)
.hasMessage("awaitStop() must not be called before start()");
}
@Test
public void start_starts_a_new_Thread() {
int activeCount = Thread.activeCount();
newCeServer().start();
assertThat(Thread.activeCount()).isSameAs(activeCount + 1);
}
@Test
public void stop_stops_Thread() {
CeServer ceServer = newCeServer();
assertThat(ceThreadExists()).isFalse();
ceServer.start();
assertThat(ceThreadExists()).isTrue();
ceServer.stop();
await().atMost(5, TimeUnit.SECONDS).until(() -> !ceThreadExists());
}
@Test
public void stop_dontDoAnythingIfThreadDoesntExist() {
CeServer ceServer = newCeServer();
assertThat(ceThreadExists()).isFalse();
ceServer.stop();
//expect no exception and thread still doesn't exist
assertThat(ceThreadExists()).isFalse();
}
private static boolean ceThreadExists() {
return Thread.getAllStackTraces().keySet().stream().anyMatch(t -> t.getName().equals("ce-main"));
}
@Test
public void start_throws_ISE_when_called_twice() {
CeServer ceServer = newCeServer();
ceServer.start();
assertThatThrownBy(ceServer::start)
.isInstanceOf(IllegalStateException.class)
.hasMessage("start() can not be called twice");
}
@Test
public void getStatus_throws_ISE_when_called_before_start() {
CeServer ceServer = newCeServer();
assertThatThrownBy(ceServer::getStatus)
.isInstanceOf(IllegalStateException.class)
.hasMessage("getStatus() can not be called before start()");
}
@Test
public void getStatus_does_not_return_OPERATIONAL_until_ComputeEngine_startup_returns() {
BlockingStartupComputeEngine computeEngine = new BlockingStartupComputeEngine(null);
CeServer ceServer = newCeServer(computeEngine);
ceServer.start();
assertThat(ceServer.getStatus()).isEqualTo(Monitored.Status.DOWN);
// release ComputeEngine startup method
computeEngine.releaseStartup();
await().atMost(5, TimeUnit.SECONDS).until(() -> ceServer.getStatus() == Monitored.Status.OPERATIONAL);
}
@Test
@UseDataProvider("exceptions")
public void getStatus_returns_FAILED_when_ComputeEngine_startup_throws_any_Exception_or_Error(RuntimeException exception) {
BlockingStartupComputeEngine computeEngine = new BlockingStartupComputeEngine(exception);
CeServer ceServer = newCeServer(computeEngine);
ceServer.start();
assertThat(ceServer.getStatus()).isEqualTo(Monitored.Status.DOWN);
// release ComputeEngine startup method which will throw startupException
computeEngine.releaseStartup();
await().atMost(5, TimeUnit.SECONDS).until(() -> ceServer.getStatus() == Monitored.Status.FAILED);
}
@DataProvider
public static Object[] exceptions() {
return new Object[] {new MessageException("exception"), new IllegalStateException("Faking failing ComputeEngine#startup()")};
}
@Test
public void awaitStop_keeps_blocking_calling_thread_even_if_calling_thread_is_interrupted_but_until_stop_is_called() throws Exception {
final CeServer ceServer = newCeServer();
Thread waitingThread = newWaitingThread(ceServer::awaitStop);
ceServer.start();
waitingThread.start();
// interrupts waitingThread 5 times in a row (we really insist)
for (int i = 0; i < 5; i++) {
waitingThread.interrupt();
Thread.sleep(5);
assertThat(waitingThread.isAlive()).isTrue();
}
ceServer.hardStop();
// wait for waiting thread to stop because we stopped ceServer
// if it does not, the test will fail with timeout
waitingThread.join();
}
@Test
public void awaitStop_unblocks_when_waiting_for_ComputeEngine_startup_fails() {
CeServer ceServer = newCeServer(new ComputeEngine() {
@Override
public void startup() {
throw new Error("Faking ComputeEngine.startup() failing");
}
@Override
public void stopProcessing() {
throw new UnsupportedOperationException("stopProcessing() should never be called in this test");
}
@Override
public void shutdown() {
throw new UnsupportedOperationException("shutdown() should never be called in this test");
}
});
ceServer.start();
// if awaitStop does not unblock, the test will fail with timeout
ceServer.awaitStop();
}
@Test
public void staticMain_withoutAnyArguments_expectException() {
String[] emptyArray = {};
assertThatThrownBy(() -> CeServer.main(emptyArray))
.hasMessage("Only a single command-line argument is accepted (absolute path to configuration file)");
}
@Test
public void stop_releases_thread_in_awaitStop_even_when_ComputeEngine_shutdown_fails() throws InterruptedException {
final CeServer ceServer = newCeServer(new ComputeEngine() {
@Override
public void startup() {
// nothing to do at startup
}
@Override
public void stopProcessing() {
throw new UnsupportedOperationException("stopProcessing should not be called in this test");
}
@Override
public void shutdown() {
throw new Error("Faking ComputeEngine.shutdown() failing");
}
});
Thread waitingThread = newWaitingThread(ceServer::awaitStop);
ceServer.start();
waitingThread.start();
ceServer.hardStop();
// wait for waiting thread to stop because we stopped ceServer
// if it does not, the test will fail with timeout
waitingThread.join();
}
private CeServer newCeServer() {
return newCeServer(mock(ComputeEngine.class));
}
private CeServer newCeServer(ComputeEngine computeEngine) {
checkState(this.underTest == null, "Only one CeServer can be created per test method");
this.underTest = new CeServer(computeEngine, minimumViableSystem, ceSecurityManager);
return underTest;
}
private Thread newWaitingThread(Runnable runnable) {
Thread t = new Thread(runnable);
checkState(this.waitingThread == null, "Only one waiting thread can be created per test method");
this.waitingThread = t;
return t;
}
private static class BlockingStartupComputeEngine implements ComputeEngine {
private final CountDownLatch latch = new CountDownLatch(1);
@CheckForNull
private final RuntimeException throwable;
public BlockingStartupComputeEngine(@Nullable RuntimeException throwable) {
this.throwable = throwable;
}
@Override
public void startup() {
try {
latch.await(1000, MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("await failed", e);
}
if (throwable != null) {
throw throwable;
}
}
@Override
public void stopProcessing() {
// do nothing
}
@Override
public void shutdown() {
// do nothing
}
private void releaseStartup() {
this.latch.countDown();
}
}
}
| 10,058 | 30.632075 | 137 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/async/SynchronousAsyncExecutionTest.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.ce.async;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SynchronousAsyncExecutionTest {
private SynchronousAsyncExecution underTest = new SynchronousAsyncExecution();
@Test
public void addToQueue_fails_with_NPE_if_Runnable_is_null() {
assertThatThrownBy(() -> underTest.addToQueue(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void addToQueue_executes_Runnable_synchronously() {
Set<String> s = new HashSet<>();
underTest.addToQueue(() -> s.add("done"));
assertThat(s).containsOnly("done");
}
}
| 1,581 | 31.958333 | 80 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/cleaning/CeCleaningSchedulerImplTest.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.ce.cleaning;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.junit.Test;
import org.sonar.ce.CeDistributedInformation;
import org.sonar.ce.configuration.CeConfiguration;
import org.sonar.ce.queue.InternalCeQueue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CeCleaningSchedulerImplTest {
private Lock jobLock = mock(Lock.class);
@Test
public void startScheduling_does_not_fail_if_cleaning_methods_send_even_an_Exception() {
InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class);
CeDistributedInformation mockedCeDistributedInformation = mockCeDistributedInformation(jobLock);
CeCleaningSchedulerImpl underTest = mockCeCleaningSchedulerImpl(mockedInternalCeQueue, mockedCeDistributedInformation);
Exception exception = new IllegalArgumentException("faking unchecked exception thrown by cancelWornOuts");
doThrow(exception).when(mockedInternalCeQueue).resetTasksWithUnknownWorkerUUIDs(any());
underTest.startScheduling();
verify(mockedInternalCeQueue).resetTasksWithUnknownWorkerUUIDs(any());
}
@Test
public void startScheduling_fails_if_resetTasksWithUnknownWorkerUUIDs_send_an_Error() {
InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class);
CeDistributedInformation mockedCeDistributedInformation = mockCeDistributedInformation(jobLock);
CeCleaningSchedulerImpl underTest = mockCeCleaningSchedulerImpl(mockedInternalCeQueue, mockedCeDistributedInformation);
Error expected = new Error("faking Error thrown by cancelWornOuts");
doThrow(expected).when(mockedInternalCeQueue).resetTasksWithUnknownWorkerUUIDs(any());
try {
underTest.startScheduling();
fail("the error should have been thrown");
} catch (Error e) {
assertThat(e).isSameAs(expected);
}
verify(mockedInternalCeQueue).resetTasksWithUnknownWorkerUUIDs(any());
}
@Test
public void startScheduling_must_call_the_lock_methods() {
InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class);
CeDistributedInformation mockedCeDistributedInformation = mockCeDistributedInformation(jobLock);
CeCleaningSchedulerImpl underTest = mockCeCleaningSchedulerImpl(mockedInternalCeQueue, mockedCeDistributedInformation);
underTest.startScheduling();
verify(mockedCeDistributedInformation, times(1)).acquireCleanJobLock();
verify(jobLock, times(1)).tryLock();
verify(jobLock, times(1)).unlock();
}
@Test
public void startScheduling_must_not_execute_method_if_lock_is_already_acquired() {
InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class);
CeDistributedInformation mockedCeDistributedInformation = mockCeDistributedInformation(jobLock);
when(jobLock.tryLock()).thenReturn(false);
CeCleaningSchedulerImpl underTest = mockCeCleaningSchedulerImpl(mockedInternalCeQueue, mockedCeDistributedInformation);
underTest.startScheduling();
verify(mockedCeDistributedInformation, times(1)).acquireCleanJobLock();
verify(jobLock, times(1)).tryLock();
// since lock cannot be locked, unlock method is not been called
verify(jobLock, times(0)).unlock();
// since lock cannot be locked, cleaning job methods must not be called
verify(mockedInternalCeQueue, times(0)).resetTasksWithUnknownWorkerUUIDs(any());
}
@Test
public void startScheduling_calls_cleaning_methods_of_internalCeQueue_at_fixed_rate_with_value_from_CeConfiguration() {
InternalCeQueue mockedInternalCeQueue = mock(InternalCeQueue.class);
long wornOutInitialDelay = 10L;
long wornOutDelay = 20L;
long unknownWorkerInitialDelay = 11L;
long unknownWorkerDelay = 21L;
CeConfiguration mockedCeConfiguration = mockCeConfiguration(wornOutInitialDelay, wornOutDelay);
CeCleaningAdapter executorService = new CeCleaningAdapter() {
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initDelay, long period, TimeUnit unit) {
schedulerCounter++;
switch(schedulerCounter) {
case 1:
assertThat(initDelay).isEqualTo(wornOutInitialDelay);
assertThat(period).isEqualTo(wornOutDelay);
assertThat(unit).isEqualTo(TimeUnit.MINUTES);
break;
case 2:
assertThat(initDelay).isEqualTo(unknownWorkerInitialDelay);
assertThat(period).isEqualTo(unknownWorkerDelay);
assertThat(unit).isEqualTo(TimeUnit.MINUTES);
break;
default:
fail("Unknown call of scheduleWithFixedDelay");
}
// synchronously execute command
command.run();
return null;
}
};
CeCleaningSchedulerImpl underTest = new CeCleaningSchedulerImpl(executorService, mockedCeConfiguration,
mockedInternalCeQueue, mockCeDistributedInformation(jobLock));
underTest.startScheduling();
assertThat(executorService.schedulerCounter).isOne();
}
private CeConfiguration mockCeConfiguration(long cleanCeTasksInitialDelay, long cleanCeTasksDelay) {
CeConfiguration mockedCeConfiguration = mock(CeConfiguration.class);
when(mockedCeConfiguration.getCleanTasksInitialDelay()).thenReturn(cleanCeTasksInitialDelay);
when(mockedCeConfiguration.getCleanTasksDelay()).thenReturn(cleanCeTasksDelay);
return mockedCeConfiguration;
}
private CeCleaningSchedulerImpl mockCeCleaningSchedulerImpl(InternalCeQueue internalCeQueue, CeDistributedInformation ceDistributedInformation) {
return new CeCleaningSchedulerImpl(new CeCleaningAdapter() {
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
// synchronously execute command
command.run();
return null;
}
}, mockCeConfiguration(1, 10), internalCeQueue, ceDistributedInformation);
}
private CeDistributedInformation mockCeDistributedInformation(Lock result) {
CeDistributedInformation mocked = mock(CeDistributedInformation.class);
when(mocked.acquireCleanJobLock()).thenReturn(result);
when(result.tryLock()).thenReturn(true);
return mocked;
}
/**
* Implementation of {@link CeCleaningExecutorService} which throws {@link UnsupportedOperationException} for every
* method.
*/
private static class CeCleaningAdapter implements CeCleaningExecutorService {
protected int schedulerCounter = 0;
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public void shutdown() {
throw createUnsupportedOperationException();
}
@Override
public List<Runnable> shutdownNow() {
throw createUnsupportedOperationException();
}
@Override
public boolean isShutdown() {
throw createUnsupportedOperationException();
}
@Override
public boolean isTerminated() {
throw createUnsupportedOperationException();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public <T> Future<T> submit(Callable<T> task) {
throw createUnsupportedOperationException();
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
throw createUnsupportedOperationException();
}
@Override
public Future<?> submit(Runnable task) {
throw createUnsupportedOperationException();
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
throw createUnsupportedOperationException();
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) {
throw createUnsupportedOperationException();
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw createUnsupportedOperationException();
}
@Override
public void execute(Runnable command) {
throw createUnsupportedOperationException();
}
private UnsupportedOperationException createUnsupportedOperationException() {
return new UnsupportedOperationException("Unexpected call");
}
}
}
| 10,354 | 37.928571 | 147 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationImplTest.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.ce.configuration;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.config.internal.ConfigurationBridge;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import static java.lang.Math.abs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CeConfigurationImplTest {
public static final ConfigurationBridge EMPTY_CONFIGURATION = new ConfigurationBridge(new MapSettings());
private SimpleWorkerCountProvider workerCountProvider = new SimpleWorkerCountProvider();
@Test
public void getWorkerCount_returns_1_when_there_is_no_WorkerCountProvider() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getWorkerCount()).isOne();
}
@Test
public void getWorkerMaxCount_returns_1_when_there_is_no_WorkerCountProvider() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getWorkerMaxCount()).isOne();
}
@Test
public void getWorkerCount_returns_value_returned_by_WorkerCountProvider_when_available() {
int value = randomValidWorkerCount();
workerCountProvider.set(value);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getWorkerCount()).isEqualTo(value);
}
@Test
public void getWorkerMaxCount_returns_10_whichever_the_value_returned_by_WorkerCountProvider() {
int value = randomValidWorkerCount();
workerCountProvider.set(value);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getWorkerMaxCount()).isEqualTo(10);
}
@Test
public void constructor_throws_MessageException_when_WorkerCountProvider_returns_0() {
workerCountProvider.set(0);
assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider))
.isInstanceOf(MessageException.class)
.hasMessage("Worker count '0' is invalid. " +
"It must be an integer strictly greater than 0 and less or equal to 10");
}
@Test
public void constructor_throws_MessageException_when_WorkerCountProvider_returns_less_than_0() {
int value = -1 - abs(new Random().nextInt());
workerCountProvider.set(value);
assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider))
.isInstanceOf(MessageException.class)
.hasMessage("Worker count '" + value + "' is invalid. " +
"It must be an integer strictly greater than 0 and less or equal to 10");
}
@Test
public void constructor_throws_MessageException_when_WorkerCountProvider_returns_more_then_10() {
int value = 10 + abs(new Random().nextInt());
workerCountProvider.set(value);
assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider))
.isInstanceOf(MessageException.class)
.hasMessage("Worker count '" + value + "' is invalid. " +
"It must be an integer strictly greater than 0 and less or equal to 10");
}
@Test
public void getCleanCeTasksInitialDelay_returns_0() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getCleanTasksInitialDelay())
.isZero();
workerCountProvider.set(1);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getCleanTasksInitialDelay())
.isZero();
}
@Test
public void getCleanCeTasksDelay_returns_2() {
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION).getCleanTasksDelay())
.isEqualTo(2L);
workerCountProvider.set(1);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getCleanTasksDelay())
.isEqualTo(2L);
}
private static final class SimpleWorkerCountProvider implements WorkerCountProvider {
private int value = 0;
void set(int value) {
this.value = value;
}
@Override
public int get() {
return value;
}
}
private static int randomValidWorkerCount() {
return 1 + Math.abs(new Random().nextInt(10));
}
}
| 4,844 | 36.269231 | 116 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationRule.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.ce.configuration;
import org.junit.rules.ExternalResource;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Mutable implementation of {@link CeConfiguration} as {@link org.junit.Rule}.
*/
public class CeConfigurationRule extends ExternalResource implements CeConfiguration {
private int workerThreadCount = 1;
private int workerCount = 1;
private long queuePollingDelay = 2 * 1000L;
private long cleanTasksInitialDelay = 1L;
private long cleanTasksDelay = 10L;
@Override
public int getWorkerMaxCount() {
return workerThreadCount;
}
public void setWorkerThreadCount(int workerThreadCount) {
checkArgument(workerThreadCount >= 1, "worker thread count must be >= 1");
this.workerThreadCount = workerThreadCount;
}
@Override
public int getWorkerCount() {
return workerCount;
}
public CeConfigurationRule setWorkerCount(int workerCount) {
checkArgument(workerCount >= 1, "worker count must be >= 1");
this.workerCount = workerCount;
return this;
}
@Override
public long getQueuePollingDelay() {
return queuePollingDelay;
}
public void setQueuePollingDelay(int queuePollingDelay) {
checkArgument(queuePollingDelay > 0, "Queue polling delay must be >= 0");
this.queuePollingDelay = queuePollingDelay;
}
@Override
public long getCleanTasksInitialDelay() {
return cleanTasksInitialDelay;
}
public void setCleanTasksInitialDelay(long cleanTasksInitialDelay) {
checkArgument(cleanTasksInitialDelay > 0, "cancel worn-outs polling initial delay must be >= 1");
this.cleanTasksInitialDelay = cleanTasksInitialDelay;
}
@Override
public long getCleanTasksDelay() {
return cleanTasksDelay;
}
public void setCleanTasksDelay(long cleanTasksDelay) {
checkArgument(cleanTasksDelay > 0, "cancel worn-outs polling delay must be >= 1");
this.cleanTasksDelay = cleanTasksDelay;
}
@Override
public long getGracefulStopTimeoutInMs() {
return 6 * 60 * 60 * 1_000L;
}
}
| 2,875 | 30.26087 | 101 | java |
sonarqube | sonarqube-master/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeWorkerCountSettingWarningTest.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.ce.configuration;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
public class CeWorkerCountSettingWarningTest {
private static final String PROPERTY_SONAR_CE_WORKER_COUNT = "sonar.ce.workerCount";
@Rule
public LogTester logTester = new LogTester();
private MapSettings settings = new MapSettings();
private CeWorkerCountSettingWarning underTest = new CeWorkerCountSettingWarning(settings.asConfig());
@Test
public void start_does_not_log_anything_if_there_is_no_settings() {
underTest.start();
assertThat(logTester.logs()).isEmpty();
}
@Test
public void start_logs_a_warning_if_property_workerCount_exists_and_empty() {
settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, "");
underTest.start();
verifyWarnMessage();
}
@Test
public void start_logs_a_warning_if_property_ceWorkerCount_exists_with_a_value() {
settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, randomAlphabetic(12));
underTest.start();
verifyWarnMessage();
}
private void verifyWarnMessage() {
assertThat(logTester.logs()).hasSize(1);
assertThat(logTester.logs(Level.WARN)).containsOnly("Property sonar.ce.workerCount is not supported anymore and will be ignored." +
" Remove it from sonar.properties to remove this warning.");
}
}
| 2,413 | 33 | 135 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.