You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InternalCeQueueImpl.java 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.ce.queue;
  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;
  23. import java.io.OutputStream;
  24. import java.io.PrintWriter;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Optional;
  28. import java.util.Set;
  29. import javax.annotation.CheckForNull;
  30. import javax.annotation.Nullable;
  31. import org.sonar.api.ce.ComputeEngineSide;
  32. import org.sonar.api.utils.System2;
  33. import org.sonar.api.utils.log.Logger;
  34. import org.sonar.api.utils.log.Loggers;
  35. import org.sonar.ce.container.ComputeEngineStatus;
  36. import org.sonar.ce.monitoring.CEQueueStatus;
  37. import org.sonar.ce.task.CeTask;
  38. import org.sonar.ce.task.CeTaskResult;
  39. import org.sonar.ce.task.TypedException;
  40. import org.sonar.ce.task.projectanalysis.component.VisitException;
  41. import org.sonar.core.util.UuidFactory;
  42. import org.sonar.db.DbClient;
  43. import org.sonar.db.DbSession;
  44. import org.sonar.db.ce.CeActivityDto;
  45. import org.sonar.db.ce.CeQueueDao;
  46. import org.sonar.db.ce.CeQueueDto;
  47. import org.sonar.db.ce.CeTaskCharacteristicDto;
  48. import org.sonar.db.component.ComponentDto;
  49. import static com.google.common.base.Preconditions.checkArgument;
  50. import static java.lang.String.format;
  51. import static java.util.Collections.singletonList;
  52. import static java.util.Objects.requireNonNull;
  53. import static java.util.Optional.ofNullable;
  54. import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
  55. @ComputeEngineSide
  56. public class InternalCeQueueImpl extends CeQueueImpl implements InternalCeQueue {
  57. private static final Logger LOG = Loggers.get(InternalCeQueueImpl.class);
  58. private final DbClient dbClient;
  59. private final CEQueueStatus queueStatus;
  60. private final ComputeEngineStatus computeEngineStatus;
  61. public InternalCeQueueImpl(System2 system2, DbClient dbClient, UuidFactory uuidFactory, CEQueueStatus queueStatus,
  62. ComputeEngineStatus computeEngineStatus) {
  63. super(system2, dbClient, uuidFactory);
  64. this.dbClient = dbClient;
  65. this.queueStatus = queueStatus;
  66. this.computeEngineStatus = computeEngineStatus;
  67. }
  68. @Override
  69. public Optional<CeTask> peek(String workerUuid, boolean excludeIndexationJob) {
  70. requireNonNull(workerUuid, "workerUuid can't be null");
  71. if (computeEngineStatus.getStatus() != ComputeEngineStatus.Status.STARTED || getWorkersPauseStatus() != WorkersPauseStatus.RESUMED) {
  72. return Optional.empty();
  73. }
  74. try (DbSession dbSession = dbClient.openSession(false)) {
  75. CeQueueDao ceQueueDao = dbClient.ceQueueDao();
  76. int i = ceQueueDao.resetToPendingForWorker(dbSession, workerUuid);
  77. if (i > 0) {
  78. dbSession.commit();
  79. LOG.debug("{} in progress tasks reset for worker uuid {}", i, workerUuid);
  80. }
  81. Optional<CeQueueDto> opt = findPendingTask(workerUuid, dbSession, ceQueueDao, excludeIndexationJob);
  82. if (!opt.isPresent()) {
  83. return Optional.empty();
  84. }
  85. CeQueueDto taskDto = opt.get();
  86. Map<String, ComponentDto> componentsByUuid = loadComponentDtos(dbSession, taskDto);
  87. Map<String, String> characteristics = dbClient.ceTaskCharacteristicsDao().selectByTaskUuids(dbSession, singletonList(taskDto.getUuid())).stream()
  88. .collect(uniqueIndex(CeTaskCharacteristicDto::getKey, CeTaskCharacteristicDto::getValue));
  89. CeTask task = convertToTask(dbSession, taskDto, characteristics,
  90. ofNullable(taskDto.getComponentUuid()).map(componentsByUuid::get).orElse(null),
  91. ofNullable(taskDto.getMainComponentUuid()).map(componentsByUuid::get).orElse(null));
  92. queueStatus.addInProgress();
  93. return Optional.of(task);
  94. }
  95. }
  96. private static Optional<CeQueueDto> findPendingTask(String workerUuid, DbSession dbSession, CeQueueDao ceQueueDao, boolean excludeIndexationJob) {
  97. // try to find tasks including indexation job & excluding app/portfolio
  98. // and if no match, try the opposite
  99. // when excludeIndexationJob is false, search first excluding indexation jobs and including app/portfolio, then the opposite
  100. Optional<CeQueueDto> opt = ceQueueDao.peek(dbSession, workerUuid, excludeIndexationJob, !excludeIndexationJob);
  101. if (!opt.isPresent()) {
  102. opt = ceQueueDao.peek(dbSession, workerUuid, !excludeIndexationJob, excludeIndexationJob);
  103. }
  104. return opt;
  105. }
  106. @Override
  107. public void remove(CeTask task, CeActivityDto.Status status, @Nullable CeTaskResult taskResult, @Nullable Throwable error) {
  108. checkArgument(error == null || status == CeActivityDto.Status.FAILED, "Error can be provided only when status is FAILED");
  109. long executionTimeInMs = 0L;
  110. try (DbSession dbSession = dbClient.openSession(false)) {
  111. CeQueueDto queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, task.getUuid())
  112. .orElseThrow(() -> new IllegalStateException("Task does not exist anymore: " + task));
  113. CeActivityDto activityDto = new CeActivityDto(queueDto);
  114. activityDto.setStatus(status);
  115. executionTimeInMs = updateExecutionFields(activityDto);
  116. updateTaskResult(activityDto, taskResult);
  117. updateError(activityDto, error);
  118. remove(dbSession, queueDto, activityDto);
  119. } finally {
  120. updateQueueStatus(status, executionTimeInMs);
  121. }
  122. }
  123. private void updateQueueStatus(CeActivityDto.Status status, long executionTimeInMs) {
  124. if (status == CeActivityDto.Status.SUCCESS) {
  125. queueStatus.addSuccess(executionTimeInMs);
  126. } else {
  127. queueStatus.addError(executionTimeInMs);
  128. }
  129. }
  130. private static void updateTaskResult(CeActivityDto activityDto, @Nullable CeTaskResult taskResult) {
  131. if (taskResult != null) {
  132. Optional<String> analysisUuid = taskResult.getAnalysisUuid();
  133. analysisUuid.ifPresent(activityDto::setAnalysisUuid);
  134. }
  135. }
  136. private static void updateError(CeActivityDto activityDto, @Nullable Throwable error) {
  137. if (error == null) {
  138. return;
  139. }
  140. if (error instanceof VisitException && error.getCause() != null) {
  141. activityDto.setErrorMessage(format("%s (%s)", error.getCause().getMessage(), error.getMessage()));
  142. } else {
  143. activityDto.setErrorMessage(error.getMessage());
  144. }
  145. String stacktrace = getStackTraceForPersistence(error);
  146. if (stacktrace != null) {
  147. activityDto.setErrorStacktrace(stacktrace);
  148. }
  149. if (error instanceof TypedException) {
  150. activityDto.setErrorType(((TypedException) error).getType());
  151. }
  152. }
  153. @CheckForNull
  154. private static String getStackTraceForPersistence(Throwable error) {
  155. try (ByteArrayOutputStream out = new ByteArrayOutputStream();
  156. LineReturnEnforcedPrintStream printStream = new LineReturnEnforcedPrintStream(out)) {
  157. error.printStackTrace(printStream);
  158. printStream.flush();
  159. return out.toString();
  160. } catch (IOException e) {
  161. LOG.debug("Failed to getStacktrace out of error", e);
  162. return null;
  163. }
  164. }
  165. @Override
  166. public void cancelWornOuts() {
  167. try (DbSession dbSession = dbClient.openSession(false)) {
  168. List<CeQueueDto> wornOutTasks = dbClient.ceQueueDao().selectWornout(dbSession);
  169. wornOutTasks.forEach(queueDto -> {
  170. CeActivityDto activityDto = new CeActivityDto(queueDto);
  171. activityDto.setStatus(CeActivityDto.Status.CANCELED);
  172. updateExecutionFields(activityDto);
  173. remove(dbSession, queueDto, activityDto);
  174. });
  175. }
  176. }
  177. @Override
  178. public void resetTasksWithUnknownWorkerUUIDs(Set<String> knownWorkerUUIDs) {
  179. try (DbSession dbSession = dbClient.openSession(false)) {
  180. dbClient.ceQueueDao().resetTasksWithUnknownWorkerUUIDs(dbSession, knownWorkerUUIDs);
  181. dbSession.commit();
  182. }
  183. }
  184. /**
  185. * A {@link PrintWriter} subclass which enforces that line returns are {@code \n} whichever the platform.
  186. */
  187. private static class LineReturnEnforcedPrintStream extends PrintWriter {
  188. LineReturnEnforcedPrintStream(OutputStream out) {
  189. super(out);
  190. }
  191. @Override
  192. public void println() {
  193. super.print('\n');
  194. }
  195. @Override
  196. public void println(boolean x) {
  197. super.print(x);
  198. println();
  199. }
  200. @Override
  201. public void println(char x) {
  202. super.print(x);
  203. println();
  204. }
  205. @Override
  206. public void println(int x) {
  207. super.print(x);
  208. println();
  209. }
  210. @Override
  211. public void println(long x) {
  212. super.print(x);
  213. println();
  214. }
  215. @Override
  216. public void println(float x) {
  217. super.print(x);
  218. println();
  219. }
  220. @Override
  221. public void println(double x) {
  222. super.print(x);
  223. println();
  224. }
  225. @Override
  226. public void println(char[] x) {
  227. super.print(x);
  228. println();
  229. }
  230. @Override
  231. public void println(String x) {
  232. super.print(x);
  233. println();
  234. }
  235. @Override
  236. public void println(Object x) {
  237. super.print(x);
  238. println();
  239. }
  240. }
  241. }