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())
182 // if ($this->database_is_locked()) {
183 // die("LATER - DATABASE IS LOCKED");
187 $this->parseArgs($opts);
189 //date_default_timezone_set('UTC');
192 $this->generateNotifications();
194 //DB_DataObject::debugLevel(1);
195 $w = DB_DataObject::factory($this->table);
200 $ff = HTML_FlexyFramework::get();
203 $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this);
205 $this->server->assignQueues($this);
211 if (!empty($this->evtype)) {
212 $w->evtype = $this->evtype;
215 $w->server_id = $this->server->id;
218 if (!empty($opts['old'])) {
219 // show old and new...
221 $w->orderBy('act_when DESC'); // latest first
222 $w->limit($opts['limit']); // we can run
223 $total = min($w->count(), $opts['limit']);
227 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
228 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
230 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
232 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
236 $w->orderBy('act_when ASC'); // oldest first.
237 $total = min($w->count(), $opts['limit']);
238 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
240 $w->limit($opts['limit']); // we can run 1000 ...
251 $this->logecho("Nothing In Queue - DONE");
256 if (!empty($opts['list'])) {
259 while ($w->fetch()) {
263 $this->logecho("{$w->id} : {$w->person()->email} email : ".
264 $o->toEventString()." ". $w->status() );
269 //echo "BATCH SIZE: ". count($ar) . "\n";
273 // only add if we don't have any queued up..
274 if (empty($this->queue) && $w->fetch()) {
275 $this->queue[] = clone($w);
279 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
281 if (empty($this->queue)) {
282 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
283 if ($this->domain_queue !== false) {
284 $this->queue = $this->remainingDomainQueue();
288 break; // nothing more in queue.. and no remaining one
292 $p = array_shift($this->queue);
293 if (!$this->poolfree()) {
294 array_unshift($this->queue,$p); /// put it back on..
298 // not sure what happesn if person email and to_email is empty!!?
299 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
301 $black = $this->server->isBlacklisted($email);
302 if ($black !== false) {
303 $this->logecho("Blacklisted - try giving it to next server");
304 if (false === $this->server->updateNotifyToNextServer($p)) {
305 $ev = $this->addEvent('NOTIFY', $p, 'BLACKLISTED FROM our DB');
306 // we dont have an althenative server to update it with.
307 $this->logecho("Blacklisted - next server did not work - try again in 30 mins");
308 $this->server->updateNotifyToNextServer($w, date("Y-m-d H:i:s", strtotime('NOW + 30 MINUTES')),true);
309 // $this->errorHandler( $ev->remarks);
317 if ($this->poolHasDomain($email) > $this->max_to_domain) {
319 // push it to a 'domain specific queue'
320 $this->logecho("REQUEING - maxed out that domain - {$email}");
321 $this->pushQueueDomain($p, $email);
328 $this->run($p->id,$email);
333 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
334 if (!empty($this->next_queue)) {
336 foreach($this->next_queue as $p) {
337 if (false === $this->server->updateNotifyToNextServer($p)) {
338 $p->updateState("????");
344 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
345 // we should have a time limit here...
346 while(count($this->pool)) {
354 $this->logecho("DONE");
361 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
365 function generateNotifications()
367 // this should check each module for 'GenerateNotifications.php' class..
368 //and run it if found..
369 $ff = HTML_FlexyFramework::get();
371 $disabled = explode(',', $ff->disable);
373 $modules = array_reverse($this->modulesList());
375 // move 'project' one to the end...
377 foreach ($modules as $module){
378 if(in_array($module, $disabled)){
381 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
382 if(!file_exists($file)){
387 $class = "Pman_{$module}_GenerateNotifications";
389 if(!method_exists($x, 'generate')){
401 function run($id, $email='', $cmdOpts="")
404 static $renice = false;
406 require_once 'System.php';
407 $renice = System::which('renice');
413 $tn = $this->tempName('stdout', true);
414 $tne = $this->tempName('stderr', true);
415 $descriptorspec = array(
416 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
417 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
418 2 => array("file", $tne, 'w'), // stderr is a file to write to
419 // 2 => array("pipe", "w") // stderr is a file to write to
424 require_once 'System.php';
425 $php = System::which('php');
428 $sn = $_SERVER["SCRIPT_NAME"];
430 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
431 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
435 if (!empty($this->send_to)) {
436 $app .= ' --sent-to='.escapeshellarg($this->send_to);
438 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
442 //$this->logecho("call proc_open $cmd");
445 if ($this->max_pool_size === 1) {
446 $this->logecho("call passthru [{$email}] $cmd");
452 if (!empty($this->opts['dryrun'])) {
453 $this->logecho("DRY RUN");
457 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
458 $info = proc_get_status($p);
460 if ($this->nice_level !== false) {
461 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
464 $this->pool[] = array(
466 'pid' => $info['pid'],
477 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
485 foreach($this->pool as $p) {
487 //echo "CHECK PID: " . $p['pid'] . "\n";
490 $info = proc_get_status($p['proc']);
493 // update if necessday.
494 if ($info['pid'] && $p['pid'] != $info['pid']) {
495 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
496 $p['pid'] = $info['pid'];
499 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
501 if ($info['running']) {
503 //if (file_exists('/proc/'.$p['pid'])) {
504 $runtime = time() - $p['started'];
505 //echo "RUNTIME ({$p['pid']}): $runtime\n";
506 if ($runtime > $this->maxruntime) {
508 proc_terminate($p['proc'], 9);
509 //fclose($p['pipes'][1]);
510 fclose($p['pipes'][0]);
512 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
517 $w = DB_DataObject::factory($this->table);
518 $w->get($p['notify_id']);
520 if ($this->log_events) {
521 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
523 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
532 fclose($p['pipes'][0]);
533 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
534 //fclose($p['pipes'][1]);
536 proc_close($p['proc']);
539 if (file_exists('/proc/'. $p['pid'])) {
540 $this->logecho("proc PID={$p['pid']} still here - trying to wait");
541 pcntl_waitpid($p['pid'], $status, WNOHANG);
545 //if (file_exists('/proc/'.$p['pid'])) {
549 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
552 // at this point we could pop onto the queue the
553 $this->popQueueDomain($p['email']);
557 $this->logecho("POOL SIZE: ". count($pool) );
559 if (count($pool) < $this->max_pool_size) {
566 * see if pool is already trying to deliver to this domain.?
567 * -- if so it get's pushed to the end of the queue.
570 function poolHasDomain($email)
573 $ea = explode('@',$email);
574 $dom = strtolower(array_pop($ea));
575 foreach($this->pool as $p) {
576 $ea = explode('@',$p['email']);
577 $mdom = strtolower(array_pop($ea));
585 function popQueueDomain($email)
587 $ea = explode('@',$email);
588 $dom = strtolower(array_pop($ea));
589 if (empty($this->domain_queue[$dom])) {
592 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
596 function pushQueueDomain($e, $email)
598 if ($this->domain_queue === false) {
599 $this->next_queue[] = $e;
603 $ea = explode('@',$email);
604 $dom = strtolower(array_pop($ea));
605 if (!isset($this->domain_queue[$dom])) {
606 $this->domain_queue[$dom] = array();
608 $this->domain_queue[$dom][] = $e;
610 function remainingDomainQueue()
613 foreach($this->domain_queue as $dom => $ar) {
614 $ret = array_merge($ret, $ar);
616 $this->domain_queue = false;
621 if ($this->server->isFirstServer()) {
623 $p = DB_DataObject::factory($this->table);
629 act_start < NOW() - INTERVAL {$this->clear_interval}
633 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
634 $p = DB_DataObject::factory($this->table);
647 act_start < NOW() - INTERVAL {$this->clear_interval}
659 $this->logecho("DONE");
662 function logecho($str)
664 echo date("Y-m-d H:i:s - ") . $str . "\n";