System_Daemon
[ class tree: System_Daemon ] [ index: System_Daemon ] [ all elements ]

Class: System_Daemon

Source Location: /System_Daemon-1.0.0/System/Daemon.php

Class Overview


System_Daemon. Create daemons with practicle functions like System_Daemon::start()


Author(s):

Version:

  • SVN: Release: $Id$

Copyright:

  • 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)

Variables

Methods


Inherited Variables

Inherited Methods


Class Details

[line 39]
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



[ Top ]


Class Variables

$_isDying =  false

[line 98]

Whether the our daemon is being killed
  • Access: protected

Type:   boolean


[ Top ]

$_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',
    )

[line 120]

Available log levels
  • Access: protected

Type:   array


[ Top ]

$_logPhpMapping = array(
        E_ERROR => array(self::LOG_ERR, 'Error'),E_WARNING=>array(self::LOG_WARNING,'Warning'),E_PARSE=>array(self::LOG_EMERG,'Parse'),E_NOTICE=>array(self::LOG_DEBUG,'Notice'),E_CORE_ERROR=>array(self::LOG_EMERG,'Core Error'),E_CORE_WARNING=>array(self::LOG_WARNING,'Core Warning'),E_COMPILE_ERROR=>array(self::LOG_EMERG,'Compile Error'),E_COMPILE_WARNING=>array(self::LOG_WARNING,'Compile Warning'),E_USER_ERROR=>array(self::LOG_ERR,'User Error'),E_USER_WARNING=>array(self::LOG_WARNING,'User Warning'),E_USER_NOTICE=>array(self::LOG_DEBUG,'User Notice'),'E_RECOVERABLE_ERROR'=>array(self::LOG_WARNING,'Recoverable Error'),'E_DEPRECATED'=>array(self::LOG_NOTICE,'Deprecated'),'E_USER_DEPRECATED'=>array(self::LOG_NOTICE,'User Deprecated'),)

[line 139]

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().
  • Access: protected

Type:   array


[ Top ]

$_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,),'useCustomLogHandler'=>array('type'=>'boolean|object','default'=>false,'punch'=>'Accepts any callable method 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',),)

[line 177]

Definitions for all Options

Type:   array


[ Top ]

$_optObj =  false

[line 161]

Holds Option Object
  • Var: object or boolean
  • Access: protected

Type:   mixed


[ Top ]

$_osObj =  false

[line 168]

Holds OS Object
  • Var: object or boolean
  • Access: protected

Type:   mixed


[ Top ]

$_processId =  0

[line 91]

The current process identifier
  • Access: protected

Type:   integer


[ Top ]

$_processIsChild =  false

[line 105]

Whether the current process is a forked child
  • Access: protected

Type:   boolean


[ Top ]

$_safeMode =  false

[line 113]

Whether SAFE_MODE is on or off. This is important for ini_set behavior
  • Access: protected

Type:   boolean


[ Top ]

$_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'),)

[line 388]

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


Type:   array


[ Top ]



Method Detail

abbr   [line 820]

string abbr( string $str, [integer $cutAt = 30], [string $suffix = '...'])

Abbreviate a string. e.g: Kevin van zonneveld -> Kevin van Z...
  • Access: public

Parameters:

string   $str   —  Data
integer   $cutAt   —  Where to cut
string   $suffix   —  Suffix with something?

[ Top ]

alert   [line 882]

boolean alert( )

Logging shortcut
  • Access: public

[ Top ]

autoload   [line 450]

void autoload( string $className)

Autoload static method for loading classes and interfaces.

Code from the PHP_CodeSniffer package by Greg Sherwood and Marc McIntyre

  • Access: public

Parameters:

string   $className   —  The name of the class or interface.

[ Top ]

crit   [line 894]

boolean crit( )

Logging shortcut
  • Access: public

[ Top ]

debug   [line 954]

boolean debug( )

Logging shortcut
  • Access: public

[ Top ]

defaultSigHandler   [line 1209]

void defaultSigHandler( integer $signo)

Default signal handler.

You can overrule various signals with the setSigHandler() method


Parameters:

integer   $signo   —  The posix signal received.

[ Top ]

emerg   [line 870]

boolean emerg( )

Logging shortcut
  • Access: public

[ Top ]

err   [line 906]

boolean err( )

Logging shortcut
  • Access: public

[ Top ]

fileread   [line 1454]

string fileread( string $filepath)

Read a file. file_get_contents() leaks memory! (#18031 for more info)
  • Access: public

Parameters:

string   $filepath   — 

[ Top ]

getOption   [line 753]

mixed getOption( string $name)

Gets any option found in $_optionDefinitions Public interface to talk with with protected option methods
  • Access: public

Parameters:

string   $name   —  Name of the Option

[ Top ]

getOptions   [line 767]

array getOptions( )

Gets an array of options found
  • Access: public

[ Top ]

info   [line 942]

boolean info( )

Logging shortcut
  • Access: public

[ Top ]

isDying   [line 1257]

boolean isDying( )

Whether the our daemon is being killed, you might want to include this in your loop
  • Access: public

[ Top ]

isInBackground   [line 1246]

boolean isInBackground( )

Whether the class is already running in the background
  • Access: public

[ Top ]

isRunning   [line 1267]

boolean isRunning( )

Check if a previous process with same pidfile was already running
  • Access: public

[ Top ]

iterate   [line 624]

void iterate( [integer $sleepSeconds = 0])

Protects your daemon by e.g. clearing statcache. Can optionally be used as a replacement for sleep as well.

Parameters:

integer   $sleepSeconds   —  Optionally put your daemon to rest for X s.

[ Top ]

log   [line 1035]

boolean log( integer $level, string $str, [string $file = false], [string $class = false], [string $function = false], [integer $line = false])

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)


Parameters:

integer   $level   —  What function the log record is from
string   $str   —  The log record
string   $file   —  What code file the log record is from
string   $class   —  What class the log record is from
string   $function   —  What function the log record is from
integer   $line   —  What code line the log record is from

[ Top ]

__construct (Constructor)   [line 434]

System_Daemon __construct( )

Making the class non-abstract with a protected constructor does a better job of preventing instantiation than just marking the class as abstract.

[ Top ]

notice   [line 930]

boolean notice( )

Logging shortcut
  • Access: public

[ Top ]

opt   [line 734]

mixed opt( string $name)

Shortcut for getOption & setOption
  • Access: public

Parameters:

string   $name   —  Option to set or get

[ Top ]

phpErrors   [line 786]

boolean phpErrors( integer $errno, string $errstr, string $errfile, integer $errline)

Catches PHP Errors and forwards them to log function
  • Access: public

Parameters:

integer   $errno   —  Level
string   $errstr   —  Error
string   $errfile   —  File
integer   $errline   —  Line

[ Top ]

restart   [line 661]

void restart( )

Restart daemon process.

[ Top ]

semantify   [line 839]

string semantify( mixed $arguments)

Tries to return the most significant information as a string based on any given argument.
  • Access: public

Parameters:

mixed   $arguments   —  Any type of variable

[ Top ]

setOption   [line 701]

boolean setOption( string $name, mixed $value)

Sets any option found in $_optionDefinitions Public interface to talk with with protected option methods
  • Access: public

Parameters:

string   $name   —  Name of the Option
mixed   $value   —  Value of the Option

[ Top ]

setOptions   [line 718]

boolean setOptions( array $use_options)

Sets an array of options found in $_optionDefinitions Public interface to talk with with protected option methods
  • Access: public

Parameters:

array   $use_options   —  Array with Options

[ Top ]

setSigHandler   [line 676]

boolean setSigHandler( string $signal, mixed $handler)

Overrule or add signal handlers.

Parameters:

string   $signal   —  Signal constant (e.g. SIGHUP)
mixed   $handler   —  Which handler to call on signal

[ Top ]

start   [line 494]

boolean start( )

Spawn daemon process.

[ Top ]

stop   [line 649]

void stop( )

Stop daemon process.

[ Top ]

warning   [line 918]

boolean warning( )

Logging shortcut
  • Access: public

[ Top ]

writeAutoRun   [line 1162]

boolean writeAutoRun( [boolean $overwrite = false])

Uses OS class to write an: 'init.d' script on the filesystem
  • Access: public

Parameters:

boolean   $overwrite   —  May the existing init.d file be overwritten?

[ Top ]

_changeIdentity   [line 1486]

boolean _changeIdentity( [integer $gid = 0], [integer $uid = 0])

Change identity of process & resources if needed.
  • Access: protected

Parameters:

integer   $gid   —  Group identifier (number)
integer   $uid   —  User identifier (number)

[ Top ]

_die   [line 1599]

void _die( [boolean $restart = false])

Sytem_Daemon::_die() Kill the daemon Keep this function as independent from complex logic as possible
  • Access: protected

Parameters:

boolean   $restart   —  Whether to restart after die

[ Top ]

_fork   [line 1559]

boolean _fork( )

Fork process and kill parent process, the heart of the 'daemonization'
  • Access: protected

[ Top ]

_ilog   [line 970]

boolean _ilog( mixed $level, mixed $str)

Internal logging function. Bridge between shortcuts like: err(), warning(), info() and the actual log() function
  • Access: protected

Parameters:

mixed   $level   —  As string or constant
mixed   $str   —  Message

[ Top ]

_isValidPidLocation   [line 1391]

boolean _isValidPidLocation( string $pidFilePath, [boolean $log = true])

Determine whether pidfilelocation is valid
  • Access: protected

Parameters:

string   $pidFilePath   —  Pid location
boolean   $log   —  Allow this function to log directly on error

[ Top ]

_mkdirr   [line 1472]

boolean _mkdirr( string $dirPath, integer $mode)

Recursive alternative to mkdir
  • Access: protected

Parameters:

string   $dirPath   —  Directory to create
integer   $mode   —  Umask

[ Top ]

_optionObjSetup   [line 1657]

boolean _optionObjSetup( )

Sets up Option Object instance
  • Access: protected

[ Top ]

_optionsInit   [line 1680]

mixed _optionsInit( [boolean $premature = false])

Checks if all the required options are set.

Initializes, sanitizes & defaults unset variables

  • Return: integer or boolean
  • Access: protected

Parameters:

boolean   $premature   —  Whether to do a premature option init

[ Top ]

_osObjSetup   [line 1637]

boolean _osObjSetup( )

Sets up OS instance
  • Access: protected

[ Top ]

_summon   [line 1301]

void _summon( )

Put the running script in background
  • Access: protected

[ Top ]

_whatIAm   [line 1585]

string _whatIAm( )

Return what the current process is: child or parent
  • Access: protected

[ Top ]

_writePid   [line 1420]

boolean _writePid( [string $pidFilePath = null], [integer $pid = null])

Creates pid dir and writes process id to pid file
  • Access: protected

Parameters:

string   $pidFilePath   —  PID File path
integer   $pid   —  PID

[ Top ]


Documentation generated on Mon, 11 Mar 2019 15:47:42 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.