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.

NextPendingTaskPicker.java 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.util.HashSet;
  22. import java.util.List;
  23. import java.util.Objects;
  24. import java.util.Optional;
  25. import java.util.Set;
  26. import javax.annotation.Nullable;
  27. import org.apache.commons.lang3.ObjectUtils;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import org.sonar.api.ce.ComputeEngineSide;
  31. import org.sonar.api.config.Configuration;
  32. import org.sonar.core.config.ComputeEngineProperties;
  33. import org.sonar.db.DbClient;
  34. import org.sonar.db.DbSession;
  35. import org.sonar.db.ce.CeQueueDao;
  36. import org.sonar.db.ce.CeQueueDto;
  37. import org.sonar.db.ce.CeTaskDtoLight;
  38. import org.sonar.db.ce.PrOrBranchTask;
  39. import static org.sonar.core.ce.CeTaskCharacteristics.BRANCH;
  40. import static org.sonar.core.ce.CeTaskCharacteristics.PULL_REQUEST;
  41. @ComputeEngineSide
  42. public class NextPendingTaskPicker {
  43. private static final Logger LOG = LoggerFactory.getLogger(NextPendingTaskPicker.class);
  44. private final Configuration config;
  45. private final CeQueueDao ceQueueDao;
  46. public NextPendingTaskPicker(Configuration config, DbClient dbClient) {
  47. this.config = config;
  48. this.ceQueueDao = dbClient.ceQueueDao();
  49. }
  50. Optional<CeQueueDto> findPendingTask(String workerUuid, DbSession dbSession, boolean prioritizeAnalysisAndRefresh) {
  51. // try to find tasks including indexing job & excluding app/portfolio and if no match, try the opposite
  52. // when prioritizeAnalysisAndRefresh is false, search first excluding indexing jobs and including app/portfolio, then the opposite
  53. Optional<CeTaskDtoLight> eligibleForPeek = ceQueueDao.selectEligibleForPeek(dbSession, prioritizeAnalysisAndRefresh, !prioritizeAnalysisAndRefresh);
  54. Optional<CeTaskDtoLight> eligibleForPeekInParallel = eligibleForPeekInParallel(dbSession);
  55. if (eligibleForPeek.isPresent() || eligibleForPeekInParallel.isPresent()) {
  56. return submitOldest(dbSession, workerUuid, eligibleForPeek.orElse(null), eligibleForPeekInParallel.orElse(null));
  57. }
  58. eligibleForPeek = ceQueueDao.selectEligibleForPeek(dbSession, !prioritizeAnalysisAndRefresh, prioritizeAnalysisAndRefresh);
  59. if (eligibleForPeek.isPresent()) {
  60. return ceQueueDao.tryToPeek(dbSession, eligibleForPeek.get().getCeTaskUuid(), workerUuid);
  61. }
  62. return Optional.empty();
  63. }
  64. /**
  65. * priority is always given to the task that is waiting longer - to avoid starvation
  66. */
  67. private Optional<CeQueueDto> submitOldest(DbSession session, String workerUuid, @Nullable CeTaskDtoLight eligibleForPeek, @Nullable CeTaskDtoLight eligibleForPeekInParallel) {
  68. CeTaskDtoLight oldest = ObjectUtils.min(eligibleForPeek, eligibleForPeekInParallel);
  69. Optional<CeQueueDto> ceQueueDto = ceQueueDao.tryToPeek(session, oldest.getCeTaskUuid(), workerUuid);
  70. if (!Objects.equals(oldest, eligibleForPeek)) {
  71. ceQueueDto.ifPresent(t -> LOG.info("Task [uuid = " + t.getUuid() + "] will be run concurrently with other tasks for the same project"));
  72. }
  73. return ceQueueDto;
  74. }
  75. Optional<CeTaskDtoLight> eligibleForPeekInParallel(DbSession dbSession) {
  76. Optional<Boolean> parallelProjectTasksEnabled = config.getBoolean(ComputeEngineProperties.CE_PARALLEL_PROJECT_TASKS_ENABLED);
  77. if (parallelProjectTasksEnabled.isPresent() && Boolean.TRUE.equals(parallelProjectTasksEnabled.get())) {
  78. return findPendingConcurrentCandidateTasks(ceQueueDao, dbSession);
  79. }
  80. return Optional.empty();
  81. }
  82. /**
  83. * Some of the tasks of the same project (mostly PRs) can be assigned and executed on workers at the same time/concurrently.
  84. * We look for them in this method.
  85. */
  86. private static Optional<CeTaskDtoLight> findPendingConcurrentCandidateTasks(CeQueueDao ceQueueDao, DbSession session) {
  87. List<PrOrBranchTask> queuedPrOrBranches = filterOldestPerProject(ceQueueDao.selectOldestPendingPrOrBranch(session));
  88. List<PrOrBranchTask> inProgressTasks = ceQueueDao.selectInProgressWithCharacteristics(session);
  89. for (PrOrBranchTask task : queuedPrOrBranches) {
  90. if ((Objects.equals(task.getBranchType(), PULL_REQUEST) && canRunPr(task, inProgressTasks))
  91. || (Objects.equals(task.getBranchType(), BRANCH) && canRunBranch(task, inProgressTasks))) {
  92. return Optional.of(task);
  93. }
  94. }
  95. return Optional.empty();
  96. }
  97. private static List<PrOrBranchTask> filterOldestPerProject(List<PrOrBranchTask> queuedPrOrBranches) {
  98. Set<String> entityUuidsSeen = new HashSet<>();
  99. return queuedPrOrBranches.stream().filter(t -> entityUuidsSeen.add(t.getEntityUuid())).toList();
  100. }
  101. /**
  102. * Branches cannot be run concurrently at this moment with other branches. And branches can already be returned in
  103. * {@link CeQueueDao#selectEligibleForPeek(org.sonar.db.DbSession, boolean, boolean)}. But we need this method because branches can be
  104. * assigned to a worker in a situation where the only type of in-progress tasks for a given project are {@link #PULLREQUEST_TYPE}.
  105. * <p>
  106. * This method returns the longest waiting branch in the queue which can be scheduled concurrently with pull requests.
  107. */
  108. private static boolean canRunBranch(PrOrBranchTask task, List<PrOrBranchTask> inProgress) {
  109. String entityUuid = task.getEntityUuid();
  110. List<PrOrBranchTask> sameComponentTasks = inProgress.stream()
  111. .filter(t -> Objects.equals(t.getEntityUuid(), entityUuid))
  112. .toList();
  113. //we can peek branch analysis task only if all the other in progress tasks for this component uuid are pull requests
  114. return sameComponentTasks.stream().map(PrOrBranchTask::getBranchType).allMatch(s -> Objects.equals(s, PULL_REQUEST));
  115. }
  116. /**
  117. * Queued pull requests can almost always be assigned to worker unless there is already PR running with the same ID (text_value column)
  118. * and for the same project. We look for the one that waits for the longest time.
  119. */
  120. private static boolean canRunPr(PrOrBranchTask task, List<PrOrBranchTask> inProgress) {
  121. // return true unless the same PR is already in progress
  122. return inProgress.stream()
  123. .noneMatch(pr -> Objects.equals(pr.getEntityUuid(), task.getEntityUuid())
  124. && Objects.equals(pr.getBranchType(), PULL_REQUEST)
  125. && Objects.equals(pr.getComponentUuid(), task.getComponentUuid()));
  126. }
  127. }