JobList.php 12 KB

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