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..
127 var $server; // core_notify_server
129 var $poolname = 'core';
134 var $clear_interval = '1 WEEK'; // how long to clear the old queue of items.
138 $ff = HTML_FlexyFramework::get();
140 die("access denied");
142 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
148 function parseArgs(&$opts)
150 if ($opts['debug']) {
151 DB_DataObject::debugLevel($opts['debug']);
155 if (!empty($opts['poolsize'])) {
156 $this->max_pool_size = $opts['poolsize'];
159 if (empty($opts['limit'])) {
160 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
163 if (!empty($opts['old'])) {
164 $opts['list'] = 1; // force listing..
167 $this->force = empty($opts['force']) ? 0 : 1;
169 if (!empty($opts['send-to'])) {
170 $this->send_to = $opts['send-to'];
174 var $queue = array();
175 var $domain_queue = array(); // false to use nextquee
176 var $next_queue = array();
179 function get($r,$opts=array())
181 $this->parseArgs($opts);
183 //date_default_timezone_set('UTC');
186 $this->generateNotifications();
188 //DB_DataObject::debugLevel(1);
189 $w = DB_DataObject::factory($this->table);
194 $ff = HTML_FlexyFramework::get();
197 $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this);
199 $this->server->assignQueues($this);
205 if (!empty($this->evtype)) {
206 $w->evtype = $this->evtype;
209 $w->server_id = $this->server->id;
212 if (!empty($opts['old'])) {
213 // show old and new...
215 $w->orderBy('act_when DESC'); // latest first
216 $w->limit($opts['limit']); // we can run
217 $total = min($w->count(), $opts['limit']);
221 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
222 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
224 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
226 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
230 $w->orderBy('act_when ASC'); // oldest first.
231 $total = min($w->count(), $opts['limit']);
232 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
234 $w->limit($opts['limit']); // we can run 1000 ...
245 $this->logecho("Nothing In Queue - DONE");
250 if (!empty($opts['list'])) {
253 while ($w->fetch()) {
257 $this->logecho("{$w->id} : {$w->person()->email} email : ".
258 $o->toEventString()." ". $w->status() );
263 //echo "BATCH SIZE: ". count($ar) . "\n";
267 // only add if we don't have any queued up..
268 if (empty($this->queue) && $w->fetch()) {
269 $this->queue[] = clone($w);
273 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
275 if (empty($this->queue)) {
276 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
277 if ($this->domain_queue !== false) {
278 $this->queue = $this->remainingDomainQueue();
282 break; // nothing more in queue.. and no remaining one
286 $p = array_shift($this->queue);
287 if (!$this->poolfree()) {
288 array_unshift($this->queue,$p); /// put it back on..
292 // not sure what happesn if person email and to_email is empty!!?
293 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
295 $black = $this->server->isBlacklisted($email);
296 if ($black !== false) {
297 $this->logecho("Blacklisted - try giving it to next server");
298 if (false === $this->server->updateNotifyToNextServer($p)) {
299 $ev = $this->addEvent('NOTIFY', $p, 'BLACKLISTED FROM our DB');
300 // we dont have an althenative server to update it with.
301 $this->logecho("Blacklisted - next server did not work - try again in 30 mins");
302 $this->server->updateNotifyToNextServer($w, date("Y-m-d H:i:s", strtotime('NOW + 30 MINUTES')),true);
303 // $this->errorHandler( $ev->remarks);
311 if ($this->poolHasDomain($email) > $this->max_to_domain) {
313 // push it to a 'domain specific queue'
314 $this->logecho("REQUEING - maxed out that domain - {$email}");
315 $this->pushQueueDomain($p, $email);
322 $this->run($p->id,$email);
327 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
328 if (!empty($this->next_queue)) {
330 foreach($this->next_queue as $p) {
331 if (false === $this->server->updateNotifyToNextServer($p)) {
332 $p->updateState("????");
338 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
339 // we should have a time limit here...
340 while(count($this->pool)) {
348 $this->logecho("DONE");
355 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
359 function generateNotifications()
361 // this should check each module for 'GenerateNotifications.php' class..
362 //and run it if found..
363 $ff = HTML_FlexyFramework::get();
365 $disabled = explode(',', $ff->disable);
367 $modules = array_reverse($this->modulesList());
369 // move 'project' one to the end...
371 foreach ($modules as $module){
372 if(in_array($module, $disabled)){
375 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
376 if(!file_exists($file)){
381 $class = "Pman_{$module}_GenerateNotifications";
383 if(!method_exists($x, 'generate')){
395 function run($id, $email='', $cmdOpts="")
398 static $renice = false;
400 require_once 'System.php';
401 $renice = System::which('renice');
407 $tn = $this->tempName('stdout', true);
408 $tne = $this->tempName('stderr', true);
409 $descriptorspec = array(
410 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
411 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
412 2 => array("file", $tne, 'w'), // stderr is a file to write to
413 // 2 => array("pipe", "w") // stderr is a file to write to
418 require_once 'System.php';
419 $php = System::which('php');
422 $sn = $_SERVER["SCRIPT_NAME"];
424 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
425 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
429 if (!empty($this->send_to)) {
430 $app .= ' --sent-to='.escapeshellarg($this->send_to);
432 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
436 //$this->logecho("call proc_open $cmd");
439 if ($this->max_pool_size === 1) {
440 $this->logecho("call passthru [{$email}] $cmd");
446 if (!empty($this->opts['dryrun'])) {
447 $this->logecho("DRY RUN");
451 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
452 $info = proc_get_status($p);
454 if ($this->nice_level !== false) {
455 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
458 $this->pool[] = array(
460 'pid' => $info['pid'],
471 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
479 foreach($this->pool as $p) {
481 //echo "CHECK PID: " . $p['pid'] . "\n";
484 $info = proc_get_status($p['proc']);
487 // update if necessday.
488 if ($info['pid'] && $p['pid'] != $info['pid']) {
489 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
490 $p['pid'] = $info['pid'];
493 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
495 if ($info['running']) {
497 //if (file_exists('/proc/'.$p['pid'])) {
498 $runtime = time() - $p['started'];
499 //echo "RUNTIME ({$p['pid']}): $runtime\n";
500 if ($runtime > $this->maxruntime) {
502 proc_terminate($p['proc'], 9);
503 //fclose($p['pipes'][1]);
504 fclose($p['pipes'][0]);
506 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
511 $w = DB_DataObject::factory($this->table);
512 $w->get($p['notify_id']);
514 if ($this->log_events) {
515 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
517 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
526 fclose($p['pipes'][0]);
527 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
528 //fclose($p['pipes'][1]);
530 proc_close($p['proc']);
533 if (file_exists('/proc/'. $p['pid'])) {
534 $this->logecho("proc PID={$p['pid']} still here - trying to wait");
535 pcntl_waitpid($p['pid'], $status, WNOHANG);
539 //if (file_exists('/proc/'.$p['pid'])) {
543 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
546 // at this point we could pop onto the queue the
547 $this->popQueueDomain($p['email']);
551 $this->logecho("POOL SIZE: ". count($pool) );
553 if (count($pool) < $this->max_pool_size) {
560 * see if pool is already trying to deliver to this domain.?
561 * -- if so it get's pushed to the end of the queue.
564 function poolHasDomain($email)
567 $ea = explode('@',$email);
568 $dom = strtolower(array_pop($ea));
569 foreach($this->pool as $p) {
570 $ea = explode('@',$p['email']);
571 $mdom = strtolower(array_pop($ea));
579 function popQueueDomain($email)
581 $ea = explode('@',$email);
582 $dom = strtolower(array_pop($ea));
583 if (empty($this->domain_queue[$dom])) {
586 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
590 function pushQueueDomain($e, $email)
592 if ($this->domain_queue === false) {
593 $this->next_queue[] = $e;
597 $ea = explode('@',$email);
598 $dom = strtolower(array_pop($ea));
599 if (!isset($this->domain_queue[$dom])) {
600 $this->domain_queue[$dom] = array();
602 $this->domain_queue[$dom][] = $e;
604 function remainingDomainQueue()
607 foreach($this->domain_queue as $dom => $ar) {
608 $ret = array_merge($ret, $ar);
610 $this->domain_queue = false;
615 if ($this->server->isFirstServer()) {
617 $p = DB_DataObject::factory($this->table);
623 act_start < NOW() - INTERVAL {$this->clear_interval}
627 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
628 $p = DB_DataObject::factory($this->table);
641 act_start < NOW() - INTERVAL {$this->clear_interval}
653 $this->logecho("DONE");
656 function logecho($str)
658 echo date("Y-m-d H:i:s - ") . $str . "\n";