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..
134 $ff = HTML_FlexyFramework::get();
136 die("access denied");
138 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
144 function parseArgs(&$opts)
146 if ($opts['debug']) {
147 DB_DataObject::debugLevel($opts['debug']);
151 if (!empty($opts['poolsize'])) {
152 $this->max_pool_size = $opts['poolsize'];
155 if (empty($opts['limit'])) {
156 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
159 if (!empty($opts['old'])) {
160 $opts['list'] = 1; // force listing..
163 $this->force = empty($opts['force']) ? 0 : 1;
165 if (!empty($opts['send-to'])) {
166 $this->send_to = $opts['send-to'];
170 var $queue = array();
171 var $domain_queue = array(); // false to use nextquee
172 var $next_queue = array();
175 function get($r,$opts=array())
177 $this->parseArgs($opts);
179 //date_default_timezone_set('UTC');
182 $this->generateNotifications();
184 $this->assignQueues();
186 //DB_DataObject::debugLevel(1);
187 $w = DB_DataObject::factory($this->table);
192 $ff = HTML_FlexyFramework::get();
193 if (!empty($ff->Core_Notify['servers'])) {
194 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
195 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
197 $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
199 if (!empty($this->evtype)) {
200 $w->evtype = $this->evtype;
205 if (!empty($opts['old'])) {
206 // show old and new...
208 $w->orderBy('act_when DESC'); // latest first
209 $w->limit($opts['limit']); // we can run
210 $total = min($w->count(), $opts['limit']);
214 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
215 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
217 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
219 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
222 $w->orderBy('act_when ASC'); // oldest first.
223 $total = min($w->count(), $opts['limit']);
224 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
226 $w->limit($opts['limit']); // we can run 1000 ...
238 $this->logecho("Nothing In Queue - DONE");
243 if (!empty($opts['list'])) {
246 while ($w->fetch()) {
250 $this->logecho("{$w->id} : {$w->person()->email} email : ".
251 $o->toEventString()." ". $w->status() );
256 //echo "BATCH SIZE: ". count($ar) . "\n";
260 // only add if we don't have any queued up..
261 if (empty($this->queue) && $w->fetch()) {
262 $this->queue[] = clone($w);
266 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
268 if (empty($this->queue)) {
269 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
270 if ($this->domain_queue !== false) {
271 $this->queue = $this->remainingDomainQueue();
275 break; // nothing more in queue.. and no remaining one
279 $p = array_shift($this->queue);
280 if (!$this->poolfree()) {
281 array_unshift($this->queue,$p); /// put it back on..
285 // not sure what happesn if person email and to_email is empty!!?
286 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
288 $black = $this->isBlacklisted($email);
289 if ($black !== false) {
290 $this->logecho("DOMAIN blacklisted - {$email} - moving to another pool");
291 $this->updateServer($p, $black);
296 if ($this->poolHasDomain($email) > $this->max_to_domain) {
298 // push it to a 'domain specific queue'
299 $this->logecho("REQUEING - maxed out that domain - {$email}");
300 $this->pushQueueDomain($p, $email);
308 $this->run($p->id,$email);
313 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
314 if (!empty($this->next_queue)) {
316 foreach($this->next_queue as $p) {
317 $this->updateServer($p);
322 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
323 // we should have a time limit here...
324 while(count($this->pool)) {
332 $this->logecho("DONE");
337 function isBlacklisted($email)
339 // return current server id..
340 $ff = HTML_FlexyFramework::get();
341 //$this->logecho("CHECK BLACKLISTED - {$email}");
342 if (empty($ff->Core_Notify['servers'])) {
346 if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
351 $ea = explode('@',$email);
352 $dom = strtolower(array_pop($ea));
354 //$this->logecho("CHECK BLACKLISTED DOM - {$dom}");
355 if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
358 //$this->logecho("RETURN BLACKLISTED TRUE");
359 return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
362 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
363 function updateServer($ww, $exclude = -1)
365 $w = DB_DataObject::factory($ww->tableName());
368 $ff = HTML_FlexyFramework::get();
370 if (empty($ff->Core_Notify['servers'])) {
373 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
374 if ($exclude == $num ) {
375 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
379 $w->server_id = $num;
381 $w->act_when = $w->sqlValue('NOW() + INTERVAL 1 MINUTE');
388 function generateNotifications()
390 // this should check each module for 'GenerateNotifications.php' class..
391 //and run it if found..
392 $ff = HTML_FlexyFramework::get();
394 $disabled = explode(',', $ff->disable);
396 $modules = array_reverse($this->modulesList());
398 // move 'project' one to the end...
400 foreach ($modules as $module){
401 if(in_array($module, $disabled)){
404 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
405 if(!file_exists($file)){
410 $class = "Pman_{$module}_GenerateNotifications";
412 if(!method_exists($x, 'generate')){
422 function assignQueues()
424 $ff = HTML_FlexyFramework::get();
426 if (empty($ff->Core_Notify['servers'])) {
430 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
431 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
433 // only run this on the main server...
434 if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
438 $num_servers = count(array_keys($ff->Core_Notify['servers']));
439 $p = DB_DataObject::factory($this->table);
445 act_start < NOW() + INTERVAL 3 HOUR
450 if ($p->count() < 1) {
453 $p = DB_DataObject::factory($this->table);
454 // 6 seconds on this machne...
459 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END +1) % {$num_servers})
465 act_start < NOW() + INTERVAL 3 HOUR
477 function run($id, $email='', $cmdOpts="")
480 static $renice = false;
482 require_once 'System.php';
483 $renice = System::which('renice');
489 $tn = $this->tempName('stdout', true);
490 $descriptorspec = array(
491 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
492 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
493 2 => array("pipe", "w") // stderr is a file to write to
498 require_once 'System.php';
499 $php = System::which('php');
502 $sn = $_SERVER["SCRIPT_NAME"];
504 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
505 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
509 if (!empty($this->send_to)) {
510 $app .= ' --sent-to='.escapeshellarg($this->send_to);
512 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
516 //$this->logecho("call proc_open $cmd");
519 if ($this->max_pool_size === 1) {
520 $this->logecho("call passthru [{$email}] $cmd");
526 if (!empty($this->opts['dryrun'])) {
527 $this->logecho("DRY RUN");
531 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
532 $info = proc_get_status($p);
534 if ($this->nice_level !== false) {
535 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
538 $this->pool[] = array(
540 'pid' => $info['pid'],
550 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
558 foreach($this->pool as $p) {
560 //echo "CHECK PID: " . $p['pid'] . "\n";
561 $info = proc_get_status($p['proc']);
564 // update if necessday.
565 if ($info['pid'] && $p['pid'] != $info['pid']) {
566 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
567 $p['pid'] = $info['pid'];
570 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
572 if ($info['running']) {
574 //if (file_exists('/proc/'.$p['pid'])) {
575 $runtime = time() - $p['started'];
576 //echo "RUNTIME ({$p['pid']}): $runtime\n";
577 if ($runtime > $this->maxruntime) {
579 proc_terminate($p['proc'], 9);
580 //fclose($p['pipes'][1]);
581 fclose($p['pipes'][0]);
582 fclose($p['pipes'][2]);
583 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
587 $w = DB_DataObject::factory($this->table);
588 $w->get($p['notify_id']);
590 if ($this->log_events) {
591 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
593 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
602 fclose($p['pipes'][0]);
603 fclose($p['pipes'][2]);
604 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
605 //fclose($p['pipes'][1]);
607 proc_close($p['proc']);
611 //if (file_exists('/proc/'.$p['pid'])) {
615 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) );
617 // at this point we could pop onto the queue the
618 $this->popQueueDomain($p['email']);
622 $this->logecho("POOL SIZE: ". count($pool) );
624 if (count($pool) < $this->max_pool_size) {
631 * see if pool is already trying to deliver to this domain.?
632 * -- if so it get's pushed to the end of the queue.
635 function poolHasDomain($email)
638 $ea = explode('@',$email);
639 $dom = strtolower(array_pop($ea));
640 foreach($this->pool as $p) {
641 $ea = explode('@',$p['email']);
642 $mdom = strtolower(array_pop($ea));
650 function popQueueDomain($email)
652 $ea = explode('@',$email);
653 $dom = strtolower(array_pop($ea));
654 if (empty($this->domain_queue[$dom])) {
657 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
661 function pushQueueDomain($e, $email)
663 if ($this->domain_queue === false) {
664 $this->next_queue[] = $e;
668 $ea = explode('@',$email);
669 $dom = strtolower(array_pop($ea));
670 if (!isset($this->domain_queue[$dom])) {
671 $this->domain_queue[$dom] = array();
673 $this->domain_queue[$dom][] = $e;
675 function remainingDomainQueue()
678 foreach($this->domain_queue as $dom => $ar) {
679 $ret = array_merge($ret, $ar);
681 $this->domain_queue = false;
689 $this->logecho("DONE");
692 function logecho($str)
694 echo date("Y-m-d H:i:s - ") . $str . "\n";