JobList.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Noveen Sachdeva <noveen.sachdeva@research.iiit.ac.in>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Robin McCorkell <robin@mccorkell.me.uk>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\BackgroundJob;
  29. use OCP\AppFramework\QueryException;
  30. use OCP\AppFramework\Utility\ITimeFactory;
  31. use OCP\BackgroundJob\IJob;
  32. use OCP\BackgroundJob\IJobList;
  33. use OCP\AutoloadNotAllowedException;
  34. use OCP\DB\QueryBuilder\IQueryBuilder;
  35. use OCP\IConfig;
  36. use OCP\IDBConnection;
  37. class JobList implements IJobList {
  38. /** @var IDBConnection */
  39. protected $connection;
  40. /**@var IConfig */
  41. protected $config;
  42. /**@var ITimeFactory */
  43. protected $timeFactory;
  44. /** @var int - 12 hours * 3600 seconds*/
  45. private $jobTimeOut = 43200;
  46. /**
  47. * @param IDBConnection $connection
  48. * @param IConfig $config
  49. * @param ITimeFactory $timeFactory
  50. */
  51. public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
  52. $this->connection = $connection;
  53. $this->config = $config;
  54. $this->timeFactory = $timeFactory;
  55. }
  56. /**
  57. * @param IJob|string $job
  58. * @param mixed $argument
  59. */
  60. public function add($job, $argument = null) {
  61. if (!$this->has($job, $argument)) {
  62. if ($job instanceof IJob) {
  63. $class = get_class($job);
  64. } else {
  65. $class = $job;
  66. }
  67. $argument = json_encode($argument);
  68. if (strlen($argument) > 4000) {
  69. throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
  70. }
  71. $query = $this->connection->getQueryBuilder();
  72. $query->insert('jobs')
  73. ->values([
  74. 'class' => $query->createNamedParameter($class),
  75. 'argument' => $query->createNamedParameter($argument),
  76. 'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
  77. 'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
  78. ]);
  79. $query->execute();
  80. }
  81. }
  82. /**
  83. * @param IJob|string $job
  84. * @param mixed $argument
  85. */
  86. public function remove($job, $argument = null) {
  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. $argument = json_encode($argument);
  97. $query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
  98. }
  99. $query->execute();
  100. }
  101. /**
  102. * @param int $id
  103. */
  104. protected function removeById($id) {
  105. $query = $this->connection->getQueryBuilder();
  106. $query->delete('jobs')
  107. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  108. $query->execute();
  109. }
  110. /**
  111. * check if a job is in the list
  112. *
  113. * @param IJob|string $job
  114. * @param mixed $argument
  115. * @return bool
  116. */
  117. public function has($job, $argument) {
  118. if ($job instanceof IJob) {
  119. $class = get_class($job);
  120. } else {
  121. $class = $job;
  122. }
  123. $argument = json_encode($argument);
  124. $query = $this->connection->getQueryBuilder();
  125. $query->select('id')
  126. ->from('jobs')
  127. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  128. ->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)))
  129. ->setMaxResults(1);
  130. $result = $query->execute();
  131. $row = $result->fetch();
  132. $result->closeCursor();
  133. return (bool) $row;
  134. }
  135. /**
  136. * get all jobs in the list
  137. *
  138. * @return IJob[]
  139. * @deprecated 9.0.0 - This method is dangerous since it can cause load and
  140. * memory problems when creating too many instances.
  141. */
  142. public function getAll() {
  143. $query = $this->connection->getQueryBuilder();
  144. $query->select('*')
  145. ->from('jobs');
  146. $result = $query->execute();
  147. $jobs = [];
  148. while ($row = $result->fetch()) {
  149. $job = $this->buildJob($row);
  150. if ($job) {
  151. $jobs[] = $job;
  152. }
  153. }
  154. $result->closeCursor();
  155. return $jobs;
  156. }
  157. /**
  158. * get the next job in the list
  159. *
  160. * @return IJob|null
  161. */
  162. public function getNext() {
  163. $query = $this->connection->getQueryBuilder();
  164. $query->select('*')
  165. ->from('jobs')
  166. ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - $this->jobTimeOut, IQueryBuilder::PARAM_INT)))
  167. ->orderBy('last_checked', 'ASC')
  168. ->setMaxResults(1);
  169. $update = $this->connection->getQueryBuilder();
  170. $update->update('jobs')
  171. ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
  172. ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
  173. ->where($update->expr()->eq('id', $update->createParameter('jobid')))
  174. ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
  175. ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
  176. $result = $query->execute();
  177. $row = $result->fetch();
  178. $result->closeCursor();
  179. if ($row) {
  180. $update->setParameter('jobid', $row['id']);
  181. $update->setParameter('reserved_at', $row['reserved_at']);
  182. $update->setParameter('last_checked', $row['last_checked']);
  183. $count = $update->execute();
  184. if ($count === 0) {
  185. // Background job already executed elsewhere, try again.
  186. return $this->getNext();
  187. }
  188. $job = $this->buildJob($row);
  189. if ($job === null) {
  190. // Background job from disabled app, try again.
  191. return $this->getNext();
  192. }
  193. return $job;
  194. } else {
  195. return null;
  196. }
  197. }
  198. /**
  199. * @param int $id
  200. * @return IJob|null
  201. */
  202. public function getById($id) {
  203. $query = $this->connection->getQueryBuilder();
  204. $query->select('*')
  205. ->from('jobs')
  206. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  207. $result = $query->execute();
  208. $row = $result->fetch();
  209. $result->closeCursor();
  210. if ($row) {
  211. return $this->buildJob($row);
  212. } else {
  213. return null;
  214. }
  215. }
  216. /**
  217. * get the job object from a row in the db
  218. *
  219. * @param array $row
  220. * @return IJob|null
  221. */
  222. private function buildJob($row) {
  223. try {
  224. try {
  225. // Try to load the job as a service
  226. /** @var IJob $job */
  227. $job = \OC::$server->query($row['class']);
  228. } catch (QueryException $e) {
  229. if (class_exists($row['class'])) {
  230. $class = $row['class'];
  231. $job = new $class();
  232. } else {
  233. // job from disabled app or old version of an app, no need to do anything
  234. return null;
  235. }
  236. }
  237. $job->setId($row['id']);
  238. $job->setLastRun($row['last_run']);
  239. $job->setArgument(json_decode($row['argument'], true));
  240. return $job;
  241. } catch (AutoloadNotAllowedException $e) {
  242. // job is from a disabled app, ignore
  243. return null;
  244. }
  245. }
  246. /**
  247. * set the job that was last ran
  248. *
  249. * @param IJob $job
  250. */
  251. public function setLastJob(IJob $job) {
  252. $this->unlockJob($job);
  253. $this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
  254. }
  255. /**
  256. * Remove the reservation for a job
  257. *
  258. * @param IJob $job
  259. * @suppress SqlInjectionChecker
  260. */
  261. public function unlockJob(IJob $job) {
  262. $query = $this->connection->getQueryBuilder();
  263. $query->update('jobs')
  264. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  265. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  266. $query->execute();
  267. }
  268. /**
  269. * get the id of the last ran job
  270. *
  271. * @return int
  272. * @deprecated 9.1.0 - The functionality behind the value is deprecated, it
  273. * only tells you which job finished last, but since we now allow multiple
  274. * executors to run in parallel, it's not used to calculate the next job.
  275. */
  276. public function getLastJob() {
  277. return (int) $this->config->getAppValue('backgroundjob', 'lastjob', 0);
  278. }
  279. /**
  280. * set the lastRun of $job to now
  281. *
  282. * @param IJob $job
  283. */
  284. public function setLastRun(IJob $job) {
  285. $query = $this->connection->getQueryBuilder();
  286. $query->update('jobs')
  287. ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  288. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  289. $query->execute();
  290. }
  291. /**
  292. * @param IJob $job
  293. * @param $timeTaken
  294. */
  295. public function setExecutionTime(IJob $job, $timeTaken) {
  296. $query = $this->connection->getQueryBuilder();
  297. $query->update('jobs')
  298. ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
  299. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  300. $query->execute();
  301. }
  302. /**
  303. * checks if a job is still running (reserved_at time is smaller than 12 hours ago)
  304. *
  305. * Background information:
  306. *
  307. * The 12 hours is the same timeout that is also used to re-schedule an non-terminated
  308. * job (see getNext()). The idea here is to give a job enough time to run very
  309. * long but still be able to recognize that it maybe crashed and re-schedule it
  310. * after the timeout. It's more likely to be crashed at that time than it ran
  311. * that long.
  312. *
  313. * In theory it could lead to an nearly endless loop (as in - at most 12 hours).
  314. * The cron command will not start new jobs when maintenance mode is active and
  315. * this method is only executed in maintenance mode (see where it is called in
  316. * the upgrader class. So this means in the worst case we wait 12 hours when a
  317. * job has crashed. On the other hand: then the instance should be fixed anyways.
  318. *
  319. * @return bool
  320. */
  321. public function isAnyJobRunning(): bool {
  322. $query = $this->connection->getQueryBuilder();
  323. $query->select('*')
  324. ->from('jobs')
  325. ->where($query->expr()->gt('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - $this->jobTimeOut, IQueryBuilder::PARAM_INT)))
  326. ->setMaxResults(1);
  327. $result = $query->execute();
  328. $row = $result->fetch();
  329. $result->closeCursor();
  330. if ($row) {
  331. return true;
  332. }
  333. return false;
  334. }
  335. }