JobList.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\BackgroundJob;
  8. use OCP\AppFramework\QueryException;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\AutoloadNotAllowedException;
  11. use OCP\BackgroundJob\IJob;
  12. use OCP\BackgroundJob\IJobList;
  13. use OCP\BackgroundJob\IParallelAwareJob;
  14. use OCP\DB\Exception;
  15. use OCP\DB\QueryBuilder\IQueryBuilder;
  16. use OCP\IConfig;
  17. use OCP\IDBConnection;
  18. use Psr\Log\LoggerInterface;
  19. use function get_class;
  20. use function json_encode;
  21. use function md5;
  22. use function strlen;
  23. class JobList implements IJobList {
  24. protected IDBConnection $connection;
  25. protected IConfig $config;
  26. protected ITimeFactory $timeFactory;
  27. protected LoggerInterface $logger;
  28. public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory, LoggerInterface $logger) {
  29. $this->connection = $connection;
  30. $this->config = $config;
  31. $this->timeFactory = $timeFactory;
  32. $this->logger = $logger;
  33. }
  34. public function add($job, $argument = null, ?int $firstCheck = null): void {
  35. if ($firstCheck === null) {
  36. $firstCheck = $this->timeFactory->getTime();
  37. }
  38. if ($job instanceof IJob) {
  39. $class = get_class($job);
  40. } else {
  41. $class = $job;
  42. }
  43. $argumentJson = json_encode($argument);
  44. if (strlen($argumentJson) > 4000) {
  45. throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
  46. }
  47. $query = $this->connection->getQueryBuilder();
  48. if (!$this->has($job, $argument)) {
  49. $query->insert('jobs')
  50. ->values([
  51. 'class' => $query->createNamedParameter($class),
  52. 'argument' => $query->createNamedParameter($argumentJson),
  53. 'argument_hash' => $query->createNamedParameter(md5($argumentJson)),
  54. 'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
  55. 'last_checked' => $query->createNamedParameter($firstCheck, IQueryBuilder::PARAM_INT),
  56. ]);
  57. } else {
  58. $query->update('jobs')
  59. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  60. ->set('last_checked', $query->createNamedParameter($firstCheck, IQueryBuilder::PARAM_INT))
  61. ->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  62. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  63. ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
  64. }
  65. $query->executeStatement();
  66. }
  67. public function scheduleAfter(string $job, int $runAfter, $argument = null): void {
  68. $this->add($job, $argument, $runAfter);
  69. }
  70. /**
  71. * @param IJob|string $job
  72. * @param mixed $argument
  73. */
  74. public function remove($job, $argument = null): void {
  75. if ($job instanceof IJob) {
  76. $class = get_class($job);
  77. } else {
  78. $class = $job;
  79. }
  80. $query = $this->connection->getQueryBuilder();
  81. $query->delete('jobs')
  82. ->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  83. if (!is_null($argument)) {
  84. $argumentJson = json_encode($argument);
  85. $query->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
  86. }
  87. // Add galera safe delete chunking if using mysql
  88. // Stops us hitting wsrep_max_ws_rows when large row counts are deleted
  89. if ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL) {
  90. // Then use chunked delete
  91. $max = IQueryBuilder::MAX_ROW_DELETION;
  92. $query->setMaxResults($max);
  93. do {
  94. $deleted = $query->execute();
  95. } while ($deleted === $max);
  96. } else {
  97. // Dont use chunked delete - let the DB handle the large row count natively
  98. $query->execute();
  99. }
  100. }
  101. public function removeById(int $id): void {
  102. $query = $this->connection->getQueryBuilder();
  103. $query->delete('jobs')
  104. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  105. $query->executeStatement();
  106. }
  107. /**
  108. * check if a job is in the list
  109. *
  110. * @param IJob|class-string<IJob> $job
  111. * @param mixed $argument
  112. */
  113. public function has($job, $argument): bool {
  114. if ($job instanceof IJob) {
  115. $class = get_class($job);
  116. } else {
  117. $class = $job;
  118. }
  119. $argument = json_encode($argument);
  120. $query = $this->connection->getQueryBuilder();
  121. $query->select('id')
  122. ->from('jobs')
  123. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  124. ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argument))))
  125. ->setMaxResults(1);
  126. $result = $query->executeQuery();
  127. $row = $result->fetch();
  128. $result->closeCursor();
  129. return (bool) $row;
  130. }
  131. public function getJobs($job, ?int $limit, int $offset): array {
  132. $iterable = $this->getJobsIterator($job, $limit, $offset);
  133. if (is_array($iterable)) {
  134. return $iterable;
  135. } else {
  136. return iterator_to_array($iterable);
  137. }
  138. }
  139. /**
  140. * @param IJob|class-string<IJob>|null $job
  141. * @return iterable<IJob> Avoid to store these objects as they may share a Singleton instance. You should instead use these IJobs instances while looping on the iterable.
  142. */
  143. public function getJobsIterator($job, ?int $limit, int $offset): iterable {
  144. $query = $this->connection->getQueryBuilder();
  145. $query->select('*')
  146. ->from('jobs')
  147. ->setMaxResults($limit)
  148. ->setFirstResult($offset);
  149. if ($job !== null) {
  150. if ($job instanceof IJob) {
  151. $class = get_class($job);
  152. } else {
  153. $class = $job;
  154. }
  155. $query->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  156. }
  157. $result = $query->executeQuery();
  158. while ($row = $result->fetch()) {
  159. $job = $this->buildJob($row);
  160. if ($job) {
  161. yield $job;
  162. }
  163. }
  164. $result->closeCursor();
  165. }
  166. /**
  167. * @inheritDoc
  168. */
  169. public function getNext(bool $onlyTimeSensitive = false, ?array $jobClasses = null): ?IJob {
  170. $query = $this->connection->getQueryBuilder();
  171. $query->select('*')
  172. ->from('jobs')
  173. ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
  174. ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
  175. ->orderBy('last_checked', 'ASC')
  176. ->setMaxResults(1);
  177. if ($onlyTimeSensitive) {
  178. $query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
  179. }
  180. if (!empty($jobClasses)) {
  181. $orClasses = [];
  182. foreach ($jobClasses as $jobClass) {
  183. $orClasses[] = $query->expr()->eq('class', $query->createNamedParameter($jobClass, IQueryBuilder::PARAM_STR));
  184. }
  185. $query->andWhere($query->expr()->orX(...$orClasses));
  186. }
  187. $result = $query->executeQuery();
  188. $row = $result->fetch();
  189. $result->closeCursor();
  190. if ($row) {
  191. $job = $this->buildJob($row);
  192. if ($job instanceof IParallelAwareJob && !$job->getAllowParallelRuns() && $this->hasReservedJob(get_class($job))) {
  193. $this->logger->info('Skipping ' . get_class($job) . ' job with ID ' . $job->getId() . ' because another job with the same class is already running', ['app' => 'cron']);
  194. $update = $this->connection->getQueryBuilder();
  195. $update->update('jobs')
  196. ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime() + 1))
  197. ->where($update->expr()->eq('id', $update->createParameter('jobid')));
  198. $update->setParameter('jobid', $row['id']);
  199. $update->executeStatement();
  200. return $this->getNext($onlyTimeSensitive);
  201. }
  202. $update = $this->connection->getQueryBuilder();
  203. $update->update('jobs')
  204. ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
  205. ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
  206. ->where($update->expr()->eq('id', $update->createParameter('jobid')))
  207. ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
  208. ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
  209. $update->setParameter('jobid', $row['id']);
  210. $update->setParameter('reserved_at', $row['reserved_at']);
  211. $update->setParameter('last_checked', $row['last_checked']);
  212. $count = $update->executeStatement();
  213. if ($count === 0) {
  214. // Background job already executed elsewhere, try again.
  215. return $this->getNext($onlyTimeSensitive, $jobClasses);
  216. }
  217. if ($job === null) {
  218. // set the last_checked to 12h in the future to not check failing jobs all over again
  219. $reset = $this->connection->getQueryBuilder();
  220. $reset->update('jobs')
  221. ->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
  222. ->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
  223. ->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
  224. $reset->executeStatement();
  225. // Background job from disabled app, try again.
  226. return $this->getNext($onlyTimeSensitive, $jobClasses);
  227. }
  228. return $job;
  229. } else {
  230. return null;
  231. }
  232. }
  233. /**
  234. * @return ?IJob The job matching the id. Beware that this object may be a singleton and may be modified by the next call to buildJob.
  235. */
  236. public function getById(int $id): ?IJob {
  237. $row = $this->getDetailsById($id);
  238. if ($row) {
  239. return $this->buildJob($row);
  240. }
  241. return null;
  242. }
  243. public function getDetailsById(int $id): ?array {
  244. $query = $this->connection->getQueryBuilder();
  245. $query->select('*')
  246. ->from('jobs')
  247. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  248. $result = $query->executeQuery();
  249. $row = $result->fetch();
  250. $result->closeCursor();
  251. if ($row) {
  252. return $row;
  253. }
  254. return null;
  255. }
  256. /**
  257. * get the job object from a row in the db
  258. *
  259. * @param array{class:class-string<IJob>, id:mixed, last_run:mixed, argument:string} $row
  260. * @return ?IJob the next job to run. Beware that this object may be a singleton and may be modified by the next call to buildJob.
  261. */
  262. private function buildJob(array $row): ?IJob {
  263. try {
  264. try {
  265. // Try to load the job as a service
  266. /** @var IJob $job */
  267. $job = \OCP\Server::get($row['class']);
  268. } catch (QueryException $e) {
  269. if (class_exists($row['class'])) {
  270. $class = $row['class'];
  271. $job = new $class();
  272. } else {
  273. // Remove job from disabled app or old version of an app
  274. $this->removeById($row['id']);
  275. return null;
  276. }
  277. }
  278. if (!($job instanceof IJob)) {
  279. // This most likely means an invalid job was enqueued. We can ignore it.
  280. return null;
  281. }
  282. $job->setId((int) $row['id']);
  283. $job->setLastRun((int) $row['last_run']);
  284. $job->setArgument(json_decode($row['argument'], true));
  285. return $job;
  286. } catch (AutoloadNotAllowedException $e) {
  287. // job is from a disabled app, ignore
  288. return null;
  289. }
  290. }
  291. /**
  292. * set the job that was last ran
  293. */
  294. public function setLastJob(IJob $job): void {
  295. $this->unlockJob($job);
  296. $this->config->setAppValue('backgroundjob', 'lastjob', (string)$job->getId());
  297. }
  298. /**
  299. * Remove the reservation for a job
  300. */
  301. public function unlockJob(IJob $job): void {
  302. $query = $this->connection->getQueryBuilder();
  303. $query->update('jobs')
  304. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  305. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  306. $query->executeStatement();
  307. }
  308. /**
  309. * set the lastRun of $job to now
  310. */
  311. public function setLastRun(IJob $job): void {
  312. $query = $this->connection->getQueryBuilder();
  313. $query->update('jobs')
  314. ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  315. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  316. if ($job instanceof \OCP\BackgroundJob\TimedJob
  317. && !$job->isTimeSensitive()) {
  318. $query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
  319. }
  320. $query->executeStatement();
  321. }
  322. /**
  323. * @param int $timeTaken
  324. */
  325. public function setExecutionTime(IJob $job, $timeTaken): void {
  326. $query = $this->connection->getQueryBuilder();
  327. $query->update('jobs')
  328. ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
  329. ->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  330. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  331. $query->executeStatement();
  332. }
  333. /**
  334. * Reset the $job so it executes on the next trigger
  335. *
  336. * @since 23.0.0
  337. */
  338. public function resetBackgroundJob(IJob $job): void {
  339. $query = $this->connection->getQueryBuilder();
  340. $query->update('jobs')
  341. ->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  342. ->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  343. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
  344. $query->executeStatement();
  345. }
  346. public function hasReservedJob(?string $className = null): bool {
  347. $query = $this->connection->getQueryBuilder();
  348. $query->select('*')
  349. ->from('jobs')
  350. ->where($query->expr()->gt('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 6 * 3600, IQueryBuilder::PARAM_INT)))
  351. ->setMaxResults(1);
  352. if ($className !== null) {
  353. $query->andWhere($query->expr()->eq('class', $query->createNamedParameter($className)));
  354. }
  355. try {
  356. $result = $query->executeQuery();
  357. $hasReservedJobs = $result->fetch() !== false;
  358. $result->closeCursor();
  359. return $hasReservedJobs;
  360. } catch (Exception $e) {
  361. $this->logger->debug('Querying reserved jobs failed', ['exception' => $e]);
  362. return false;
  363. }
  364. }
  365. public function countByClass(): array {
  366. $query = $this->connection->getQueryBuilder();
  367. $query->select('class')
  368. ->selectAlias($query->func()->count('id'), 'count')
  369. ->from('jobs')
  370. ->orderBy('count')
  371. ->groupBy('class');
  372. $result = $query->executeQuery();
  373. $jobs = [];
  374. while (($row = $result->fetch()) !== false) {
  375. /**
  376. * @var array{count:int, class:class-string} $row
  377. */
  378. $jobs[] = $row;
  379. }
  380. return $jobs;
  381. }
  382. }