-
Notifications
You must be signed in to change notification settings - Fork 1
/
CronProcess.php
312 lines (267 loc) · 9.1 KB
/
CronProcess.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<?php
/**
* Class CronProcess
*
* Represents process for CronTask with additional information about current running status, last times of start/stop
* and PID of running instance.
*
* CronProcess is created for each CronTask. Execution process is the following:
* 1. Create process from CronTask instance
* 2. If the task can be started - save info file with it's definition and start background wrapper process with special
* console action 'cron/run' with task identifier.
* 3. In console action get task identifier and run process: register shutdown function (to handle unexpected
* termination of the task) and redirect runtime process to specified console command.
* 4. Log and save to info file information about task termination - successful or not (error, exception).
* 5. Profit :-)
*
* Information about each task serialized and stored in special file named by task unique id with '.json' extension.
* Files stored in runtime path specified by cron application component.
*
* @author Vadym Stepanov <[email protected]>
* @date 18.01.2016
*/
class CronProcess
{
const STATUS_NEW = 0;
const STATUS_RUNNING = 1;
const STATUS_FINISHED = 2;
const STATUS_FAILED = 3;
/**
* @var int status of the task execution at the moment
*/
public $status = self::STATUS_NEW;
/**
* @var string last date and time of task start
*/
public $lastStart;
/**
* @var string last date and time of task stop
*/
public $lastStop;
/**
* @var int PID of running task instance
*/
public $pid;
/**
* @var string unique hash from CronTask instance
*/
private $id;
/**
* @var string name from CronTask instance
*/
private $name;
/**
* @var string console command from CronTask instance
*/
private $command;
/**
* @var string console command action from CronTask instance
*/
private $action;
/**
* @var array list of params from CronTask instance
*/
private $params;
/**
* @var bool uniqueness flag from CronTask instance
*/
private $unique;
/**
* @var string shell command to run task wrapper
*/
private $_wrapperCommand;
/**
* @var CronService application component instance
*/
private $_service;
/**
* Static method to create new instance and get information about last execution. Used in console daemon action.
* @param CronTask $task configured task instance
* @param CronService $service application service component
* @return CronProcess
*/
public static function createByTask(CronTask $task, CronService $service)
{
$process = new self($service, $task->getId());
$process->readInfoFile();
$process->unique = $task->isUnique();
$process->name = $task->getName();
$process->command = $task->getCommand();
$process->action = $task->getCommandAction();
$params = array();
foreach ($task->getParams() as $param => $value) {
$params[] = "--{$param}={$value}";
}
$process->params = $params;
$app = Yii::app()->getBasePath() . DIRECTORY_SEPARATOR . 'yiic';
$output = $task->getOutputFile() ? "> {$task->getOutputFile()}" : '>> /dev/null';
$process->_wrapperCommand = "{$app} cron run --id={$task->getId()} {$output} 2>&1 & echo $!";
return $process;
}
/**
* Static method to create process instance by task identifier. Used in special wrapper command to run specified
* task and log it's execution.
* @param string $id
* @param CronService $service application service component
* @return self
*/
public static function createById($id, CronService $service)
{
$process = new self($service, $id);
$process->readInfoFile(true);
return $process;
}
/**
* Get if task process is running at the moment
* @return bool
*/
public function isRunning()
{
return ($this->status === self::STATUS_RUNNING);
}
/**
* Save info file and task wrapper
*/
public function runWrapper()
{
$this->saveInfoFile();
exec($this->_wrapperCommand);
}
/**
* Run console command saved in the process. Handle normal and abnormal termination (save status to lock file and
* log message)
*/
public function run()
{
$this->checkIsCLI();
if ($this->unique && $this->isRunning()) {
CronService::log(
"Cannot run task '{$this->name}': it is still running and does not allow overlapping (unique)",
CLogger::LEVEL_WARNING
);
return;
}
$this->pid = getmypid();
$this->status = self::STATUS_RUNNING;
$this->lastStart = date('Y-m-d H:i:s');
$this->saveInfoFile();
CronService::log("Task '{$this->name}' started (PID: {$this->pid})");
// to log task failure if error or exception occurred
register_shutdown_function(array($this, 'shutdown'));
/** @var CConsoleCommand $command */
$command = Yii::app()->getCommandRunner()->createCommand($this->command);
$command->init();
$params = $this->params;
$action = $this->action ?: $command->defaultAction;
array_unshift($params, $action);
$command->run($params);
// normal end of the task process
$this->status = self::STATUS_FINISHED;
CronService::log("Task '{$this->name}' successfully finished");
}
/**
* Called by PHP on shutdown process. Checks if task was successfully finished.
* Allowed only in CLI mode.
* @throws CException
*/
public function shutdown()
{
$this->checkIsCLI();
$this->pid = null;
$this->lastStop = date('Y-m-d H:i:s');
// not finished in usual way (exception or another error)
if ($this->status === self::STATUS_RUNNING) {
$this->status = self::STATUS_FAILED;
}
$this->saveInfoFile();
if ($this->status === self::STATUS_FAILED) {
CronService::log(
"Task '{$this->name}' unexpectedly finished. Check logs and console command",
CLogger::LEVEL_ERROR
);
// force flush application logs
Yii::getLogger()->flush(true);
}
}
/**
* Private constructor to prevent manual instantiating outside of the special static methods
* @param CronService $service
* @param string $id
*/
private function __construct(CronService $service, $id)
{
$this->_service = $service;
$this->id = $id;
}
/**
* Load file with information about process (JSON content). Decode data and set attributes of current instance.
* Identifier attribute should be set before calling this method.
* @param bool|false $exceptionNoFile
* @throws RuntimeException
*/
private function readInfoFile($exceptionNoFile = false)
{
$file = $this->getInfoFileName();
if (file_exists($file) && is_readable($file)) {
$data = json_decode(file_get_contents($file), true);
if (!empty($data)) {
foreach ($data as $key => $value) {
$this->$key = $value;
}
$this->checkProcessAvailability();
}
} else {
if ($exceptionNoFile) {
throw new RuntimeException('Process info file is not available. Wrong hash?');
}
}
}
/**
* Check if task process really active and running
*/
private function checkProcessAvailability()
{
if ($this->pid !== null && $this->status === self::STATUS_RUNNING) {
exec("ps -p {$this->pid} -o pid", $output);
if (count($output) != 2) {
$this->pid = null;
$this->status = self::STATUS_FAILED;
CronService::log(
"Task '{$this->name}' unexpectedly finished. Check logs and console command",
CLogger::LEVEL_ERROR
);
}
}
}
/**
* Serialize current instance attributes to the file.
* Allowed only in CLI mode.
* @return void
*/
private function saveInfoFile()
{
$this->checkIsCLI();
$data = get_object_vars($this);
unset($data['_service'], $data['_wrapperCommand']);
file_put_contents($this->getInfoFileName(), json_encode($data), LOCK_EX);
@chmod($this->getInfoFileName(), 0777);
}
/**
* Generate name of the file with process information
* @return string
*/
private function getInfoFileName()
{
return $this->_service->getRuntimePath() . DIRECTORY_SEPARATOR . $this->id . '.json';
}
/**
* Check current PHP_SAPI constant value. If not 'cli' (console mode) - throw runtime exception.
* @throws RuntimeException
*/
private function checkIsCLI()
{
if (PHP_SAPI !== 'cli') {
throw new RuntimeException('You cannot run cron process in non CLI mode');
}
}
}