2 require_once 'Pman.php';
5 * notification script runner
7 * This does not actualy send stuf out, it only starts the NotifySend/{id}
8 * which does the actuall notifcations.
10 * It manages a pool of notifiers.
16 class Pman_Core_Notify extends Pman
19 static $cli_desc = "Runs the notification queue (usually from cron)
20 Normally used to sends out emails to anyone in the notification list.
22 /etc/cron.d/pman-core-notify
23 * * * * * www-data /usr/bin/php /home/gitlive/web.mtrack/admin.php Core/Notify > /dev/null
27 static $cli_opts = array(
29 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
37 'desc' => 'List message to send, do not send them..',
45 'desc' => 'Show old messages.. (and new messages...)',
53 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
59 /* removed - use GenerateNotifcations.php hooked classes
60 'generate' => 'Generate notifications for a table, eg. cash_invoice',
65 'desc' => 'Limit search for no. to send to ',
72 'desc' => 'Dry run - do not send.',
79 'desc' => 'Pool size',
87 * @var $nice_level Unix 'nice' level to stop it jamming server up.
89 var $nice_level = false;
91 * @var $max_pool_size maximum runners to start at once.
93 var $max_pool_size = 10;
95 * @var $max_to_domain maximum connections to make to a single domain
97 var $max_to_domain = 10;
100 * @var $maxruntime - maximum seconds a child is allowed to run - defaut 2 minutes
102 var $maxruntime = 120;
105 * @var {Boolean} log_events - default true if events should be logged.
107 var $log_events = true;
109 * @var {Number} try_again_minutes how long after failing to try again default = 30 if max runtime fails
111 var $try_again_minutes = 30;
114 * @var {String} table - the table that the class will query for notification events
116 var $table = 'core_notify';
118 * @var {String} target - the application that will run for each Row in the table (eg. Pman/Core/NotifySend)
120 var $target = 'Core/NotifySend';
124 var $evtype = ''; // any notification...
125 // this script should only handle EMAIL notifications..
131 $ff = HTML_FlexyFramework::get();
133 die("access denied");
135 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
141 function parseArgs(&$opts)
143 if ($opts['debug']) {
144 DB_DataObject::debugLevel($opts['debug']);
148 if (!empty($opts['poolsize'])) {
149 $this->max_pool_size = $opts['poolsize'];
152 if (empty($opts['limit'])) {
153 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
156 if (!empty($opts['old'])) {
157 $opts['list'] = 1; // force listing..
160 $this->force = empty($opts['force']) ? 0 : 1;
162 if (!empty($opts['send-to'])) {
163 $this->send_to = $opts['send-to'];
168 function get($r,$opts=array())
170 $this->parseArgs($opts);
172 //date_default_timezone_set('UTC');
175 $this->generateNotifications();
178 //DB_DataObject::debugLevel(1);
179 $w = DB_DataObject::factory($this->table);
182 if (!empty($opts['old'])) {
183 // show old and new...
185 $w->orderBy('act_when DESC'); // latest first
186 $w->limit($opts['limit']); // we can run
187 $total = min($w->count(), $opts['limit']);
191 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
192 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
194 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
196 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
199 $w->orderBy('act_when ASC'); // oldest first.
200 $total = min($w->count(), $opts['limit']);
201 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
203 $w->limit($opts['limit']); // we can run 1000 ...
206 if (!empty($this->evtype)) {
207 $w->evtype = $this->evtype;
213 $ar = array(); // $w->fetchAll();
215 if (!empty($opts['list'])) {
218 while ($w->fetch()) {
222 $this->logecho("{$w->id} : {$w->person()->email} email : ".
223 $o->toEventString()." ". $w->status() );
228 //echo "BATCH SIZE: ". count($ar) . "\n";
232 // only add if we don't have any queued up..
233 if (empty($ar) && $w->fetch()) {
238 $this->logecho("BATCH SIZE: ". (count($ar) + $total) );
241 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
243 if (empty($pushed)) {
252 $p = array_shift($ar);
253 if (!$this->poolfree()) {
254 array_unshift($ar,$p); /// put it back on..
258 $email = $p->person() ? $p->person()->email : $p->to_email;
260 if ($this->poolHasDomain($email) > $this->max_to_domain) {
262 if ($pushed === false) {
263 // we only try once to requeue..
275 $this->run($p->id,$email);
281 // we should have a time limit here...
282 while(count($this->pool)) {
287 foreach($requeue as $p) {
289 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
295 $this->logecho("DONE");
299 function generateNotifications()
301 // this should check each module for 'GenerateNotifications.php' class..
302 //and run it if found..
303 $ff = HTML_FlexyFramework::get();
305 $disabled = explode(',', $ff->disable);
307 $modules = array_reverse($this->modulesList());
309 // move 'project' one to the end...
311 foreach ($modules as $module){
312 if(in_array($module, $disabled)){
315 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
316 if(!file_exists($file)){
321 $class = "Pman_{$module}_GenerateNotifications";
323 if(!method_exists($x, 'generate')){
335 function run($id, $email='', $cmdOpts="")
338 static $renice = false;
340 require_once 'System.php';
341 $renice = System::which('renice');
347 $tn = $this->tempName('stdout', true);
348 $descriptorspec = array(
349 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
350 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
351 2 => array("pipe", "w") // stderr is a file to write to
356 require_once 'System.php';
357 $php = System::which('php');
360 $sn = $_SERVER["SCRIPT_NAME"];
362 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
363 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
367 if (!empty($this->send_to)) {
368 $app .= ' --sent-to='.escapeshellarg($this->send_to);
370 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
374 $this->logecho("call proc_open $cmd");
377 if ($this->max_pool_size === 1) {
383 if (!empty($this->opts['dryrun'])) {
384 $this->logecho("DRY RUN");
388 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
389 $info = proc_get_status($p);
391 if ($this->nice_level !== false) {
392 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
395 $this->pool[] = array(
397 'pid' => $info['pid'],
407 $this->logecho("RUN ({$info['pid']}) $cmd ");
415 foreach($this->pool as $p) {
417 //echo "CHECK PID: " . $p['pid'] . "\n";
418 $info = proc_get_status($p['proc']);
421 // update if necessday.
422 if ($info['pid'] && $p['pid'] != $info['pid']) {
423 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
424 $p['pid'] = $info['pid'];
427 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
429 if ($info['running']) {
431 //if (file_exists('/proc/'.$p['pid'])) {
432 $runtime = time() - $p['started'];
433 //echo "RUNTIME ({$p['pid']}): $runtime\n";
434 if ($runtime > $this->maxruntime) {
436 proc_terminate($p['proc'], 9);
437 //fclose($p['pipes'][1]);
438 fclose($p['pipes'][0]);
439 fclose($p['pipes'][2]);
440 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
444 $w = DB_DataObject::factory($this->table);
445 $w->get($p['notify_id']);
447 if ($this->log_events) {
448 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
450 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
459 fclose($p['pipes'][0]);
460 fclose($p['pipes'][2]);
461 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
462 //fclose($p['pipes'][1]);
464 proc_close($p['proc']);
468 //if (file_exists('/proc/'.$p['pid'])) {
472 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
476 $this->logecho("POOL SIZE: ". count($pool) );
478 if (count($pool) < $this->max_pool_size) {
485 * see if pool is already trying to deliver to this domain.?
486 * -- if so it get's pushed to the end of the queue.
489 function poolHasDomain($email)
492 $ea = explode('@',$email);
493 $dom = strtolower(array_pop($ea));
494 foreach($this->pool as $p) {
495 $ea = explode('@',$p['email']);
496 $mdom = strtolower(array_pop($ea));
507 $this->logecho("DONE");
510 function logecho($str)
512 echo date("Y-m-d H:i:s - ") . $str . "\n";