forked from kvz/system_daemon
/
Daemon.php
1597 lines (1428 loc) · 48.3 KB
/
Daemon.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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* vim: set noai expandtab tabstop=4 softtabstop=4 shiftwidth=4: */
/**
* System_Daemon turns PHP-CLI scripts into daemons.
*
* PHP version 5
*
* @category System
* @package System_Daemon
* @author Kevin van Zonneveld <kevin@vanzonneveld.net>
* @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* @license http://www.opensource.org/licenses/bsd-license.php New BSD Licence
* @version SVN: Release: $Id$
* @link http://trac.plutonia.nl/projects/system_daemon
*/
// Autoloader borrowed from PHP_CodeSniffer, see function for credits
spl_autoload_register(array('System_Daemon', 'autoload'));
/**
* System_Daemon. Create daemons with practicle functions
* like System_Daemon::start()
*
* Requires PHP build with --enable-cli --with-pcntl.
* Only runs on *NIX systems, because Windows lacks of the pcntl ext.
*
* PHP version 5
*
* @category System
* @package System_Daemon
* @author Kevin van Zonneveld <kevin@vanzonneveld.net>
* @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* @license http://www.opensource.org/licenses/bsd-license.php New BSD Licence
* @version SVN: Release: $Id$
* @link http://trac.plutonia.nl/projects/system_daemon
*
*/
class System_Daemon
{
// Make these corresponding with PEAR
// Ensures compatibility while maintaining independency
/**
* System is unusable (will throw a System_Daemon_Exception as well)
*/
const LOG_EMERG = 0;
/**
* Immediate action required (will throw a System_Daemon_Exception as well)
*/
const LOG_ALERT = 1;
/**
* Critical conditions (will throw a System_Daemon_Exception as well)
*/
const LOG_CRIT = 2;
/**
* Error conditions
*/
const LOG_ERR = 3;
/**
* Warning conditions
*/
const LOG_WARNING = 4;
/**
* Normal but significant
*/
const LOG_NOTICE = 5;
/**
* Informational
*/
const LOG_INFO = 6;
/**
* Debug-level messages
*/
const LOG_DEBUG = 7;
/**
* The current process identifier
*
* @var integer
*/
static protected $_processId = 0;
/**
* Whether the our daemon is being killed
*
* @var boolean
*/
static protected $_isDying = false;
/**
* Whether the current process is a forked child
*
* @var boolean
*/
static protected $_processIsChild = false;
/**
* Whether SAFE_MODE is on or off. This is important for ini_set
* behavior
*
* @var boolean
*/
static protected $_safeMode = false;
/**
* Available log levels
*
* @var array
*/
static protected $_logLevels = array(
self::LOG_EMERG => 'emerg',
self::LOG_ALERT => 'alert',
self::LOG_CRIT => 'crit',
self::LOG_ERR => 'err',
self::LOG_WARNING => 'warning',
self::LOG_NOTICE => 'notice',
self::LOG_INFO => 'info',
self::LOG_DEBUG => 'debug',
);
/**
* Available PHP error levels and their meaning in POSIX loglevel terms
* Some ERROR constants are not supported in all PHP versions
* and will conditionally be translated from strings to constants,
* or else: removed from this mapping at start().
*
* @var array
*/
static protected $_logPhpMapping = array(
E_ERROR => self::LOG_ERR,
E_WARNING => self::LOG_WARNING,
E_PARSE => self::LOG_EMERG,
E_NOTICE => self::LOG_DEBUG,
E_CORE_ERROR => self::LOG_EMERG,
E_CORE_WARNING => self::LOG_WARNING,
E_COMPILE_ERROR => self::LOG_EMERG,
E_COMPILE_WARNING => self::LOG_WARNING,
E_USER_ERROR => self::LOG_ERR,
E_USER_WARNING => self::LOG_WARNING,
E_USER_NOTICE => self::LOG_DEBUG,
'E_RECOVERABLE_ERROR' => self::LOG_WARNING,
'E_DEPRECATED' => self::LOG_NOTICE,
'E_USER_DEPRECATED' => self::LOG_NOTICE,
);
/**
* Holds Option Object
*
* @var mixed object or boolean
*/
static protected $_optObj = false;
/**
* Holds OS Object
*
* @var mixed object or boolean
*/
static protected $_osObj = false;
/**
* Definitions for all Options
*
* @var array
* @see setOption()
* @see getOption()
*/
static protected $_optionDefinitions = array(
'usePEAR' => array(
'type' => 'boolean',
'default' => true,
'punch' => 'Whether to run this class using PEAR',
'detail' => 'Will run standalone when false',
'required' => true,
),
'usePEARLogInstance' => array(
'type' => 'boolean|object',
'default' => false,
'punch' => 'Accepts a PEAR_Log instance to handle all logging',
'detail' => 'This will replace System_Daemon\'s own logging facility',
'required' => true,
),
'authorName' => array(
'type' => 'string/0-50',
'punch' => 'Author name',
'example' => 'Kevin van zonneveld',
'detail' => 'Required for forging init.d script',
),
'authorEmail' => array(
'type' => 'string/email',
'punch' => 'Author e-mail',
'example' => 'kevin@vanzonneveld.net',
'detail' => 'Required for forging init.d script',
),
'appName' => array(
'type' => 'string/unix',
'punch' => 'The application name',
'example' => 'logparser',
'detail' => 'Must be UNIX-proof; Required for running daemon',
'required' => true,
),
'appDescription' => array(
'type' => 'string',
'punch' => 'Daemon description',
'example' => 'Parses logfiles of vsftpd and stores them in MySQL',
'detail' => 'Required for forging init.d script',
),
'appDir' => array(
'type' => 'string/existing_dirpath',
'default' => '@dirname({SERVER.SCRIPT_NAME})',
'punch' => 'The home directory of the daemon',
'example' => '/usr/local/logparser',
'detail' => 'Highly recommended to set this yourself',
'required' => true,
),
'appExecutable' => array(
'type' => 'string/existing_filepath',
'default' => '@basename({SERVER.SCRIPT_NAME})',
'punch' => 'The executable daemon file',
'example' => 'logparser.php',
'detail' => 'Recommended to set this yourself; Required for init.d',
'required' => true
),
'logVerbosity' => array(
'type' => 'number/0-7',
'default' => self::LOG_INFO,
'punch' => 'Messages below this log level are ignored',
'example' => '',
'detail' => 'Not written to logfile; not displayed on screen',
'required' => true,
),
'logLocation' => array(
'type' => 'string/creatable_filepath',
'default' => '/var/log/{OPTIONS.appName}.log',
'punch' => 'The log filepath',
'example' => '/var/log/logparser_daemon.log',
'detail' => 'Not applicable if you use PEAR Log',
'required' => false,
),
'logPhpErrors' => array(
'type' => 'boolean',
'default' => true,
'punch' => 'Reroute PHP errors to log function',
'detail' => '',
'required' => true,
),
'logFilePosition' => array(
'type' => 'boolean',
'default' => false,
'punch' => 'Show file in which the log message was generated',
'detail' => '',
'required' => true,
),
'logTrimAppDir' => array(
'type' => 'boolean',
'default' => true,
'punch' => 'Strip the application dir from file positions in log msgs',
'detail' => '',
'required' => true,
),
'logLinePosition' => array(
'type' => 'boolean',
'default' => true,
'punch' => 'Show the line number in which the log message was generated',
'detail' => '',
'required' => true,
),
'appRunAsUID' => array(
'type' => 'number/0-65000',
'default' => 0,
'punch' => 'The user id under which to run the process',
'example' => '1000',
'detail' => 'Defaults to root which is insecure!',
'required' => true,
),
'appRunAsGID' => array(
'type' => 'number/0-65000',
'default' => 0,
'punch' => 'The group id under which to run the process',
'example' => '1000',
'detail' => 'Defaults to root which is insecure!',
'required' => true,
),
'appPidLocation' => array(
'type' => 'string/unix_filepath',
'default' => '/var/run/{OPTIONS.appName}/{OPTIONS.appName}.pid',
'punch' => 'The pid filepath',
'example' => '/var/run/logparser/logparser.pid',
'detail' => '',
'required' => true,
),
'appChkConfig' => array(
'type' => 'string',
'default' => '- 99 0',
'punch' => 'chkconfig parameters for init.d',
'detail' => 'runlevel startpriority stoppriority',
),
'appDieOnIdentityCrisis' => array(
'type' => 'boolean',
'default' => true,
'punch' => 'Kill daemon if it cannot assume the identity',
'detail' => '',
'required' => true,
),
'sysMaxExecutionTime' => array(
'type' => 'number',
'default' => 0,
'punch' => 'Maximum execution time of each script in seconds',
'detail' => '0 is infinite',
),
'sysMaxInputTime' => array(
'type' => 'number',
'default' => 0,
'punch' => 'Maximum time to spend parsing request data',
'detail' => '0 is infinite',
),
'sysMemoryLimit' => array(
'type' => 'string',
'default' => '128M',
'punch' => 'Maximum amount of memory a script may consume',
'detail' => '0 is infinite',
),
'runTemplateLocation' => array(
'type' => 'string/existing_filepath',
'default' => false,
'punch' => 'The filepath to a custom autorun Template',
'example' => '/etc/init.d/skeleton',
'detail' => 'Sometimes it\'s better to stick with the OS default,
and use something like /etc/default/<name> for customization',
),
);
/**
* Available signal handlers
* setSigHandler can overwrite these values individually.
*
* Available POSIX SIGNALS and their PHP handler functions.
* Some SIGNALS constants are not supported in all PHP versions
* and will conditionally be translated from strings to constants,
* or else: removed from this mapping at start().
*
* 'kill -l' gives you a list of signals available on your UNIX.
* Eg. Ubuntu:
*
* 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
* 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
* 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
* 13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD
* 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN
* 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
* 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO
* 30) SIGPWR 31) SIGSYS 33) SIGRTMIN 34) SIGRTMIN+1
* 35) SIGRTMIN+2 36) SIGRTMIN+3 37) SIGRTMIN+4 38) SIGRTMIN+5
* 39) SIGRTMIN+6 40) SIGRTMIN+7 41) SIGRTMIN+8 42) SIGRTMIN+9
* 43) SIGRTMIN+10 44) SIGRTMIN+11 45) SIGRTMIN+12 46) SIGRTMIN+13
* 47) SIGRTMIN+14 48) SIGRTMIN+15 49) SIGRTMAX-15 50) SIGRTMAX-14
* 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
* 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
* 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
* 63) SIGRTMAX-1 64) SIGRTMAX
*
* SIG_IGN, SIG_DFL, SIG_ERR are no real signals
*
* @var array
* @see setSigHandler()
*/
static protected $_sigHandlers = array(
SIGHUP => array('System_Daemon', 'defaultSigHandler'),
SIGINT => array('System_Daemon', 'defaultSigHandler'),
SIGQUIT => array('System_Daemon', 'defaultSigHandler'),
SIGILL => array('System_Daemon', 'defaultSigHandler'),
SIGTRAP => array('System_Daemon', 'defaultSigHandler'),
SIGABRT => array('System_Daemon', 'defaultSigHandler'),
'SIGIOT' => array('System_Daemon', 'defaultSigHandler'),
SIGBUS => array('System_Daemon', 'defaultSigHandler'),
SIGFPE => array('System_Daemon', 'defaultSigHandler'),
SIGUSR1 => array('System_Daemon', 'defaultSigHandler'),
SIGSEGV => array('System_Daemon', 'defaultSigHandler'),
SIGUSR2 => array('System_Daemon', 'defaultSigHandler'),
SIGPIPE => SIG_IGN,
SIGALRM => array('System_Daemon', 'defaultSigHandler'),
SIGTERM => array('System_Daemon', 'defaultSigHandler'),
'SIGSTKFLT' => array('System_Daemon', 'defaultSigHandler'),
'SIGCLD' => array('System_Daemon', 'defaultSigHandler'),
'SIGCHLD' => array('System_Daemon', 'defaultSigHandler'),
SIGCONT => array('System_Daemon', 'defaultSigHandler'),
SIGTSTP => array('System_Daemon', 'defaultSigHandler'),
SIGTTIN => array('System_Daemon', 'defaultSigHandler'),
SIGTTOU => array('System_Daemon', 'defaultSigHandler'),
SIGURG => array('System_Daemon', 'defaultSigHandler'),
SIGXCPU => array('System_Daemon', 'defaultSigHandler'),
SIGXFSZ => array('System_Daemon', 'defaultSigHandler'),
SIGVTALRM => array('System_Daemon', 'defaultSigHandler'),
SIGPROF => array('System_Daemon', 'defaultSigHandler'),
SIGWINCH => array('System_Daemon', 'defaultSigHandler'),
'SIGPOLL' => array('System_Daemon', 'defaultSigHandler'),
SIGIO => array('System_Daemon', 'defaultSigHandler'),
'SIGPWR' => array('System_Daemon', 'defaultSigHandler'),
'SIGSYS' => array('System_Daemon', 'defaultSigHandler'),
SIGBABY => array('System_Daemon', 'defaultSigHandler'),
'SIG_BLOCK' => array('System_Daemon', 'defaultSigHandler'),
'SIG_UNBLOCK' => array('System_Daemon', 'defaultSigHandler'),
'SIG_SETMASK' => array('System_Daemon', 'defaultSigHandler'),
);
/**
* Making the class non-abstract with a protected constructor does a better
* job of preventing instantiation than just marking the class as abstract.
*
* @see start()
*/
protected function __construct()
{
}
/**
* Autoload static method for loading classes and interfaces.
* Code from the PHP_CodeSniffer package by Greg Sherwood and
* Marc McIntyre
*
* @param string $className The name of the class or interface.
*
* @return void
*/
static public function autoload($className)
{
$parent = 'System_';
$parent_len = strlen($parent);
if (substr($className, 0, $parent_len) == $parent) {
$newClassName = substr($className, $parent_len);
} else {
$newClassName = $className;
}
$path = str_replace('_', '/', $newClassName).'.php';
if (is_file(dirname(__FILE__).'/'.$path) === true) {
// Check standard file locations based on class name.
include(dirname(__FILE__).'/'.$path);
} else {
// Everything else.
@include($path);
}
}
/**
* Spawn daemon process.
*
* @return boolean
* @see iterate()
* @see stop()
* @see autoload()
* @see _optionsInit()
* @see _summon()
*/
static public function start()
{
// Conditionally add loglevel mappings that are not supported in
// all PHP versions.
// They will be in string representation and have to be
// converted & unset
foreach (self::$_logPhpMapping as $phpConstant => $sdLevel) {
if (!is_numeric($phpConstant)) {
if (defined($phpConstant)) {
self::$_logPhpMapping[constant($phpConstant)] = $sdLevel;
}
unset(self::$_logPhpMapping[$phpConstant]);
}
}
// Same goes for POSIX signals. Not all Constants are available on
// all platforms.
foreach (self::$_sigHandlers as $signal => $handler) {
if (!$signal) {
unset(self::$_sigHandlers[$signal]);
} else if (is_string($signal)) {
if (defined($signal)) {
self::$_sigHandlers[constant($signal)] = $handler;
}
unset(self::$_sigHandlers[$signal]);
}
}
// Quickly initialize some defaults like usePEAR
// by adding the $premature flag
self::_optionsInit(true);
if (self::opt('logPhpErrors')) {
set_error_handler(array('System_Daemon', 'phpErrors'), E_ALL);
}
// To run as a part of PEAR
if (self::opt('usePEAR')) {
// SPL's autoload will make sure classes are automatically loaded
if (false === class_exists('PEAR', true)) {
$msg = 'PEAR not found. Install PEAR or run with option: '.
'usePEAR = false';
trigger_error($msg, E_USER_ERROR);
}
if (false === class_exists('PEAR_Exception', true)) {
$msg = 'PEAR_Exception not found?!';
trigger_error($msg, E_USER_ERROR);
}
if (false === class_exists('System_Daemon_Exception', true)) {
// PEAR_Exception is OK. PEAR was found already.
throw new PEAR_Exception('Class System_Daemon_Exception not found');
}
}
// Check the PHP configuration
if (!defined('SIGHUP')) {
$msg = 'PHP is compiled without --enable-pcntl directive';
if (self::opt('usePEAR')) {
throw new System_Daemon_Exception($msg);
} else {
trigger_error($msg, E_USER_ERROR);
}
}
// Check for CLI
if ((php_sapi_name() !== 'cli')) {
$msg = 'You can only create daemon from the command line (CLI-mode)';
if (self::opt('usePEAR')) {
throw new System_Daemon_Exception($msg);
} else {
trigger_error($msg, E_USER_ERROR);
}
}
// Check for POSIX
if (!function_exists('posix_getpid')) {
$msg = 'PHP is compiled without --enable-posix directive';
if (self::opt('usePEAR')) {
throw new System_Daemon_Exception($msg);
} else {
trigger_error($msg, E_USER_ERROR);
}
}
// Initialize & check variables
if (false === self::_optionsInit(false)) {
if (is_object(self::$_optObj) && is_array(self::$_optObj->errors)) {
foreach (self::$_optObj->errors as $error) {
self::notice($error);
}
}
$msg = 'Crucial options are not set. Review log:';
if (self::opt('usePEAR')) {
throw new System_Daemon_Exception($msg);
} else {
trigger_error($msg, E_USER_ERROR);
}
}
// Become daemon
self::_summon();
return true;
}
/**
* Protects your daemon by e.g. clearing statcache. Can optionally
* be used as a replacement for sleep as well.
*
* @param integer $sleepSeconds Optionally put your daemon to rest for X s.
*
* @return void
* @see start()
* @see stop()
*/
static public function iterate($sleepSeconds = 0)
{
self::_optionObjSetup();
if ($sleepSeconds !== 0) {
sleep($sleepSeconds);
}
clearstatcache();
return true;
}
/**
* Stop daemon process.
*
* @return void
* @see start()
*/
static public function stop()
{
self::info('Stopping {appName}');
self::_die(false);
}
/**
* Restart daemon process.
*
* @return void
* @see _die()
*/
static public function restart()
{
self::info('Restarting {appName}');
self::_die(true);
}
/**
* Overrule or add signal handlers.
*
* @param string $signal Signal constant (e.g. SIGHUP)
* @param mixed $handler Which handler to call on signal
*
* @return boolean
* @see $_sigHandlers
*/
static public function setSigHandler($signal, $handler)
{
if (!isset(self::$_sigHandlers[$signal])) {
// The signal should be defined already
self::notice(
'Can only overrule on of these signal handlers: %s',
join(', ', array_keys(self::$_sigHandlers))
);
return false;
}
// Overwrite on existance
self::$_sigHandlers[$signal] = $handler;
return true;
}
/**
* Sets any option found in $_optionDefinitions
* Public interface to talk with with protected option methods
*
* @param string $name Name of the Option
* @param mixed $value Value of the Option
*
* @return boolean
*/
static public function setOption($name, $value)
{
if (!self::_optionObjSetup()) {
return false;
}
return self::$_optObj->setOption($name, $value);
}
/**
* Sets an array of options found in $_optionDefinitions
* Public interface to talk with with protected option methods
*
* @param array $use_options Array with Options
*
* @return boolean
*/
static public function setOptions($use_options)
{
if (!self::_optionObjSetup()) {
return false;
}
return self::$_optObj->setOptions($use_options);
}
/**
* Shortcut for getOption & setOption
*
* @param string $name Option to set or get
*
* @return mixed
*/
static public function opt($name)
{
$args = func_get_args();
if (count($args) > 1) {
return self::setOption($name, $args[1]);
} else {
return self::getOption($name);
}
}
/**
* Gets any option found in $_optionDefinitions
* Public interface to talk with with protected option methods
*
* @param string $name Name of the Option
*
* @return mixed
*/
static public function getOption($name)
{
if (!self::_optionObjSetup()) {
return false;
}
return self::$_optObj->getOption($name);
}
/**
* Gets an array of options found
*
* @return array
*/
static public function getOptions()
{
if (!self::_optionObjSetup()) {
return false;
}
return self::$_optObj->getOptions();
}
/**
* Catches PHP Errors and forwards them to log function
*
* @param integer $errno Level
* @param string $errstr Error
* @param string $errfile File
* @param integer $errline Line
*
* @return boolean
*/
static public function phpErrors($errno, $errstr, $errfile, $errline)
{
// Ignore suppressed errors
if (error_reporting() == 0) {
return;
}
// Map PHP error level to System_Daemon log level
if (empty(self::$_logPhpMapping[$errno])) {
self::warning('Unknown PHP errorno: %s', $errno);
$lvl = self::LOG_ERR;
} else {
$lvl = self::$_logPhpMapping[$errno];
}
// Log it
// No shortcuts this time!
self::log(
$lvl, '[PHP Error] '.$errstr, $errfile, __CLASS__,
__FUNCTION__, $errline
);
return true;
}
/**
* Abbreviate a string. e.g: Kevin van zonneveld -> Kevin van Z...
*
* @param string $str Data
* @param integer $cutAt Where to cut
* @param string $suffix Suffix with something?
*
* @return string
*/
public function abbr($str, $cutAt = 30, $suffix = '...')
{
if (strlen($str) <= 30) {
return $str;
}
$canBe = $cutAt - strlen($suffix);
return substr($str, 0, $canBe). $suffix;
}
/**
* Tries to return the most significant information as a string
* based on any given argument.
*
* @param mixed $arguments Any type of variable
*
* @return string
*/
public function semantify($arguments)
{
if (is_object($arguments)) {
return get_class($arguments);
}
if (!is_array($arguments)) {
if (!is_numeric($arguments) && !is_bool($arguments)) {
$arguments = '\''.$arguments.'\'';
}
return $arguments;
}
$arr = array();
foreach ($arguments as $key=>$val) {
if (is_array($val)) {
$val = json_encode($val);
} elseif (!is_numeric($val) && !is_bool($val)) {
$val = '\''.$val.'\'';
}
$val = self::abbr($val);
$arr[] = $key.': '.$val;
}
return join(', ', $arr);
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function emerg()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return false;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function crit()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return false;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function err()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return false;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function warning()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return false;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function notice()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return true;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function info()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return true;
}
/**
* Logging shortcut
*
* @return boolean
*/
public static function debug()
{
$arguments = func_get_args(); array_unshift($arguments, __FUNCTION__);
call_user_func_array(array('System_Daemon', '_ilog'), $arguments);
return true;
}
/**
* Internal logging function. Bridge between shortcuts like:
* err(), warning(), info() and the actual log() function
*
* @param mixed $level As string or constant
* @param mixed $str Message
*
* @return boolean
*/
protected static function _ilog($level, $str)
{
$arguments = func_get_args();
$level = $arguments[0];
$format = $arguments[1];
if (is_string($level)) {
if (false === ($l = array_search($level, self::$_logLevels))) {
self::log(LOG_EMERG, 'No such loglevel: '. $level);
} else {
$level = $l;
}
}
unset($arguments[0]);
unset($arguments[1]);
$str = $format;
if (count($arguments)) {
foreach ($arguments as $k => $v) {
$arguments[$k] = self::semantify($v);
}
$str = vsprintf($str, $arguments);
}
self::_optionObjSetup();
$str = preg_replace_callback(
'/\{([^\{\}]+)\}/is',
array(self::$_optObj, 'replaceVars'),
$str
);
$history = 2;
$dbg_bt = @debug_backtrace();
$class = (string)@$dbg_bt[($history-1)]['class'];
$function = (string)@$dbg_bt[($history-1)]['function'];
$file = (string)@$dbg_bt[$history]['file'];
$line = (string)@$dbg_bt[$history]['line'];
return self::log($level, $str, $file, $class, $function, $line);
}
/**
* Almost every deamon requires a log file, this function can
* facilitate that. Also handles class-generated errors, chooses
* either PEAR handling or PEAR-independant handling, depending on:
* self::opt('usePEAR').
* Also supports PEAR_Log if you referenc to a valid instance of it
* in self::opt('usePEARLogInstance').
*
* It logs a string according to error levels specified in array:
* self::$_logLevels (0 is fatal and handles daemon's death)
*
* @param integer $level What function the log record is from
* @param string $str The log record
* @param string $file What code file the log record is from
* @param string $class What class the log record is from
* @param string $function What function the log record is from
* @param integer $line What code line the log record is from
*
* @throws System_Daemon_Exception
* @return boolean
* @see _logLevels
* @see logLocation
*/
static public function log($level, $str, $file = false, $class = false,
$function = false, $line = false) {
// If verbosity level is not matched, don't do anything
if (null === self::opt('logVerbosity')
|| false === self::opt('logVerbosity')
) {
// Somebody is calling log before launching daemon..
// fair enough, but we have to init some log options
self::_optionsInit(true);
}
if (!self::opt('appName')) {
// Not logging for anything without a name
return false;
}
if ($level > self::opt('logVerbosity')) {