1
0

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. /**
  144. * get all jobs in the list
  145. *
  146. * @return IJob[]
  147. * @deprecated 9.0.0 - This method is dangerous since it can cause load and
  148. * memory problems when creating too many instances. Use getJobs instead.
  149. */
  150. public function getAll(): array {
  151. return $this->getJobs(null, null, 0);
  152. }
  153. /**
  154. * @param IJob|class-string<IJob>|null $job
  155. * @return IJob[]
  156. */
  157. public function getJobs($job, ?int $limit, int $offset): array {
  158. $query = $this->connection->getQueryBuilder();
  159. $query->select('*')
  160. ->from('jobs')
  161. ->setMaxResults($limit)
  162. ->setFirstResult($offset);
  163. if ($job !== null) {
  164. if ($job instanceof IJob) {
  165. $class = get_class($job);
  166. } else {
  167. $class = $job;
  168. }
  169. $query->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  170. }
  171. $result = $query->executeQuery();
  172. $jobs = [];
  173. while ($row = $result->fetch()) {
  174. $job = $this->buildJob($row);
  175. if ($job) {
  176. $jobs[] = $job;
  177. }
  178. }
  179. $result->closeCursor();
  180. return $jobs;
  181. }
  182. /**
  183. * get the next job in the list
  184. */
  185. public function getNext(bool $onlyTimeSensitive = false): ?IJob {
  186. $query = $this->connection->getQueryBuilder();
  187. $query->select('*')
  188. ->from('jobs')
  189. ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
  190. ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
  191. ->orderBy('last_checked', 'ASC')
  192. ->setMaxResults(1);
  193. if ($onlyTimeSensitive) {
  194. $query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
  195. }
  196. $update = $this->connection->getQueryBuilder();
  197. $update->update('jobs')
  198. ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
  199. ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
  200. ->where($update->expr()->eq('id', $update->createParameter('jobid')))
  201. ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
  202. ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
  203. $result = $query->executeQuery();
  204. $row = $result->fetch();
  205. $result->closeCursor();
  206. if ($row) {
  207. $update->setParameter('jobid', $row['id']);
  208. $update->setParameter('reserved_at', $row['reserved_at']);
  209. $update->setParameter('last_checked', $row['last_checked']);
  210. $count = $update->executeStatement();
  211. if ($count === 0) {
  212. // Background job already executed elsewhere, try again.
  213. return $this->getNext($onlyTimeSensitive);
  214. }
  215. $job = $this->buildJob($row);
  216. if ($job === null) {
  217. // set the last_checked to 12h in the future to not check failing jobs all over again
  218. $reset = $this->connection->getQueryBuilder();
  219. $reset->update('jobs')
  220. ->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
  221. ->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
  222. ->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
  223. $reset->executeStatement();
  224. // Background job from disabled app, try again.
  225. return $this->getNext($onlyTimeSensitive);
  226. }
  227. return $job;
  228. } else {
  229. return null;
  230. }
  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. */
  257. private function buildJob(array $row): ?IJob {
  258. try {
  259. try {
  260. // Try to load the job as a service
  261. /** @var IJob $job */
  262. $job = \OCP\Server::get($row['class']);
  263. } catch (QueryException $e) {
  264. if (class_exists($row['class'])) {
  265. $class = $row['class'];
  266. $job = new $class();
  267. } else {
  268. // job from disabled app or old version of an app, no need to do anything
  269. return null;
  270. }
  271. }
  272. if (!($job instanceof IJob)) {
  273. // This most likely means an invalid job was enqueued. We can ignore it.
  274. return null;
  275. }
  276. $job->setId((int) $row['id']);
  277. $job->setLastRun((int) $row['last_run']);
  278. $job->setArgument(json_decode($row['argument'], true));
  279. return $job;
  280. } catch (AutoloadNotAllowedException $e) {
  281. // job is from a disabled app, ignore
  282. return null;
  283. }
  284. }
  285. /**
  286. * set the job that was last ran
  287. */
  288. public function setLastJob(IJob $job): void {
  289. $this->unlockJob($job);
  290. $this->config->setAppValue('backgroundjob', 'lastjob', (string)$job->getId());
  291. }
  292. /**
  293. * Remove the reservation for a job
  294. */
  295. public function unlockJob(IJob $job): void {
  296. $query = $this->connection->getQueryBuilder();
  297. $query->update('jobs')
  298. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  299. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  300. $query->executeStatement();
  301. }
  302. /**
  303. * set the lastRun of $job to now
  304. */
  305. public function setLastRun(IJob $job): void {
  306. $query = $this->connection->getQueryBuilder();
  307. $query->update('jobs')
  308. ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  309. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  310. if ($job instanceof \OCP\BackgroundJob\TimedJob
  311. && !$job->isTimeSensitive()) {
  312. $query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
  313. }
  314. $query->executeStatement();
  315. }
  316. /**
  317. * @param int $timeTaken
  318. */
  319. public function setExecutionTime(IJob $job, $timeTaken): void {
  320. $query = $this->connection->getQueryBuilder();
  321. $query->update('jobs')
  322. ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
  323. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  324. $query->executeStatement();
  325. }
  326. /**
  327. * Reset the $job so it executes on the next trigger
  328. *
  329. * @since 23.0.0
  330. */
  331. public function resetBackgroundJob(IJob $job): void {
  332. $query = $this->connection->getQueryBuilder();
  333. $query->update('jobs')
  334. ->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  335. ->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
  336. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
  337. $query->executeStatement();
  338. }
  339. }