Job.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. /**
  3. * @package Grav\Common\Scheduler
  4. * @author Originally based on peppeocchi/php-cron-scheduler modified for Grav integration
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Scheduler;
  9. use Closure;
  10. use Cron\CronExpression;
  11. use DateTime;
  12. use Grav\Common\Grav;
  13. use InvalidArgumentException;
  14. use RuntimeException;
  15. use Symfony\Component\Process\Process;
  16. use function call_user_func;
  17. use function call_user_func_array;
  18. use function count;
  19. use function is_array;
  20. use function is_callable;
  21. use function is_string;
  22. /**
  23. * Class Job
  24. * @package Grav\Common\Scheduler
  25. */
  26. class Job
  27. {
  28. use IntervalTrait;
  29. /** @var string */
  30. private $id;
  31. /** @var bool */
  32. private $enabled;
  33. /** @var callable|string */
  34. private $command;
  35. /** @var string */
  36. private $at;
  37. /** @var array */
  38. private $args = [];
  39. /** @var bool */
  40. private $runInBackground = true;
  41. /** @var DateTime */
  42. private $creationTime;
  43. /** @var CronExpression */
  44. private $executionTime;
  45. /** @var string */
  46. private $tempDir;
  47. /** @var string */
  48. private $lockFile;
  49. /** @var bool */
  50. private $truthTest = true;
  51. /** @var string */
  52. private $output;
  53. /** @var int */
  54. private $returnCode = 0;
  55. /** @var array */
  56. private $outputTo = [];
  57. /** @var array */
  58. private $emailTo = [];
  59. /** @var array */
  60. private $emailConfig = [];
  61. /** @var callable|null */
  62. private $before;
  63. /** @var callable|null */
  64. private $after;
  65. /** @var callable */
  66. private $whenOverlapping;
  67. /** @var string */
  68. private $outputMode;
  69. /** @var Process|null $process */
  70. private $process;
  71. /** @var bool */
  72. private $successful = false;
  73. /** @var string|null */
  74. private $backlink;
  75. /**
  76. * Create a new Job instance.
  77. *
  78. * @param string|callable $command
  79. * @param array $args
  80. * @param string|null $id
  81. */
  82. public function __construct($command, $args = [], $id = null)
  83. {
  84. if (is_string($id)) {
  85. $this->id = Grav::instance()['inflector']->hyphenize($id);
  86. } else {
  87. if (is_string($command)) {
  88. $this->id = md5($command);
  89. } else {
  90. /* @var object $command */
  91. $this->id = spl_object_hash($command);
  92. }
  93. }
  94. $this->creationTime = new DateTime('now');
  95. // initialize the directory path for lock files
  96. $this->tempDir = sys_get_temp_dir();
  97. $this->command = $command;
  98. $this->args = $args;
  99. // Set enabled state
  100. $status = Grav::instance()['config']->get('scheduler.status');
  101. $this->enabled = !(isset($status[$id]) && $status[$id] === 'disabled');
  102. }
  103. /**
  104. * Get the command
  105. *
  106. * @return Closure|string
  107. */
  108. public function getCommand()
  109. {
  110. return $this->command;
  111. }
  112. /**
  113. * Get the cron 'at' syntax for this job
  114. *
  115. * @return string
  116. */
  117. public function getAt()
  118. {
  119. return $this->at;
  120. }
  121. /**
  122. * Get the status of this job
  123. *
  124. * @return bool
  125. */
  126. public function getEnabled()
  127. {
  128. return $this->enabled;
  129. }
  130. /**
  131. * Get optional arguments
  132. *
  133. * @return string|null
  134. */
  135. public function getArguments()
  136. {
  137. if (is_string($this->args)) {
  138. return $this->args;
  139. }
  140. return null;
  141. }
  142. /**
  143. * @return CronExpression
  144. */
  145. public function getCronExpression()
  146. {
  147. return CronExpression::factory($this->at);
  148. }
  149. /**
  150. * Get the status of the last run for this job
  151. *
  152. * @return bool
  153. */
  154. public function isSuccessful()
  155. {
  156. return $this->successful;
  157. }
  158. /**
  159. * Get the Job id.
  160. *
  161. * @return string
  162. */
  163. public function getId()
  164. {
  165. return $this->id;
  166. }
  167. /**
  168. * Check if the Job is due to run.
  169. * It accepts as input a DateTime used to check if
  170. * the job is due. Defaults to job creation time.
  171. * It also default the execution time if not previously defined.
  172. *
  173. * @param DateTime|null $date
  174. * @return bool
  175. */
  176. public function isDue(DateTime $date = null)
  177. {
  178. // The execution time is being defaulted if not defined
  179. if (!$this->executionTime) {
  180. $this->at('* * * * *');
  181. }
  182. $date = $date ?? $this->creationTime;
  183. return $this->executionTime->isDue($date);
  184. }
  185. /**
  186. * Check if the Job is overlapping.
  187. *
  188. * @return bool
  189. */
  190. public function isOverlapping()
  191. {
  192. return $this->lockFile &&
  193. file_exists($this->lockFile) &&
  194. call_user_func($this->whenOverlapping, filemtime($this->lockFile)) === false;
  195. }
  196. /**
  197. * Force the Job to run in foreground.
  198. *
  199. * @return $this
  200. */
  201. public function inForeground()
  202. {
  203. $this->runInBackground = false;
  204. return $this;
  205. }
  206. /**
  207. * Sets/Gets an option backlink
  208. *
  209. * @param string|null $link
  210. * @return string|null
  211. */
  212. public function backlink($link = null)
  213. {
  214. if ($link) {
  215. $this->backlink = $link;
  216. }
  217. return $this->backlink;
  218. }
  219. /**
  220. * Check if the Job can run in background.
  221. *
  222. * @return bool
  223. */
  224. public function runInBackground()
  225. {
  226. return !(is_callable($this->command) || $this->runInBackground === false);
  227. }
  228. /**
  229. * This will prevent the Job from overlapping.
  230. * It prevents another instance of the same Job of
  231. * being executed if the previous is still running.
  232. * The job id is used as a filename for the lock file.
  233. *
  234. * @param string|null $tempDir The directory path for the lock files
  235. * @param callable|null $whenOverlapping A callback to ignore job overlapping
  236. * @return self
  237. */
  238. public function onlyOne($tempDir = null, callable $whenOverlapping = null)
  239. {
  240. if ($tempDir === null || !is_dir($tempDir)) {
  241. $tempDir = $this->tempDir;
  242. }
  243. $this->lockFile = implode('/', [
  244. trim($tempDir),
  245. trim($this->id) . '.lock',
  246. ]);
  247. if ($whenOverlapping) {
  248. $this->whenOverlapping = $whenOverlapping;
  249. } else {
  250. $this->whenOverlapping = static function () {
  251. return false;
  252. };
  253. }
  254. return $this;
  255. }
  256. /**
  257. * Configure the job.
  258. *
  259. * @param array $config
  260. * @return self
  261. */
  262. public function configure(array $config = [])
  263. {
  264. // Check if config has defined a tempDir
  265. if (isset($config['tempDir']) && is_dir($config['tempDir'])) {
  266. $this->tempDir = $config['tempDir'];
  267. }
  268. return $this;
  269. }
  270. /**
  271. * Truth test to define if the job should run if due.
  272. *
  273. * @param callable $fn
  274. * @return self
  275. */
  276. public function when(callable $fn)
  277. {
  278. $this->truthTest = $fn();
  279. return $this;
  280. }
  281. /**
  282. * Run the job.
  283. *
  284. * @return bool
  285. */
  286. public function run()
  287. {
  288. // If the truthTest failed, don't run
  289. if ($this->truthTest !== true) {
  290. return false;
  291. }
  292. // If overlapping, don't run
  293. if ($this->isOverlapping()) {
  294. return false;
  295. }
  296. // Write lock file if necessary
  297. $this->createLockFile();
  298. // Call before if required
  299. if (is_callable($this->before)) {
  300. call_user_func($this->before);
  301. }
  302. // If command is callable...
  303. if (is_callable($this->command)) {
  304. $this->output = $this->exec();
  305. } else {
  306. $args = is_string($this->args) ? explode(' ', $this->args) : $this->args;
  307. $command = array_merge([$this->command], $args);
  308. $process = new Process($command);
  309. $this->process = $process;
  310. if ($this->runInBackground()) {
  311. $process->start();
  312. } else {
  313. $process->run();
  314. $this->finalize();
  315. }
  316. }
  317. return true;
  318. }
  319. /**
  320. * Finish up processing the job
  321. *
  322. * @return void
  323. */
  324. public function finalize()
  325. {
  326. $process = $this->process;
  327. if ($process) {
  328. $process->wait();
  329. if ($process->isSuccessful()) {
  330. $this->successful = true;
  331. $this->output = $process->getOutput();
  332. } else {
  333. $this->successful = false;
  334. $this->output = $process->getErrorOutput();
  335. }
  336. $this->postRun();
  337. unset($this->process);
  338. }
  339. }
  340. /**
  341. * Things to run after job has run
  342. *
  343. * @return void
  344. */
  345. private function postRun()
  346. {
  347. if (count($this->outputTo) > 0) {
  348. foreach ($this->outputTo as $file) {
  349. $output_mode = $this->outputMode === 'append' ? FILE_APPEND | LOCK_EX : LOCK_EX;
  350. $timestamp = (new DateTime('now'))->format('c');
  351. $output = $timestamp . "\n" . str_pad('', strlen($timestamp), '>') . "\n" . $this->output;
  352. file_put_contents($file, $output, $output_mode);
  353. }
  354. }
  355. // Send output to email
  356. $this->emailOutput();
  357. // Call any callback defined
  358. if (is_callable($this->after)) {
  359. call_user_func($this->after, $this->output, $this->returnCode);
  360. }
  361. $this->removeLockFile();
  362. }
  363. /**
  364. * Create the job lock file.
  365. *
  366. * @param mixed $content
  367. * @return void
  368. */
  369. private function createLockFile($content = null)
  370. {
  371. if ($this->lockFile) {
  372. if ($content === null || !is_string($content)) {
  373. $content = $this->getId();
  374. }
  375. file_put_contents($this->lockFile, $content);
  376. }
  377. }
  378. /**
  379. * Remove the job lock file.
  380. *
  381. * @return void
  382. */
  383. private function removeLockFile()
  384. {
  385. if ($this->lockFile && file_exists($this->lockFile)) {
  386. unlink($this->lockFile);
  387. }
  388. }
  389. /**
  390. * Execute a callable job.
  391. *
  392. * @return string
  393. * @throws RuntimeException
  394. */
  395. private function exec()
  396. {
  397. $return_data = '';
  398. ob_start();
  399. try {
  400. $return_data = call_user_func_array($this->command, $this->args);
  401. $this->successful = true;
  402. } catch (RuntimeException $e) {
  403. $return_data = $e->getMessage();
  404. $this->successful = false;
  405. }
  406. $this->output = ob_get_clean() . (is_string($return_data) ? $return_data : '');
  407. $this->postRun();
  408. return $this->output;
  409. }
  410. /**
  411. * Set the file/s where to write the output of the job.
  412. *
  413. * @param string|array $filename
  414. * @param bool $append
  415. * @return self
  416. */
  417. public function output($filename, $append = false)
  418. {
  419. $this->outputTo = is_array($filename) ? $filename : [$filename];
  420. $this->outputMode = $append === false ? 'overwrite' : 'append';
  421. return $this;
  422. }
  423. /**
  424. * Get the job output.
  425. *
  426. * @return mixed
  427. */
  428. public function getOutput()
  429. {
  430. return $this->output;
  431. }
  432. /**
  433. * Set the emails where the output should be sent to.
  434. * The Job should be set to write output to a file
  435. * for this to work.
  436. *
  437. * @param string|array $email
  438. * @return self
  439. */
  440. public function email($email)
  441. {
  442. if (!is_string($email) && !is_array($email)) {
  443. throw new InvalidArgumentException('The email can be only string or array');
  444. }
  445. $this->emailTo = is_array($email) ? $email : [$email];
  446. // Force the job to run in foreground
  447. $this->inForeground();
  448. return $this;
  449. }
  450. /**
  451. * Email the output of the job, if any.
  452. *
  453. * @return bool
  454. */
  455. private function emailOutput()
  456. {
  457. if (!count($this->outputTo) || !count($this->emailTo)) {
  458. return false;
  459. }
  460. if (is_callable('Grav\Plugin\Email\Utils::sendEmail')) {
  461. $subject ='Grav Scheduled Job [' . $this->getId() . ']';
  462. $content = "<h1>Output from Job ID: {$this->getId()}</h1>\n<h4>Command: {$this->getCommand()}</h4><br /><pre style=\"font-size: 12px; font-family: Monaco, Consolas, monospace\">\n".$this->getOutput()."\n</pre>";
  463. $to = $this->emailTo;
  464. \Grav\Plugin\Email\Utils::sendEmail($subject, $content, $to);
  465. }
  466. return true;
  467. }
  468. /**
  469. * Set function to be called before job execution
  470. * Job object is injected as a parameter to callable function.
  471. *
  472. * @param callable $fn
  473. * @return self
  474. */
  475. public function before(callable $fn)
  476. {
  477. $this->before = $fn;
  478. return $this;
  479. }
  480. /**
  481. * Set a function to be called after job execution.
  482. * By default this will force the job to run in foreground
  483. * because the output is injected as a parameter of this
  484. * function, but it could be avoided by passing true as a
  485. * second parameter. The job will run in background if it
  486. * meets all the other criteria.
  487. *
  488. * @param callable $fn
  489. * @param bool $runInBackground
  490. * @return self
  491. */
  492. public function then(callable $fn, $runInBackground = false)
  493. {
  494. $this->after = $fn;
  495. // Force the job to run in foreground
  496. if ($runInBackground === false) {
  497. $this->inForeground();
  498. }
  499. return $this;
  500. }
  501. }