/
class.MTDaemon.php
660 lines (590 loc) · 24.1 KB
/
class.MTDaemon.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
<?php
/**
* MultiThreaded Daemon (MTD)
*
* Copyright (c) 2007, Benoit Perroud
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @package MTD
* @author Benoit Perroud <ben@migtechnology.ch>
* @copyright 2007 Benoit Perroud
* @license http://www.gnu.org/copyleft/gpl.html
* @version $Id: class.MTDaemon.php 8 2007-10-19 09:16:00Z killerwhile $
*
* See http://code.google.com/p/phpmultithreadeddaemon/
* and http://phpmultithreaddaemon.blogspot.com/ for more information
*
*/
/*
* Modifications by Daniel Kadosh, Affinegy Inc., June 2009
* Made many enhancements for robustness:
* - Truly daemonized by starting process group with posix_setsid()
* - Surrounded key items in try/catch for proper logging
* - Handling of SIGTERM/ SIGQUIT = no more children spawned, wait for all threads to die.
* - Handling of SIGHUP = call to loadConfig() method
* - Created PID file to ensure only 1 copy of the daemon is running
* - Full cleanup of semaphores & PID file on exit
*
*/
declare (ticks=1);
require_once dirname(__FILE__).'/class.MTLog.php';
/*
* Added code for better daemon behavior by handling signals, from
* http://www.van-steenbeek.net/?q=php_pcntl_fork
*/
ini_set("max_execution_time", "0"); // Give us eternity to execute the script. We can always kill -9
ini_set("max_input_time", "0");
set_time_limit(0);
$nSignalReceived = NULL;
function mtd_sig_handler($signo) {
// Just capture signal in a global, deal with it in handle() method
// TODO: multiple unhandled signals received would mean last one wins...
global $nSignalReceived;
$sSigMsg = "";
switch ( $signo ) {
case SIGQUIT: // Treat same as SIGTERM
case SIGTERM:
$nSignalReceived = SIGTERM;
$sSigMsg = "SIGTERM = terminate. Will end once all children die.";
break;
case SIGHUP:
$nSignalReceived = SIGHUP;
$sSigMsg = "SIGHUP = hangup. Will re-read config files.";
break;
default:
$sSigMsg = "$signo -- ignored.";
break;
}
MTLog::getInstance()->warn('Received signal '.$sSigMsg);
}
pcntl_signal(SIGTERM, "mtd_sig_handler");
pcntl_signal(SIGHUP, "mtd_sig_handler");
// Main class
abstract class MTDaemon {
/*
* Configuration vaiables
*/
// max concurrent threads
// should be implemented with sem_get('name', $max_aquire) but this can't be dynamically updated as this var.
protected $max_threads = 4;
// sleep time when no job
protected $idle_sleep_time = 5;
/*
* Internal constants
*/
const _INDEX_DATA = 0; // shared data goes here.
const _INDEX_THREADS = 1; // how many threads are working
const _INDEX_SLOTS = 2; // which slot do the current thread use ?
/*
* Internal variables
*/
protected $shm; // = ftok(__FILE__, 'g');
protected $shared_data; // = shm_attach($this->shm);
protected $mutex; // lock critical path, used in lock() and unlock()
protected $mutex_main_process; // lock main process only. Children can continue to run
protected $mutex_children_processes; // lock children processes only. Main can continue to run
protected $main_thread_pid;
protected $sPIDFileName;
/*
* Constructor
*
* @params $threads : number of concurrent threads, default 4
* @params $idelsleeptime : time to sleep when no job ready (getNext return null), in seconds, default 5
*/
public function __construct($threads = null, $idlesleeptime = null, $sPIDFileName = null) {
global $argv;
$this->main_thread_pid = posix_getpid();
// Ensure a PID file is created
if ( !$sPIDFileName ) $sPIDFileName = $this->makePIDFileName();
$this->sPIDFileName = $sPIDFileName;
if ( !$this->checkPIDFile() ) {
throw new Exception('Cannot secure PID file '.$this->sPIDFileName);
}
// Daemonize -- fork & disconnect from tty
// NOTE: stdout/stderr cannot be automatically redirected to logger,
// so avoid print & echo or start daemon in CLI with ">& /dev/null"
$newpid = pcntl_fork();
if ( $newpid==-1 ) {
throw new Exception('Cannot fork porcess');
} elseif ( $newpid ) {
print $argv[0].": Starting daemon under pid=$newpid\n";
exit();
}
if ( !posix_setsid() ) {
throw new Exception('Cannot dettach from terminal!');
}
// Init some variables
if ( $threads ) $this->max_threads = $threads;
if ( $idlesleeptime ) $this->idle_sleep_time = $idlesleeptime;
if ( !$this->writePIDFile() ) {
// Should never happen, unless disk full...
throw new Exception('Cannot write to PID file!');
}
}
function makePIDFileName() {
$name=join('_',$_SERVER["argv"]);
$name=preg_replace('/\W/', '_',$name);
$rnd=rand();
$key="/tmp/mtd3_".$name."_".$this->main_thread_pid."_".$rnd."_.pid";
return $key;
}
/*
* Manage PID file
*/
protected function checkPIDFile() {
// Ensure no currently running daemon
if ( file_exists($this->sPIDFileName) ) {
$nOldPID = trim(file_get_contents($this->sPIDFileName));
// Clean up if previous daemon didn't clean up after itself
// and handle EPERM error
// http://www.php.net/manual/en/function.posix-kill.php#82560
$bRunning = posix_kill($nOldPID, 0);
if ( posix_get_last_error()==1 ) $bRunning = true;
if ( !$bRunning ) unlink($this->sPIDFileName);
/*
* Could be dangerous to kill old daemon...
MTLog::getInstance()->warn('Killing old deamon from '.$this->sPIDFileName);
if ( posix_kill($nOldPID,SIGTERM) ) {
// Sent signal, give it a chance to die
sleep ($this->idle_sleep_time * 2);
}
*/
}
if ( file_exists($this->sPIDFileName) ) {
MTLog::getInstance()->error('Daemon pid='.$nOldPID.' still running according to PID file '.$this->sPIDFileName);
return false;
}
if ( !touch($this->sPIDFileName) ) {
MTLog::getInstance()->error('Cannot create PID file '.$this->sPIDFileName);
return false;
}
return true;
}
/*
*
*/
protected function writePIDFile() {
// Just touched it, so MUST be able to write to it!
if ( !file_put_contents($this->sPIDFileName, $this->main_thread_pid) ) {
MTLog::getInstance()->error('Cannot write PID file '.$this->sPIDFileName);
return false;
}
// Success!
MTLog::getInstance()->debug('Successfully created PID file '.$this->sPIDFileName);
return true;
}
/*
*
*/
public function getPIDFile() {
return $this->sPIDFileName;
}
/*
* Hook called just before the main loop.
*
* Remark : cleanup code goes here.
*/
protected function _prerun() {
global $argv;
MTLog::getInstance()->info($argv[0].': Starting daemon with '.$this->max_threads.' slots');
$this->shm = ftok($this->sPIDFileName, 'g'); // global shm
$this->shared_data = shm_attach($this->shm);
$this->mutex = sem_get($this->shm);
//$this->mutex_main_process = sem_get(ftok($this->sPIDFileName, 'm'));
//$this->mutex_children_processes = sem_get(ftok($this->sPIDFileName, 'c'));
shm_put_var($this->shared_data, self::_INDEX_DATA, array());
$this->setThreads(0);
$slots = array();
for ( $i = 0; $i<$this->max_threads; $i++ ) {
$slots[] = false;
}
shm_put_var($this->shared_data, self::_INDEX_SLOTS, $slots);
// Call to optional method
$this->loadConfig();
}
/*
* Hook called just after the main loop
* Cleans up all semaphores and removes PID file
*/
protected function _postrun() {
global $argv;
MTLog::getInstance()->debug($argv[0].': _postrun() called.');
while ( ($nThreads = $this->getThreads(true))>0 ) {
$res=pcntl_wait($status);
if ( $res>0 ) {
MTLog::getInstance()->info('_postrun Finishing child with pid '.$res);
} else {
break;
}
}
// Clean up all UNIX semaphore data
shm_remove ($this->shared_data);
sem_remove ($this->mutex);
//sem_remove ($this->mutex_main_process);
//sem_remove ($this->mutex_children_processes);
shm_detach ($this->shared_data);
unlink ($this->sPIDFileName);
MTLog::getInstance()->info($argv[0].': daemon exited');
}
/*
* Main loop, request next job using getNext() and execute run($job) in a separate thread
* _prerun and _postrun hooks are called before and after the main loop -> usefull for cleanup and so on.
*/
public function handle() {
global $nSignalReceived;
$this->run = true;
$this->bTerminate = false;
$this->_prerun();
while ( $this->run ) {
/*
* Terminating all child, to not let some zombie leaking the memory.
*/
MTLog::getInstance()->debug2('-- Next iteration ');
$this->lock();
// HACK : avoid zombie and free earlier the memory
do {
$res = pcntl_wait($status, WNOHANG);
MTLog::getInstance()->debug2('$res = pcntl_wait($status, WNOHANG); called with $res = '.$res);
if ( $res>0 ) MTLog::getInstance()->debug('(finishing child with pid '.$res.')');
} while ( $res>0 );
/*
* Process signals now, before waiting for a slot to free up
*/
if ( $nSignalReceived ) {
switch ( $nSignalReceived ) {
case SIGTERM:
$this->bTerminate = true;
break;
case SIGHUP:
$this->loadConfig();
break;
default: break;
}
$nSignalReceived = NULL;
}
/*
* Loop until a slot frees
*/
while ( !$this->bTerminate && !$this->hasFreeSlot() ) {
$this->unlock();
MTLog::getInstance()->debug('No more free slot, waiting');
$res = pcntl_wait($status); // wait until a child ends up
MTLog::getInstance()->debug2('$res = pcntl_wait($status); called with $res = '.$res);
if ( $res>0 ) {
MTLog::getInstance()->debug('Finishing child with pid '.$res);
} else {
MTLog::getInstance()->error('Outch1, this souldn\'t happen. Verify your implementation ...');
$this->run = false;
break;
}
$this->lock();
}
/*
* Handle Outch1 error and
* Double-check for signal before starting a new child
*/
if ( !$this->run ) continue;
if ( $nSignalReceived ) {
$this->unlock();
continue;
}
/*
* If terminating, just loop until all jobs are finished.
*/
if ( $this->bTerminate ) {
MTLog::getInstance()->info('Terminating: Waiting for '.$this->getThreads().' threads to end');
while ( ($nThreads = $this->getThreads())>0 ) {
$this->unlock();
MTLog::getInstance()->debug('Waiting for '.$nThreads.' threads to end');
$res = pcntl_wait($status); // wait until a child ends up
MTLog::getInstance()->debug2('$res = pcntl_wait($status); called with $res = '.$res);
if ( $res>0 ) {
MTLog::getInstance()->debug('Finishing child with pid '.$res);
} else {
MTLog::getInstance()->error('Outch3, this souldn\'t happen. Verify your implementation ...');
$this->run = false;
break;
}
$this->lock();
}
if ( $this->run ) $this->unlock(); // don't double unlock
$this->run = false;
continue;
}
$slot = $this->requestSlot();
$this->incThreads();
$this->unlock();
if ( $slot===null ) {
var_dump(shm_get_var($this->shared_data, self::_INDEX_DATA));
var_dump(shm_get_var($this->shared_data, self::_INDEX_THREADS));
var_dump(shm_get_var($this->shared_data, self::_INDEX_SLOTS));
MTLog::getInstance()->error('Outch2, this souldn\'t happen. Verify your implementation ...');
$this->run = false; // Quit now
continue;
}
/*
* Request next action to handle
*/
try {
$next = &$this->getNext($slot);
} catch( Exception $e ) {
MTLog::getInstance()->error('getNext() method: '.$e->getMessage());
$this->bTerminate = true;
continue;
}
/*
* If no job
*/
if ( !$next ) {
// Within parent process, release slot & sleep for a bit...
MTLog::getInstance()->debug('No job, sleeping at most '.$this->idle_sleep_time.' sec ... ');
// TODO : waiting for signal pushed into a queue when inserting a new job.
$this->lock();
$this->releaseSlot($slot);
$this->decThreads();
$this->unlock();
sleep ($this->idle_sleep_time);
continue;
} else {
// Fork off new child & do some work
$pid = pcntl_fork();
if ( $pid==-1 ) {
MTLog::getInstance()->error('[fork] Duplication impossible');
// $this->run = false; // Quit now
$this->bTerminate = true; // Wait till children finish
continue;
} else if ( $pid ) {
unset ($next);
usleep(10); // HACK : give the hand to the child -> a simple way to better handle zombies
continue;
} else {
MTLog::getInstance()->debug('Executing thread #'.posix_getpid().' in slot '.number_format($slot));
try {
$res = $this->run($next, $slot);
} catch( Exception $e ) {
MTLog::getInstance()->error('run() method: '.$e->getMessage());
$res = -1;
}
unset ($next);
$this->lock();
$this->releaseSlot($slot);
$this->decThreads();
$this->unlock();
exit ($res);
}
}
}
$this->_postrun();
exit (0);
}
/*
* Called at init, plus at SIGHUP signal
* This function is run in the parent thread
*/
//abstract public function loadConfig();
public function loadConfig(){}
/*
* Request data of the next element to run in a thread
* This function will return the next element to process, or null if there is currently no job and the daemon should wait.
*
* slot = where the thread will be executed
* return null or false if no job currently
*/
abstract public function getNext($slot);
/*
* Process the element fetched by getNext in a new thread
* This function is run in a separated thread (after forking) and take as argument the element to process (given by getNext).
*
* slot = where the thread will be executed
* return the exiting status of the thread
*/
abstract public function run($next, $slot);
/*
*
*/
protected function lock() {
MTLog::getInstance()->debug2('[lock] lock');
$res = @sem_acquire($this->mutex);
if ( !$res ) exit(-1);
}
/*
*
*/
protected function unlock() {
MTLog::getInstance()->debug2('[lock] unlock');
$res = @sem_release($this->mutex);
if ( !$res ) exit(-1);
}
/*
*
*/
protected function lockMain() {
MTLog::getInstance()->debug2('[lock] lock main process');
$res = sem_acquire($this->mutex_main_process);
if ( !$res ) exit(-1);
}
/*
*
*/
protected function unlockMain() {
MTLog::getInstance()->debug2('[lock] unlock main process');
$res = sem_release($this->mutex_main_process);
if ( !$res ) exit(-1);
}
/*
*
*/
protected function lockChildren() {
MTLog::getInstance()->debug2('[lock] lock children processes');
$res = sem_acquire($this->mutex_children_processes);
if ( !$res ) exit(-1);
}
/*
*
*/
protected function unlockChildren() {
MTLog::getInstance()->debug2('[lock] unlock children processes');
$res = sem_release($this->mutex_children_processes);
if ( !$res ) exit(-1);
}
/*
* Get a shared var based on hash.
*
* Return null if the var doesn't exist.
*/
protected function getVar($name, $lock = false) {
if ( $lock ) $this->lock();
$vars = shm_get_var($this->shared_data, self::_INDEX_DATA);
$value = (isset($vars[$name])) ? $vars[$name] : null;
if ( $lock ) $this->unlock();
return $value;
}
/*
* Set a shared var.
*
* Remark : the var should be serialized.
*/
protected function setVar($name, $value, $lock = false) {
if ( $lock ) $this->lock();
$vars = shm_get_var($this->shared_data, self::_INDEX_DATA);
$vars[$name] = $value;
$res = shm_put_var($this->shared_data, self::_INDEX_DATA, $vars);
if ( $lock ) $this->unlock();
return $res;
}
/*
* Get the number of running threads
*/
protected function getThreads($lock = false) {
if ( $lock ) $this->lock();
$res = shm_get_var($this->shared_data, self::_INDEX_THREADS);
if ( $lock ) $this->unlock();
return $res;
}
/*
* Set the number of running threads
*/
protected function setThreads($threads, $lock = false) {
if ( $lock ) $this->lock();
$res = shm_put_var($this->shared_data, self::_INDEX_THREADS, $threads);
if ( $lock ) $this->unlock();
return $res;
}
/*
* Increment the number of running threads
*/
protected function incThreads($lock = false) {
if ( $lock ) $this->lock();
$threads = $this->getThreads();
$res = shm_put_var($this->shared_data, self::_INDEX_THREADS, $threads + 1);
MTLog::getInstance()->debug('incThreads, $threads = '.($threads + 1));
if ( $lock ) $this->unlock();
return $res;
}
/*
* Decrement the number of running threads
*/
protected function decThreads($lock = false) {
if ( $lock ) $this->lock();
$threads = $this->getThreads();
$res = shm_put_var($this->shared_data, self::_INDEX_THREADS, $threads - 1);
MTLog::getInstance()->debug('decThreads, $threads = '.($threads - 1));
if ( $lock ) $this->unlock();
return $res;
}
/*
* Return true if any slot is free
*/
protected function hasFreeSlot() {
$threads = $this->getThreads();
$res = ($threads<$this->max_threads) ? true : false;
MTLog::getInstance()->debug('Has free slot ? => #running threads = '.$threads);
return $res;
}
/*
* Assign a free slot
*
* Return null if no free slot is available
*/
protected function requestSlot($lock = false) {
MTLog::getInstance()->debug('Requesting slot ... ');
$slot = null;
if ( $lock ) $this->lock();
$slots = shm_get_var($this->shared_data, self::_INDEX_SLOTS);
for ( $i = 0; $i<$this->max_threads; $i++ ) {
if ( !isset($slots[$i]) ) {
$slots[$i] = true;
$slot = $i;
break;
} else {
if ( $slots[$i]==false ) {
$slots[$i] = true;
$slot = $i;
break;
}
}
}
shm_put_var($this->shared_data, self::_INDEX_SLOTS, $slots);
if ( $lock ) $this->unlock();
if ( is_null($slot) ) {
MTLog::getInstance()->debug('no free slots !!');
} else {
MTLog::getInstance()->debug('slot '.$slot.' found.');
}
return $slot;
}
/*
* Release given slot
*/
protected function releaseSlot($slot, $lock = false) {
if ( $lock ) $this->lock();
$slots = shm_get_var($this->shared_data, self::_INDEX_SLOTS);
$slots[$slot] = false;
shm_put_var($this->shared_data, self::_INDEX_SLOTS, $slots);
if ( $lock ) $this->unlock();
MTLog::getInstance()->debug('Releasing slot '.$slot);
return true;
}
}