CrontabManager.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Crontab;
  7. use Magento\Framework\App\Filesystem\DirectoryList;
  8. use Magento\Framework\Exception\LocalizedException;
  9. use Magento\Framework\Filesystem;
  10. use Magento\Framework\Phrase;
  11. use Magento\Framework\ShellInterface;
  12. /**
  13. * Manager works with cron tasks
  14. */
  15. class CrontabManager implements CrontabManagerInterface
  16. {
  17. /**
  18. * @var ShellInterface
  19. */
  20. private $shell;
  21. /**
  22. * @var Filesystem
  23. */
  24. private $filesystem;
  25. /**
  26. * @param ShellInterface $shell
  27. * @param Filesystem $filesystem
  28. */
  29. public function __construct(
  30. ShellInterface $shell,
  31. Filesystem $filesystem
  32. ) {
  33. $this->shell = $shell;
  34. $this->filesystem = $filesystem;
  35. }
  36. /**
  37. * @return string
  38. */
  39. private function getTasksBlockStart()
  40. {
  41. $tasksBlockStart = self::TASKS_BLOCK_START;
  42. if (defined('BP')) {
  43. $tasksBlockStart .= ' ' . md5(BP);
  44. }
  45. return $tasksBlockStart;
  46. }
  47. /**
  48. * @return string
  49. */
  50. private function getTasksBlockEnd()
  51. {
  52. $tasksBlockEnd = self::TASKS_BLOCK_END;
  53. if (defined('BP')) {
  54. $tasksBlockEnd .= ' ' . md5(BP);
  55. }
  56. return $tasksBlockEnd;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getTasks()
  62. {
  63. $this->checkSupportedOs();
  64. $content = $this->getCrontabContent();
  65. $pattern = '!(' . $this->getTasksBlockStart() . ')(.*?)(' . $this->getTasksBlockEnd() . ')!s';
  66. if (preg_match($pattern, $content, $matches)) {
  67. $tasks = trim($matches[2], PHP_EOL);
  68. $tasks = explode(PHP_EOL, $tasks);
  69. return $tasks;
  70. }
  71. return [];
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function saveTasks(array $tasks)
  77. {
  78. if (!$tasks) {
  79. throw new LocalizedException(new Phrase('The list of tasks is empty. Add tasks and try again.'));
  80. }
  81. $this->checkSupportedOs();
  82. $baseDir = $this->filesystem->getDirectoryRead(DirectoryList::ROOT)->getAbsolutePath();
  83. $logDir = $this->filesystem->getDirectoryRead(DirectoryList::LOG)->getAbsolutePath();
  84. foreach ($tasks as $key => $task) {
  85. if (empty($task['expression'])) {
  86. $tasks[$key]['expression'] = '* * * * *';
  87. }
  88. if (empty($task['command'])) {
  89. throw new LocalizedException(new Phrase("The command shouldn't be empty. Enter and try again."));
  90. }
  91. $tasks[$key]['command'] = str_replace(
  92. ['{magentoRoot}', '{magentoLog}'],
  93. [$baseDir, $logDir],
  94. $task['command']
  95. );
  96. }
  97. $content = $this->getCrontabContent();
  98. $content = $this->cleanMagentoSection($content);
  99. $content = $this->generateSection($content, $tasks);
  100. $this->save($content);
  101. }
  102. /**
  103. * {@inheritdoc}
  104. * @throws LocalizedException
  105. */
  106. public function removeTasks()
  107. {
  108. $this->checkSupportedOs();
  109. $content = $this->getCrontabContent();
  110. $content = $this->cleanMagentoSection($content);
  111. $this->save($content);
  112. }
  113. /**
  114. * Generate Magento Tasks Section
  115. *
  116. * @param string $content
  117. * @param array $tasks
  118. * @return string
  119. */
  120. private function generateSection($content, $tasks = [])
  121. {
  122. if ($tasks) {
  123. // Add EOL symbol to previous line if not exist.
  124. if (substr($content, -strlen(PHP_EOL)) !== PHP_EOL) {
  125. $content .= PHP_EOL;
  126. }
  127. $content .= $this->getTasksBlockStart() . PHP_EOL;
  128. foreach ($tasks as $task) {
  129. $content .= $task['expression'] . ' ' . PHP_BINARY . ' ' . $task['command'] . PHP_EOL;
  130. }
  131. $content .= $this->getTasksBlockEnd() . PHP_EOL;
  132. }
  133. return $content;
  134. }
  135. /**
  136. * Clean Magento Tasks Section in crontab content
  137. *
  138. * @param string $content
  139. * @return string
  140. */
  141. private function cleanMagentoSection($content)
  142. {
  143. $content = preg_replace(
  144. '!' . preg_quote($this->getTasksBlockStart()) . '.*?'
  145. . preg_quote($this->getTasksBlockEnd() . PHP_EOL) . '!s',
  146. '',
  147. $content
  148. );
  149. return $content;
  150. }
  151. /**
  152. * Get crontab content without Magento Tasks Section
  153. *
  154. * In case of some exceptions the empty content is returned
  155. *
  156. * @return string
  157. */
  158. private function getCrontabContent()
  159. {
  160. try {
  161. $content = (string)$this->shell->execute('crontab -l');
  162. } catch (LocalizedException $e) {
  163. return '';
  164. }
  165. return $content;
  166. }
  167. /**
  168. * Save crontab
  169. *
  170. * @param string $content
  171. * @return void
  172. * @throws LocalizedException
  173. */
  174. private function save($content)
  175. {
  176. $content = str_replace(['%', '"'], ['%%', '\"'], $content);
  177. try {
  178. $this->shell->execute('echo "' . $content . '" | crontab -');
  179. } catch (LocalizedException $e) {
  180. throw new LocalizedException(
  181. new Phrase('Error during saving of crontab: %1', [$e->getPrevious()->getMessage()]),
  182. $e
  183. );
  184. }
  185. }
  186. /**
  187. * Check that OS is supported
  188. *
  189. * If OS is not supported then no possibility to work with crontab
  190. *
  191. * @return void
  192. * @throws LocalizedException
  193. */
  194. private function checkSupportedOs()
  195. {
  196. if (stripos(PHP_OS, 'WIN') === 0) {
  197. throw new LocalizedException(
  198. new Phrase('Your operating system is not supported to work with this command')
  199. );
  200. }
  201. }
  202. }