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..
129 var $poolname = 'core';
135 $ff = HTML_FlexyFramework::get();
137 die("access denied");
139 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
145 function parseArgs(&$opts)
147 if ($opts['debug']) {
148 DB_DataObject::debugLevel($opts['debug']);
152 if (!empty($opts['poolsize'])) {
153 $this->max_pool_size = $opts['poolsize'];
156 if (empty($opts['limit'])) {
157 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
160 if (!empty($opts['old'])) {
161 $opts['list'] = 1; // force listing..
164 $this->force = empty($opts['force']) ? 0 : 1;
166 if (!empty($opts['send-to'])) {
167 $this->send_to = $opts['send-to'];
171 var $queue = array();
172 var $domain_queue = array(); // false to use nextquee
173 var $next_queue = array();
176 function get($r,$opts=array())
178 $this->parseArgs($opts);
180 //date_default_timezone_set('UTC');
183 $this->generateNotifications();
185 $this->assignQueues();
187 //DB_DataObject::debugLevel(1);
188 $w = DB_DataObject::factory($this->table);
193 $ff = HTML_FlexyFramework::get();
196 $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this);
197 if (!empty($ff->Core_Notify['servers']) && empty($ff->Core_Notify['servers-non-pool'][gethostname()])) {
199 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
200 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
202 $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
204 if (!empty($this->evtype)) {
205 $w->evtype = $this->evtype;
210 if (!empty($opts['old'])) {
211 // show old and new...
213 $w->orderBy('act_when DESC'); // latest first
214 $w->limit($opts['limit']); // we can run
215 $total = min($w->count(), $opts['limit']);
219 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
220 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
222 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
224 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
227 $w->orderBy('act_when ASC'); // oldest first.
228 $total = min($w->count(), $opts['limit']);
229 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
231 $w->limit($opts['limit']); // we can run 1000 ...
243 $this->logecho("Nothing In Queue - DONE");
248 if (!empty($opts['list'])) {
251 while ($w->fetch()) {
255 $this->logecho("{$w->id} : {$w->person()->email} email : ".
256 $o->toEventString()." ". $w->status() );
261 //echo "BATCH SIZE: ". count($ar) . "\n";
265 // only add if we don't have any queued up..
266 if (empty($this->queue) && $w->fetch()) {
267 $this->queue[] = clone($w);
271 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
273 if (empty($this->queue)) {
274 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
275 if ($this->domain_queue !== false) {
276 $this->queue = $this->remainingDomainQueue();
280 break; // nothing more in queue.. and no remaining one
284 $p = array_shift($this->queue);
285 if (!$this->poolfree()) {
286 array_unshift($this->queue,$p); /// put it back on..
290 // not sure what happesn if person email and to_email is empty!!?
291 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
293 $black = $this->isBlacklisted($email);
294 if ($black !== false) {
295 $this->logecho("DOMAIN blacklisted - {$email} - moving to another pool");
296 $this->updateServer($p, $black);
301 if ($this->poolHasDomain($email) > $this->max_to_domain) {
303 // push it to a 'domain specific queue'
304 $this->logecho("REQUEING - maxed out that domain - {$email}");
305 $this->pushQueueDomain($p, $email);
313 $this->run($p->id,$email);
318 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
319 if (!empty($this->next_queue)) {
321 foreach($this->next_queue as $p) {
322 $this->updateServer($p);
327 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
328 // we should have a time limit here...
329 while(count($this->pool)) {
337 $this->logecho("DONE");
342 function isBlacklisted($email)
344 // return current server id..
345 $ff = HTML_FlexyFramework::get();
346 //$this->logecho("CHECK BLACKLISTED - {$email}");
347 if (empty($ff->Core_Notify['servers'])) {
351 if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
356 $ea = explode('@',$email);
357 $dom = strtolower(array_pop($ea));
359 //$this->logecho("CHECK BLACKLISTED DOM - {$dom}");
360 if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
363 //$this->logecho("RETURN BLACKLISTED TRUE");
364 return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
367 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
368 function updateServer($ww, $exclude = -1)
370 $w = DB_DataObject::factory($ww->tableName());
373 $ff = HTML_FlexyFramework::get();
375 if (empty($ff->Core_Notify['servers'])) {
378 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
379 if ($exclude == $num ) {
380 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
384 $w->server_id = $num;
386 $w->act_when = $w->sqlValue('NOW() + INTERVAL 1 MINUTE');
393 function generateNotifications()
395 // this should check each module for 'GenerateNotifications.php' class..
396 //and run it if found..
397 $ff = HTML_FlexyFramework::get();
399 $disabled = explode(',', $ff->disable);
401 $modules = array_reverse($this->modulesList());
403 // move 'project' one to the end...
405 foreach ($modules as $module){
406 if(in_array($module, $disabled)){
409 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
410 if(!file_exists($file)){
415 $class = "Pman_{$module}_GenerateNotifications";
417 if(!method_exists($x, 'generate')){
427 function assignQueues()
430 DB_DataObject::Factory('core_notify_server')->assignQueues($this);
435 function run($id, $email='', $cmdOpts="")
438 static $renice = false;
440 require_once 'System.php';
441 $renice = System::which('renice');
447 $tn = $this->tempName('stdout', true);
448 $descriptorspec = array(
449 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
450 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
451 2 => array("pipe", "w") // stderr is a file to write to
456 require_once 'System.php';
457 $php = System::which('php');
460 $sn = $_SERVER["SCRIPT_NAME"];
462 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
463 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
467 if (!empty($this->send_to)) {
468 $app .= ' --sent-to='.escapeshellarg($this->send_to);
470 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
474 //$this->logecho("call proc_open $cmd");
477 if ($this->max_pool_size === 1) {
478 $this->logecho("call passthru [{$email}] $cmd");
484 if (!empty($this->opts['dryrun'])) {
485 $this->logecho("DRY RUN");
489 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
490 $info = proc_get_status($p);
492 if ($this->nice_level !== false) {
493 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
496 $this->pool[] = array(
498 'pid' => $info['pid'],
508 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
516 foreach($this->pool as $p) {
518 //echo "CHECK PID: " . $p['pid'] . "\n";
519 $info = proc_get_status($p['proc']);
522 // update if necessday.
523 if ($info['pid'] && $p['pid'] != $info['pid']) {
524 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
525 $p['pid'] = $info['pid'];
528 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
530 if ($info['running']) {
532 //if (file_exists('/proc/'.$p['pid'])) {
533 $runtime = time() - $p['started'];
534 //echo "RUNTIME ({$p['pid']}): $runtime\n";
535 if ($runtime > $this->maxruntime) {
537 proc_terminate($p['proc'], 9);
538 //fclose($p['pipes'][1]);
539 fclose($p['pipes'][0]);
540 fclose($p['pipes'][2]);
541 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
545 $w = DB_DataObject::factory($this->table);
546 $w->get($p['notify_id']);
548 if ($this->log_events) {
549 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
551 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
560 fclose($p['pipes'][0]);
561 fclose($p['pipes'][2]);
562 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
563 //fclose($p['pipes'][1]);
565 proc_close($p['proc']);
569 //if (file_exists('/proc/'.$p['pid'])) {
573 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) );
575 // at this point we could pop onto the queue the
576 $this->popQueueDomain($p['email']);
580 $this->logecho("POOL SIZE: ". count($pool) );
582 if (count($pool) < $this->max_pool_size) {
589 * see if pool is already trying to deliver to this domain.?
590 * -- if so it get's pushed to the end of the queue.
593 function poolHasDomain($email)
596 $ea = explode('@',$email);
597 $dom = strtolower(array_pop($ea));
598 foreach($this->pool as $p) {
599 $ea = explode('@',$p['email']);
600 $mdom = strtolower(array_pop($ea));
608 function popQueueDomain($email)
610 $ea = explode('@',$email);
611 $dom = strtolower(array_pop($ea));
612 if (empty($this->domain_queue[$dom])) {
615 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
619 function pushQueueDomain($e, $email)
621 if ($this->domain_queue === false) {
622 $this->next_queue[] = $e;
626 $ea = explode('@',$email);
627 $dom = strtolower(array_pop($ea));
628 if (!isset($this->domain_queue[$dom])) {
629 $this->domain_queue[$dom] = array();
631 $this->domain_queue[$dom][] = $e;
633 function remainingDomainQueue()
636 foreach($this->domain_queue as $dom => $ar) {
637 $ret = array_merge($ret, $ar);
639 $this->domain_queue = false;
647 $this->logecho("DONE");
650 function logecho($str)
652 echo date("Y-m-d H:i:s - ") . $str . "\n";