1
0

JobList.php 14 KB

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