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;
211 if (!empty($opts['old'])) {
212 // show old and new...
214 $w->orderBy('act_when DESC'); // latest first
215 $w->limit($opts['limit']); // we can run
216 $total = min($w->count(), $opts['limit']);
220 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
221 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
223 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
225 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
228 $w->orderBy('act_when ASC'); // oldest first.
229 $total = min($w->count(), $opts['limit']);
230 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
232 $w->limit($opts['limit']); // we can run 1000 ...
244 $this->logecho("Nothing In Queue - DONE");
249 if (!empty($opts['list'])) {
252 while ($w->fetch()) {
256 $this->logecho("{$w->id} : {$w->person()->email} email : ".
257 $o->toEventString()." ". $w->status() );
262 //echo "BATCH SIZE: ". count($ar) . "\n";
266 // only add if we don't have any queued up..
267 if (empty($this->queue) && $w->fetch()) {
268 $this->queue[] = clone($w);
272 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
274 if (empty($this->queue)) {
275 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
276 if ($this->domain_queue !== false) {
277 $this->queue = $this->remainingDomainQueue();
281 break; // nothing more in queue.. and no remaining one
285 $p = array_shift($this->queue);
286 if (!$this->poolfree()) {
287 array_unshift($this->queue,$p); /// put it back on..
291 // not sure what happesn if person email and to_email is empty!!?
292 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
294 $black = $this->server->isBlacklisted($email);
295 if ($black !== false) {
297 if (false === $this->server->updateNotifyToNextServer($p)) {
298 $p->updateState("????");
305 if ($this->poolHasDomain($email) > $this->max_to_domain) {
307 // push it to a 'domain specific queue'
308 $this->logecho("REQUEING - maxed out that domain - {$email}");
309 $this->pushQueueDomain($p, $email);
316 $this->run($p->id,$email);
321 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
322 if (!empty($this->next_queue)) {
324 foreach($this->next_queue as $p) {
325 if (false === $this->server->updateNotifyToNextServer($p)) {
326 $p->updateState("????");
332 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
333 // we should have a time limit here...
334 while(count($this->pool)) {
342 $this->logecho("DONE");
349 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
353 function generateNotifications()
355 // this should check each module for 'GenerateNotifications.php' class..
356 //and run it if found..
357 $ff = HTML_FlexyFramework::get();
359 $disabled = explode(',', $ff->disable);
361 $modules = array_reverse($this->modulesList());
363 // move 'project' one to the end...
365 foreach ($modules as $module){
366 if(in_array($module, $disabled)){
369 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
370 if(!file_exists($file)){
375 $class = "Pman_{$module}_GenerateNotifications";
377 if(!method_exists($x, 'generate')){
389 function run($id, $email='', $cmdOpts="")
392 static $renice = false;
394 require_once 'System.php';
395 $renice = System::which('renice');
401 $tn = $this->tempName('stdout', true);
402 $descriptorspec = array(
403 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
404 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
405 2 => array("pipe", "w") // stderr is a file to write to
410 require_once 'System.php';
411 $php = System::which('php');
414 $sn = $_SERVER["SCRIPT_NAME"];
416 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
417 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
421 if (!empty($this->send_to)) {
422 $app .= ' --sent-to='.escapeshellarg($this->send_to);
424 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
428 //$this->logecho("call proc_open $cmd");
431 if ($this->max_pool_size === 1) {
432 $this->logecho("call passthru [{$email}] $cmd");
438 if (!empty($this->opts['dryrun'])) {
439 $this->logecho("DRY RUN");
443 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
444 $info = proc_get_status($p);
446 if ($this->nice_level !== false) {
447 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
450 $this->pool[] = array(
452 'pid' => $info['pid'],
462 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
470 foreach($this->pool as $p) {
472 //echo "CHECK PID: " . $p['pid'] . "\n";
473 $info = proc_get_status($p['proc']);
476 // update if necessday.
477 if ($info['pid'] && $p['pid'] != $info['pid']) {
478 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
479 $p['pid'] = $info['pid'];
482 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
484 if ($info['running']) {
486 //if (file_exists('/proc/'.$p['pid'])) {
487 $runtime = time() - $p['started'];
488 //echo "RUNTIME ({$p['pid']}): $runtime\n";
489 if ($runtime > $this->maxruntime) {
491 proc_terminate($p['proc'], 9);
492 //fclose($p['pipes'][1]);
493 fclose($p['pipes'][0]);
494 fclose($p['pipes'][2]);
495 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
499 $w = DB_DataObject::factory($this->table);
500 $w->get($p['notify_id']);
502 if ($this->log_events) {
503 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
505 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
514 fclose($p['pipes'][0]);
515 fclose($p['pipes'][2]);
516 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
517 //fclose($p['pipes'][1]);
519 proc_close($p['proc']);
523 //if (file_exists('/proc/'.$p['pid'])) {
527 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) );
529 // at this point we could pop onto the queue the
530 $this->popQueueDomain($p['email']);
534 $this->logecho("POOL SIZE: ". count($pool) );
536 if (count($pool) < $this->max_pool_size) {
543 * see if pool is already trying to deliver to this domain.?
544 * -- if so it get's pushed to the end of the queue.
547 function poolHasDomain($email)
550 $ea = explode('@',$email);
551 $dom = strtolower(array_pop($ea));
552 foreach($this->pool as $p) {
553 $ea = explode('@',$p['email']);
554 $mdom = strtolower(array_pop($ea));
562 function popQueueDomain($email)
564 $ea = explode('@',$email);
565 $dom = strtolower(array_pop($ea));
566 if (empty($this->domain_queue[$dom])) {
569 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
573 function pushQueueDomain($e, $email)
575 if ($this->domain_queue === false) {
576 $this->next_queue[] = $e;
580 $ea = explode('@',$email);
581 $dom = strtolower(array_pop($ea));
582 if (!isset($this->domain_queue[$dom])) {
583 $this->domain_queue[$dom] = array();
585 $this->domain_queue[$dom][] = $e;
587 function remainingDomainQueue()
590 foreach($this->domain_queue as $dom => $ar) {
591 $ret = array_merge($ret, $ar);
593 $this->domain_queue = false;
598 if ($this->server->isFirstServer()) {
599 $p = DB_DataObject::factory($this->table);
605 act_start < NOW() - INTERVAL {$this->clear_interval}
609 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
610 $p = DB_DataObject::factory($this->table);
623 act_start < NOW() - INTERVAL {$this->clear_interval}
635 $this->logecho("DONE");
638 function logecho($str)
640 echo date("Y-m-d H:i:s - ") . $str . "\n";