JobList.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. /**
  45. * @param IDBConnection $connection
  46. * @param IConfig $config
  47. * @param ITimeFactory $timeFactory
  48. */
  49. public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
  50. $this->connection = $connection;
  51. $this->config = $config;
  52. $this->timeFactory = $timeFactory;
  53. }
  54. /**
  55. * @param IJob|string $job
  56. * @param mixed $argument
  57. */
  58. public function add($job, $argument = null) {
  59. if (!$this->has($job, $argument)) {
  60. if ($job instanceof IJob) {
  61. $class = get_class($job);
  62. } else {
  63. $class = $job;
  64. }
  65. $argument = json_encode($argument);
  66. if (strlen($argument) > 4000) {
  67. throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
  68. }
  69. $query = $this->connection->getQueryBuilder();
  70. $query->insert('jobs')
  71. ->values([
  72. 'class' => $query->createNamedParameter($class),
  73. 'argument' => $query->createNamedParameter($argument),
  74. 'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
  75. 'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
  76. ]);
  77. $query->execute();
  78. }
  79. }
  80. /**
  81. * @param IJob|string $job
  82. * @param mixed $argument
  83. */
  84. public function remove($job, $argument = null) {
  85. if ($job instanceof IJob) {
  86. $class = get_class($job);
  87. } else {
  88. $class = $job;
  89. }
  90. $query = $this->connection->getQueryBuilder();
  91. $query->delete('jobs')
  92. ->where($query->expr()->eq('class', $query->createNamedParameter($class)));
  93. if (!is_null($argument)) {
  94. $argument = json_encode($argument);
  95. $query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
  96. }
  97. $query->execute();
  98. }
  99. /**
  100. * @param int $id
  101. */
  102. protected function removeById($id) {
  103. $query = $this->connection->getQueryBuilder();
  104. $query->delete('jobs')
  105. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  106. $query->execute();
  107. }
  108. /**
  109. * check if a job is in the list
  110. *
  111. * @param IJob|string $job
  112. * @param mixed $argument
  113. * @return bool
  114. */
  115. public function has($job, $argument) {
  116. if ($job instanceof IJob) {
  117. $class = get_class($job);
  118. } else {
  119. $class = $job;
  120. }
  121. $argument = json_encode($argument);
  122. $query = $this->connection->getQueryBuilder();
  123. $query->select('id')
  124. ->from('jobs')
  125. ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
  126. ->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)))
  127. ->setMaxResults(1);
  128. $result = $query->execute();
  129. $row = $result->fetch();
  130. $result->closeCursor();
  131. return (bool) $row;
  132. }
  133. /**
  134. * get all jobs in the list
  135. *
  136. * @return IJob[]
  137. * @deprecated 9.0.0 - This method is dangerous since it can cause load and
  138. * memory problems when creating too many instances.
  139. */
  140. public function getAll() {
  141. $query = $this->connection->getQueryBuilder();
  142. $query->select('*')
  143. ->from('jobs');
  144. $result = $query->execute();
  145. $jobs = [];
  146. while ($row = $result->fetch()) {
  147. $job = $this->buildJob($row);
  148. if ($job) {
  149. $jobs[] = $job;
  150. }
  151. }
  152. $result->closeCursor();
  153. return $jobs;
  154. }
  155. /**
  156. * get the next job in the list
  157. *
  158. * @return IJob|null
  159. * @suppress SqlInjectionChecker
  160. */
  161. public function getNext() {
  162. $query = $this->connection->getQueryBuilder();
  163. $query->select('*')
  164. ->from('jobs')
  165. ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
  166. ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), 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. // set the last_checked to 12h in the future to not check failing jobs all over again
  191. $reset = $this->connection->getQueryBuilder();
  192. $reset->update('jobs')
  193. ->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
  194. ->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
  195. ->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
  196. $reset->execute();
  197. // Background job from disabled app, try again.
  198. return $this->getNext();
  199. }
  200. return $job;
  201. } else {
  202. return null;
  203. }
  204. }
  205. /**
  206. * @param int $id
  207. * @return IJob|null
  208. */
  209. public function getById($id) {
  210. $query = $this->connection->getQueryBuilder();
  211. $query->select('*')
  212. ->from('jobs')
  213. ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  214. $result = $query->execute();
  215. $row = $result->fetch();
  216. $result->closeCursor();
  217. if ($row) {
  218. return $this->buildJob($row);
  219. } else {
  220. return null;
  221. }
  222. }
  223. /**
  224. * get the job object from a row in the db
  225. *
  226. * @param array $row
  227. * @return IJob|null
  228. */
  229. private function buildJob($row) {
  230. try {
  231. try {
  232. // Try to load the job as a service
  233. /** @var IJob $job */
  234. $job = \OC::$server->query($row['class']);
  235. } catch (QueryException $e) {
  236. if (class_exists($row['class'])) {
  237. $class = $row['class'];
  238. $job = new $class();
  239. } else {
  240. // job from disabled app or old version of an app, no need to do anything
  241. return null;
  242. }
  243. }
  244. $job->setId((int) $row['id']);
  245. $job->setLastRun($row['last_run']);
  246. $job->setArgument(json_decode($row['argument'], true));
  247. return $job;
  248. } catch (AutoloadNotAllowedException $e) {
  249. // job is from a disabled app, ignore
  250. return null;
  251. }
  252. }
  253. /**
  254. * set the job that was last ran
  255. *
  256. * @param IJob $job
  257. */
  258. public function setLastJob(IJob $job) {
  259. $this->unlockJob($job);
  260. $this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
  261. }
  262. /**
  263. * Remove the reservation for a job
  264. *
  265. * @param IJob $job
  266. * @suppress SqlInjectionChecker
  267. */
  268. public function unlockJob(IJob $job) {
  269. $query = $this->connection->getQueryBuilder();
  270. $query->update('jobs')
  271. ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
  272. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  273. $query->execute();
  274. }
  275. /**
  276. * get the id of the last ran job
  277. *
  278. * @return int
  279. * @deprecated 9.1.0 - The functionality behind the value is deprecated, it
  280. * only tells you which job finished last, but since we now allow multiple
  281. * executors to run in parallel, it's not used to calculate the next job.
  282. */
  283. public function getLastJob() {
  284. return (int) $this->config->getAppValue('backgroundjob', 'lastjob', 0);
  285. }
  286. /**
  287. * set the lastRun of $job to now
  288. *
  289. * @param IJob $job
  290. */
  291. public function setLastRun(IJob $job) {
  292. $query = $this->connection->getQueryBuilder();
  293. $query->update('jobs')
  294. ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
  295. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  296. $query->execute();
  297. }
  298. /**
  299. * @param IJob $job
  300. * @param $timeTaken
  301. */
  302. public function setExecutionTime(IJob $job, $timeTaken) {
  303. $query = $this->connection->getQueryBuilder();
  304. $query->update('jobs')
  305. ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
  306. ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
  307. $query->execute();
  308. }
  309. }