1
0

JobList.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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\DB\Exception;
  38. use OCP\DB\QueryBuilder\IQueryBuilder;
  39. use OCP\IConfig;
  40. use OCP\IDBConnection;
  41. use Psr\Log\LoggerInterface;
  42. class JobList implements IJobList {
  43. protected IDBConnection $connection;
  44. protected IConfig $config;
  45. protected ITimeFactory $timeFactory;
  46. protected LoggerInterface $logger;
  47. public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory, LoggerInterface $logger) {
  48. $this->connection = $connection;
  49. $this->config = $config;
  50. $this->timeFactory = $timeFactory;
  51. $this->logger = $logger;
  52. }
  53. /**
  54. * @param IJob|class-string<IJob> $job
  55. * @param mixed $argument
  56. */
  57. public function add($job, $argument = null): void {
  58. if ($job instanceof IJob) {
  59. $class = get_class($job);
  60. } else {
  61. $class = $job;
  62. }
  63. $argumentJson = json_encode($argument);
  64. if (strlen($argumentJson) > 4000) {
  65. throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
  66. }
  67. $query = $this->connection->getQueryBuilder();
  68. if (!$this->has($job, $argument)) {
  69. $query->insert('jobs')
  70. ->values([
  71. 'class' => $query->createNamedParameter($class),
  72. 'argument' => $query->createNamedParameter($argumentJson),
  73. 'argument_hash' => $query->createNamedParameter(md5($argumentJson)),
  74. 'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
  75. 'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
  76. ]);
  77. } else {
  78. $query->update('jobs')
  79. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  80. ->set('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT))
  81. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  82. ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
  83. }
  84. $query->executeStatement();
  85. }
  86. /**
  87. * @param IJob|string $job
  88. * @param mixed $argument
  89. */
  90. public function remove($job, $argument = null): void {
  91. if ($job instanceof IJob) {
  92. $class = get_class($job);
  93. } else {
  94. $class = $job;
  95. }
  96. $query = $this->connection->getQueryBuilder();
  97. $query->delete('jobs')
  98. ->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  99. if (!is_null($argument)) {
  100. $argumentJson = json_encode($argument);
  101. $query->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
  102. }
  103. // Add galera safe delete chunking if using mysql
  104. // Stops us hitting wsrep_max_ws_rows when large row counts are deleted
  105. if ($this->connection->getDatabasePlatform() instanceof MySQLPlatform) {
  106. // Then use chunked delete
  107. $max = IQueryBuilder::MAX_ROW_DELETION;
  108. $query->setMaxResults($max);
  109. do {
  110. $deleted = $query->execute();
  111. } while ($deleted === $max);
  112. } else {
  113. // Dont use chunked delete - let the DB handle the large row count natively
  114. $query->execute();
  115. }
  116. }
  117. protected function removeById(int $id): void {
  118. $query = $this->connection->getQueryBuilder();
  119. $query->delete('jobs')
  120. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  121. $query->executeStatement();
  122. }
  123. /**
  124. * check if a job is in the list
  125. *
  126. * @param IJob|class-string<IJob> $job
  127. * @param mixed $argument
  128. */
  129. public function has($job, $argument): bool {
  130. if ($job instanceof IJob) {
  131. $class = get_class($job);
  132. } else {
  133. $class = $job;
  134. }
  135. $argument = json_encode($argument);
  136. $query = $this->connection->getQueryBuilder();
  137. $query->select('id')
  138. ->from('jobs')
  139. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  140. ->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argument))))
  141. ->setMaxResults(1);
  142. $result = $query->executeQuery();
  143. $row = $result->fetch();
  144. $result->closeCursor();
  145. return (bool) $row;
  146. }
  147. public function getJobs($job, ?int $limit, int $offset): array {
  148. $iterable = $this->getJobsIterator($job, $limit, $offset);
  149. if (is_array($iterable)) {
  150. return $iterable;
  151. } else {
  152. return iterator_to_array($iterable);
  153. }
  154. }
  155. /**
  156. * @param IJob|class-string<IJob>|null $job
  157. * @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.
  158. */
  159. public function getJobsIterator($job, ?int $limit, int $offset): iterable {
  160. $query = $this->connection->getQueryBuilder();
  161. $query->select('*')
  162. ->from('jobs')
  163. ->setMaxResults($limit)
  164. ->setFirstResult($offset);
  165. if ($job !== null) {
  166. if ($job instanceof IJob) {
  167. $class = get_class($job);
  168. } else {
  169. $class = $job;
  170. }
  171. $query->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  172. }
  173. $result = $query->executeQuery();
  174. while ($row = $result->fetch()) {
  175. $job = $this->buildJob($row);
  176. if ($job) {
  177. yield $job;
  178. }
  179. }
  180. $result->closeCursor();
  181. }
  182. /**
  183. * Get the next job in the list
  184. * @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.
  185. */
  186. public function getNext(bool $onlyTimeSensitive = false): ?IJob {
  187. $query = $this->connection->getQueryBuilder();
  188. $query->select('*')
  189. ->from('jobs')
  190. ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
  191. ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
  192. ->orderBy('last_checked', 'ASC')
  193. ->setMaxResults(1);
  194. if ($onlyTimeSensitive) {
  195. $query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
  196. }
  197. $update = $this->connection->getQueryBuilder();
  198. $update->update('jobs')
  199. ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
  200. ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
  201. ->where($update->expr()->eq('id', $update->createParameter('jobid')))
  202. ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
  203. ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
  204. $result = $query->executeQuery();
  205. $row = $result->fetch();
  206. $result->closeCursor();
  207. if ($row) {
  208. $update->setParameter('jobid', $row['id']);
  209. $update->setParameter('reserved_at', $row['reserved_at']);
  210. $update->setParameter('last_checked', $row['last_checked']);
  211. $count = $update->executeStatement();
  212. if ($count === 0) {
  213. // Background job already executed elsewhere, try again.
  214. return $this->getNext($onlyTimeSensitive);
  215. }
  216. $job = $this->buildJob($row);
  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);
  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. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  330. $query->executeStatement();
  331. }
  332. /**
  333. * Reset the $job so it executes on the next trigger
  334. *
  335. * @since 23.0.0
  336. */
  337. public function resetBackgroundJob(IJob $job): void {
  338. $query = $this->connection->getQueryBuilder();
  339. $query->update('jobs')
  340. ->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  341. ->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  342. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
  343. $query->executeStatement();
  344. }
  345. public function hasReservedJob(?string $className = null): bool {
  346. $query = $this->connection->getQueryBuilder();
  347. $query->select('*')
  348. ->from('jobs')
  349. ->where($query->expr()->neq('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  350. ->setMaxResults(1);
  351. if ($className !== null) {
  352. $query->andWhere($query->expr()->eq('class', $query->createNamedParameter($className)));
  353. }
  354. try {
  355. $result = $query->executeQuery();
  356. $hasReservedJobs = $result->fetch() !== false;
  357. $result->closeCursor();
  358. return $hasReservedJobs;
  359. } catch (Exception $e) {
  360. $this->logger->debug('Querying reserved jobs failed', ['exception' => $e]);
  361. return false;
  362. }
  363. }
  364. }