-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathGearmanController.php
105 lines (85 loc) · 2.68 KB
/
GearmanController.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace filsh\yii2\gearman;
use Yii;
use yii\console\Controller;
use yii\helpers\Console;
use Sinergi\Gearman\Process;
use Sinergi\Gearman\Application;
class GearmanController extends Controller
{
/**
* @var boolean whether to run the forked process.
*/
public $fork = false;
public $gearmanComponent = 'gearman';
public function actionStart()
{
$app = $this->getApplication();
$process = $app->getProcess();
if ($process->isRunning()) {
$this->stdout("Failed: Process is already running\n", Console::FG_RED);
return;
}
$this->runApplication($app);
}
public function actionStop()
{
$app = $this->getApplication();
$process = $app->getProcess();
if ($process->isRunning()) {
$this->stdout("Success: Process is stopped\n", Console::FG_GREEN);
} else {
$this->stdout("Failed: Process is not stopped\n", Console::FG_RED);
}
$process->stop();
}
public function actionRestart()
{
$app = $this->getApplication();
$process = $app->getProcess();
if (!$process->isRunning()) {
$this->stdout("Failed: Process is not running\n", Console::FG_RED);
return;
}
unlink($process->getPidFile());
$process->release();
$int = 0;
while ($int < 1000) {
if (file_exists($process->getPidFile())) {
usleep(1000);
$int++;
} elseif (file_exists($process->getLockFile())) {
$process->release();
usleep(1000);
$int++;
} else {
$int = 1000;
}
}
$app->setProcess(new Process($app->getConfig(), $app->getLogger()));
$this->runApplication($app);
}
public function options($id)
{
$options = [];
if(in_array($id, ['start', 'restart'])) {
$options = ['fork'];
}
return array_merge(parent::options($id), $options);
}
protected function getApplication()
{
$component = Yii::$app->get($this->gearmanComponent);
return $component->getApplication();
}
protected function runApplication(Application $app)
{
$fork = (bool) $this->fork;
if($fork) {
$this->stdout("Success: Process is started\n", Console::FG_GREEN);
} else {
$this->stdout("Success: Process is started, but not daemonized\n", Console::FG_YELLOW);
}
$app->run((bool) $this->fork);
}
}