JobList.php 14 KB

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