-
Notifications
You must be signed in to change notification settings - Fork 1
/
Caterpillar.php
280 lines (226 loc) 路 7.45 KB
/
Caterpillar.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
<?php
class Caterpillar {
private $_tube;
private $_bs;
private $_server;
private $_port;
private $_log_path;
// workers
private $_pids;
private $_child_id;
public static $PCNTL_CONTINUE;
private static $FILE = 1;
private static $ERR = 2;
public function __construct($tube=false, $server='127.0.0.1', $port=11300, $log_path=false) {
if($tube == false)
$tube = 'default';
if($log_path == false)
$log_path = './log/';
$this->_bs = new Pheanstalk\Pheanstalk($server, $port);
$this->_tube = $tube;
$this->_server = $server;
$this->_port = $port;
$this->_log_path = $log_path;
}
public function queue($class, $method, $args=[], $opts=[]) {
$defaults = [
'priority' => 1024,
'delay' => 0,
'ttr' => 300
];
$opts = array_merge($defaults, $opts);
if(!is_array($args))
$args = [$args];
$this->_bs->putInTube($this->_tube,
json_encode(array('class'=>$class, 'method'=>$method, 'args'=>$args)),
$opts['priority'],
$opts['delay'],
$opts['ttr']);
}
private function _process(&$job) {
$data = json_decode($job->getData());
if(!is_object($data) || !property_exists($data, 'class')) {
echo "Found bad job:\n";
print_r($data);
echo "\n";
$this->_bs->delete($job);
return;
}
echo "===============================================\n";
echo "# Beginning job: " . $data->class . '::' . $data->method . "\n";
call_user_func_array([$data->class, $data->method], $data->args);
echo "\n# Job Complete\n-----------------------------------------------\n\n";
$this->_bs->delete($job);
}
public function print_stats() {
$allTubes = $this->_bs->listTubes();
$fields = array(
'current-jobs-urgent' => 'urgent',
'current-jobs-ready' => 'ready',
'current-jobs-delayed' => 'delayed',
'current-jobs-buried' => 'buried',
'current-using' => 'using',
'current-watching' => 'watching'
);
echo sprintf('%30s', 'tube');
foreach($fields as $k=>$v) {
echo "\t" . $v;
}
echo "\n";
foreach($allTubes as $tube) {
echo sprintf('%30s', $tube) . "\t";
$stats = $this->_bs->statsTube($tube);
foreach($fields as $k=>$v) {
echo $stats->{$k} . "\t";
}
echo "\n";
}
echo "\n";
}
private function _run_worker() {
$this->_bounce_log();
$this->_log("watching tube: " . $this->_tube);
$this->_bs->watch($this->_tube)->ignore('default');
while(self::$PCNTL_CONTINUE)
{
if(($job=$this->_bs->reserve(2)) == FALSE)
continue;
$this->_log("processing job");
$this->_process($job);
} // while true
$this->_log("worker finished!");
}
public function run_workers($num, $background=false) {
if($background) {
$this->_daemonize();
}
$this->_write_pidfile();
$this->_pids = array();
for($child_id = 0; $child_id < $num; $child_id++) {
// Fork now
$pid = pcntl_fork();
if($pid === 0) {
// This is the child process
self::$PCNTL_CONTINUE = TRUE;
// Set up the child signal handler to catch SIGTERM and prevent executing the next while() loop
// pcntl_signal(SIGTERM, function($sig){
// #$this->_log("Child caught SIGTERM");
// #self::$PCNTL_CONTINUE = FALSE;
// });
// pcntl_signal(SIGHUP, function($sig){
// echo "CHILD CAUGHT SIGHUP\n";
// $this->_bounce_log();
// });
$this->_log("Child process started");
$c = new Caterpillar($this->_tube, $this->_server, $this->_port, $this->_log_path);
$c->_child_id = $child_id;
$c->_run_worker();
$this->_log("Child finished gracefully");
die();
} else {
// This is the parent process
$this->_pids[] = $pid;
}
}
////////////////////////////////////////////////////////////////////////////////////////
// Everything below this line is only run in the parent process
$this->_child_id = FALSE;
$this->_bounce_log();
$this->_log("Parent started " . count($this->_pids) . " child processes", self::$FILE|self::$ERR);
// pcntl_signal(SIGHUP, function($sig){
// $this->_bounce_log();
// $this->_log("Parent caught SIGHUP");
// foreach($this->_pids as $p) {
// posix_kill($p, SIGHUP);
// }
// $this->_log('Sent SIGHUP to ' . count($this->_pids) . " children");
// });
// Pass off USR1 signals to the children
// pcntl_signal(SIGUSR1, function($sig){
// $this->_log("Parent caught SIGUSR1! Sending to children...");
// foreach($this->_pids as $p) {
// posix_kill($p, SIGUSR1);
// }
// $this->_log('Done sending USR1 to ' . count($this->_pids) . " children");
// });
pcntl_signal(SIGTERM, function($sig){
$this->_log("Parent caught SIGTERM");
foreach($this->_pids as $p) {
posix_kill($p, SIGTERM);
}
$this->_log('Done killing ' . count($this->_pids) . " children");
// After the children die, execution will finally reach "parent finished" below
});
// Trap CTRL+C signals in case the script was run from a terminal
pcntl_signal(SIGINT, function($sig){
$this->_log("CTRL+C! Killing children...", self::$FILE+self::$ERR);
foreach($this->_pids as $p) {
posix_kill($p, SIGTERM);
}
$this->_log('Done killing ' . count($this->_pids) . " children", self::$FILE+self::$ERR);
});
// Keep waiting for the children until they all exit
foreach($this->_pids as $p) {
while(0 == pcntl_waitpid($p, $status, WNOHANG)) {
pcntl_signal_dispatch();
sleep(1);
}
}
$this->_log("Parent finished", self::$FILE+self::$ERR);
$this->_remove_pidfile();
}
public function run_foreground() {
$c = new Caterpillar($this->_tube, $this->_server, $this->_port, $this->_log_path);
$c->_child_id = 0;
self::$PCNTL_CONTINUE = TRUE;
$c->_run_worker();
}
private function _daemonize() {
// Fork the current process
$pid = pcntl_fork();
// Check to make sure it forked okay
if($pid == -1) {
echo "\n Error: The process failed to fork.\n";
} else if($pid) {
echo "Daemon started with pid: $pid\n";
//This is the parent process.
exit;
} else {
//We're now in the child process.
}
$this->_bounce_log();
// Detach from the terminal window, so that we stay alive when it is closed
if(posix_setsid() == -1) {
echo "\n Error: Unable to detach from the terminal window.\n";
}
}
private function _log($msg, $dst=1) {
if($dst & self::$FILE) {
echo '[' . posix_getpid() . "] $msg\n";
}
if($dst & self::$ERR) {
fwrite(STDERR, '[' . posix_getpid() . "] $msg\n");
}
}
private function _write_pidfile() {
$pidFile = fopen($this->_log_path . $this->_tube . '.pid', 'w');
fwrite($pidFile, posix_getpid());
fclose($pidFile);
}
private function _remove_pidfile() {
$pidFile = $this->_log_path . $this->_tube . '.pid';
unlink($pidFile);
}
private function _bounce_log() {
global $STDOUT;
if(isset($STDOUT))
fclose($STDOUT);
else
fclose(STDOUT);
if(isset($this->_child_id) && $this->_child_id !== FALSE)
$filename = $this->_log_path . $this->_tube . '-' . $this->_child_id . '.log';
else
$filename = $this->_log_path . $this->_tube . '.log';
$STDOUT = fopen($filename, 'a');
}
}