/
Process.php
306 lines (234 loc) · 8.42 KB
/
Process.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
<?php
/* Process.php | Daemon dequeues and executes processes from the database. */
require_once(__DIR__ . '/Initialize.php');
use core\ContentDecoder;
use core\Database;
use core\Log;
use core\Node;
use core\Utility;
use Cron\CronExpression;
use framework\Configuration as conf;
use framework\Process;
use framework\exceptions\ProcessException;
$opts = (new framework\Optimist)
->options('nohup', array(
'alias' => 'n'
, 'describe' => 'Force nohup process spawn.'
))
->options('cron', array(
'alias' => 'c'
, 'describe' => 'Indicates the process is invoked from cron job, only affects the log.'
))
->argv;
// Process cleanup
if ( @$opts['cleanup'] ) {
$affectedRows = 0;
// Check orphaned process in process table and delete it.
$pids = array_filter(array_map(function($line) {
if ( preg_match('/^\w+\s+(\d+)/', $line, $matches) ) {
return (int) $matches[1];
}
return null;
}, explode("\n", `ps aux | grep 'php\\|node'`)));
if ( $pids ) {
// Delete normal orphan processes
$res = Database::query('DELETE FROM `'.FRAMEWORK_COLLECTION_PROCESS.'`
WHERE `type` NOT IN (\'permanent\', \'cron\')
AND `pid` IS NOT NULL
AND `pid` NOT IN ('.Utility::fillArray($pids).')', $pids);
if ( $res ) {
$affectedRows+= $res->rowCount();
}
// Delete cron process only when current time is ahead of start_time
$res = Database::query('DELETE FROM `'.FRAMEWORK_COLLECTION_PROCESS.'`
WHERE `type` = \'cron\'
AND `pid` = 0
AND `pid` NOT IN ('.Utility::fillArray($pids).')', $pids);
if ( $res ) {
$affectedRows+= $res->rowCount();
}
// Clear pid of dead permanent process
$res = Database::query('UPDATE `'.FRAMEWORK_COLLECTION_PROCESS.'` SET `pid` = NULL
WHERE `type` = \'permanent\' AND `pid` IS NOT NULL AND `pid` NOT IN ('.Utility::fillArray($pids).')', $pids);
if ( $res ) {
$affectedRows+= $res->rowCount();
}
}
unset($res, $pids);
if ( $affectedRows ) {
Log::debug(sprintf('Process cleanup, %d processes removed.', $affectedRows));
}
die;
}
// Cron processes
if ( @$opts['cron'] ) {
Log::debug('Cron started process.');
$scheduler = function($schedule) {
$nextTime = CronExpression::factory($schedule['schedule'])->getNextRunDate()->format('Y-m-d H:i:s');
/*! Note
* The purpose of schedule_name alias is to use a less common name, and
* leave the "name" property open for in-process use.
*/
$schedules = Node::get(array(
Node::FIELD_COLLECTION => FRAMEWORK_COLLECTION_PROCESS
, 'start_time' => $nextTime
, 'command' => $schedule['command']
, 'schedule_name' => $schedule['name']
));
if ( !$schedules ) {
$schedule =
[ 'command' => $schedule['command']
, 'start_time' => $nextTime
, 'schedule_name' => $schedule['name']
, '$type' => 'cron'
, '$spawn' => false
];
Log::debug('Scheduling new process', $schedule);
Process::enqueue($schedule['command'], $schedule);
}
};
// Configuration based crontab
array_map($scheduler, (array) conf::get('crontab::schedules'));
}
// Avoid forking connection crash, renew the connection.
Database::disconnect();
// Forks then exits the parent.
// Use nohup if internal forking is not supported.
if ( !function_exists('pcntl_fork') ) {
$ret = shell_exec('nohup ' . Process::EXEC_PATH . ' --nohup >/dev/null 2>&1 & echo $!');
if ( !$ret ) {
Log::error('Process cannot be spawn, please review your configuration.');
}
die;
}
elseif ( @$opts['n'] ) {
$pid = 0; // fork mimic
}
else {
$pid = pcntl_fork();
}
// parent: $forked == false
// child: $forked == true
$forked = $pid == 0;
// unset($pid);
// parent will die here
if ( !$forked ) {
exit(1);
}
// Avoid forking connection crash, renew the connection.
Database::disconnect();
// Get maximum allowed connections before table lock.
$capLimit = (int) @conf::get('system::crontab.process_limit');
if ( !$capLimit ) {
$capLimit = Process::MAXIMUM_CAPACITY;
}
// Start transaction before lock tables.
Database::beginTransaction();
// Pick next awaiting process
Database::locKTables([
FRAMEWORK_COLLECTION_PROCESS . ' READ'
]);
$res = (int) Database::fetchField('SELECT IFNULL(SUM(`capacity`), 0) as occupation
FROM `' . FRAMEWORK_COLLECTION_PROCESS . '`
WHERE `pid` IS NOT NULL AND `pid` > 0');
Database::unlockTables(true);
if ( $res >= $capLimit ) {
Log::debug('Active processes has occupied maximum server capacity, daemon exits.');
Database::rollback();
die;
}
unset($res, $capLimit);
Database::lockTables(array(
FRAMEWORK_COLLECTION_PROCESS . ' LOW_PRIORITY WRITE'
, FRAMEWORK_COLLECTION_PROCESS . ' as `active` LOW_PRIORITY WRITE'
, FRAMEWORK_COLLECTION_PROCESS . ' as `inactive` LOW_PRIORITY WRITE'
));
$process = Database::fetchRow('SELECT `inactive`.* FROM `'. FRAMEWORK_COLLECTION_PROCESS .'` as `inactive`
LEFT JOIN ( SELECT `type`, SUM(`capacity`) as `occupation` FROM `' . FRAMEWORK_COLLECTION_PROCESS . '`
WHERE `pid` IS NOT NULL GROUP BY `type` ) as `active`
ON `active`.`type` = `inactive`.`type`
WHERE `timestamp` <= CURRENT_TIMESTAMP
AND `start_time` <= CURRENT_TIMESTAMP
AND `inactive`.`pid` IS NULL
ORDER BY `occupation`, `weight` DESC, `id`
LIMIT 1;');
// No waiting jobs in queue.
if ( !$process ) {
Database::unlockTables(true);
Database::rollback();
Log::debug('No more jobs to do, suicide.');
die;
}
$processContents = (array) ContentDecoder::json($process[Node::FIELD_VIRTUAL], 1);
unset($process[Node::FIELD_VIRTUAL]);
$process+= $processContents;
unset($processContents);
$res = Database::query('UPDATE `' . FRAMEWORK_COLLECTION_PROCESS . '` SET `pid` = ?
WHERE `id` = ? AND `pid` IS NULL LIMIT 1',
[ getmypid(), $process['id'] ]);
// Commit transaction
Database::unlockTables(true);
Database::commit();
if ( $res->rowCount() < 1 ) {
Log::warning('Unable to update process pid, worker exits.');
die;
}
else {
$process['pid'] = getmypid();
$process[Node::FIELD_COLLECTION] = FRAMEWORK_COLLECTION_PROCESS;
}
// Check if $env specified in option
if ( @$_SERVER['env'] ) {
$_SERVER['env'] = ContentDecoder::json($_SERVER['env'], 1);
}
// More debug logs
Log::debug("Execute process: $process[command]");
// Spawn process and retrieve the pid
$proc = false;
do {
$proc = proc_open($process['command'], array(
array('pipe', 'r')
, array('pipe', 'w')
, array('pipe', 'e')
), $pipes, null, @$_SERVER['env']);
if ( $proc ) {
break;
}
else {
usleep(Process::$spawnCaptureInterval * 1000000);
}
}
while ( ++$retryCount < Process::$spawnCaptureCount );
if ( !$proc ) {
throw new ProcessException('Unable to spawn process, please check error logs.');
}
// Log the process output if available
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
if ( "$stdout$stderr" ) {
$method = $stderr ? 'error' : 'info';
Log::$method(sprintf('Output captured from command line: %s', $process['command']),
array_filter(array('stdout' => $stdout, 'stderr' => $stderr)));
unset($method);
}
unset($stdout, $stderr);
// Handles cleanup after process exit
switch ( strtolower($process['type']) ) {
// Permanent processes will be restarted upon death
case 'permanent':
core\Database::query('UPDATE `'.FRAMEWORK_COLLECTION_PROCESS.'` SET `pid` = NULL WHERE `id` = ?', $process['id']);
Log::debug('Permanent process died, clearing pid.', [$res, $process]);
break;
// Sets pid to 0, prevents it fire again and double enqueue of the same time slot.
case 'cron':
core\Database::query('UPDATE `'.FRAMEWORK_COLLECTION_PROCESS.'` SET `pid` = 0 WHERE `id` = ?', $process['id']);
break;
// Deletes the process object upon exit
default:
$process = array_select($process, array(Node::FIELD_COLLECTION, 'id', /*'type', 'weight', 'capacity', */'pid'));
$res = Node::delete($process);
Log::debug("Deleting finished process, affected rows: $res.", [$res, $process]);
break;
}
// Recursive process, spawn another worker.
Process::spawnWorker(@$_SERVER['env']);