-
Notifications
You must be signed in to change notification settings - Fork 83
/
BackgroundProcess.php
83 lines (74 loc) · 2.26 KB
/
BackgroundProcess.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\MagentoCloud\Util;
use Magento\MagentoCloud\Shell\ShellException;
use Magento\MagentoCloud\Shell\ShellInterface;
use Psr\Log\LoggerInterface;
/**
* Kills all running Magento cron and consumers processes
*/
class BackgroundProcess
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var ShellInterface
*/
private $shell;
/**
* @param LoggerInterface $logger
* @param ShellInterface $shell
*/
public function __construct(
LoggerInterface $logger,
ShellInterface $shell
) {
$this->logger = $logger;
$this->shell = $shell;
}
/**
* Kills all running Magento cron jobs and consumers processes.
*
* @return void
*/
public function kill():void
{
try {
$this->logger->info('Trying to kill running cron jobs and consumers processes');
$process = $this->shell->execute('pgrep -U "$(id -u)" -f "bin/magento +(cron:run|queue:consumers:start)"');
$cronPids = array_filter(explode(PHP_EOL, $process->getOutput()));
foreach ($cronPids as $pid) {
$this->killProcess($pid);
}
} catch (ShellException $e) {
// pgrep returns 1 when no processes matched. Returns 2 and 3 in case of error
if ($e->getCode() === 1) {
$this->logger->info('Running Magento cron and consumers processes were not found.');
} else {
$this->logger->warning('Error happening during kill cron or consumers processes: ' . $e->getMessage());
}
}
}
/**
* Runs command for killing the process by PID.
* Sometimes there may be an error when process was already finished before killing it.
*
* @param string $pid
* @return void
*/
private function killProcess($pid): void
{
try {
$this->shell->execute("kill $pid");
} catch (ShellException $e) {
$this->logger->info(sprintf('Couldn\'t kill process #%d it may be already finished', $pid));
$this->logger->debug($e->getMessage());
}
}
}