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..
131 $ff = HTML_FlexyFramework::get();
133 die("access denied");
135 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
141 function parseArgs(&$opts)
143 if ($opts['debug']) {
144 DB_DataObject::debugLevel($opts['debug']);
148 if (!empty($opts['poolsize'])) {
149 $this->max_pool_size = $opts['poolsize'];
152 if (empty($opts['limit'])) {
153 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
156 if (!empty($opts['old'])) {
157 $opts['list'] = 1; // force listing..
160 $this->force = empty($opts['force']) ? 0 : 1;
162 if (!empty($opts['send-to'])) {
163 $this->send_to = $opts['send-to'];
167 var $queue = array();
168 var $domain_queue = array(); // false to use nextquee
169 var $next_queue = array();
172 function get($r,$opts=array())
174 $this->parseArgs($opts);
176 //date_default_timezone_set('UTC');
179 $this->generateNotifications();
181 $this->assignQueues();
183 //DB_DataObject::debugLevel(1);
184 $w = DB_DataObject::factory($this->table);
189 $ff = HTML_FlexyFramework::get();
190 if (!empty($ff->Core_Notify['servers'])) {
191 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
192 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
194 $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
196 if (!empty($this->evtype)) {
197 $w->evtype = $this->evtype;
202 if (!empty($opts['old'])) {
203 // show old and new...
205 $w->orderBy('act_when DESC'); // latest first
206 $w->limit($opts['limit']); // we can run
207 $total = min($w->count(), $opts['limit']);
211 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
212 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
214 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
216 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
219 $w->orderBy('act_when ASC'); // oldest first.
220 $total = min($w->count(), $opts['limit']);
221 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
223 $w->limit($opts['limit']); // we can run 1000 ...
236 if (!empty($opts['list'])) {
239 while ($w->fetch()) {
243 $this->logecho("{$w->id} : {$w->person()->email} email : ".
244 $o->toEventString()." ". $w->status() );
249 //echo "BATCH SIZE: ". count($ar) . "\n";
253 // only add if we don't have any queued up..
254 if (empty($this->queue) && $w->fetch()) {
255 $this->queue[] = clone($w);
259 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
261 if (empty($this->queue)) {
262 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
263 if ($this->domain_queue !== false) {
264 $this->queue = $this->remainingDomainQueue();
268 break; // nothing more in queue.. and no remaining one
272 $p = array_shift($this->queue);
273 if (!$this->poolfree()) {
274 array_unshift($this->queue,$p); /// put it back on..
278 // not sure what happesn if person email and to_email is empty!!?
279 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
281 $black = $this->isBlacklisted($email);
282 if ($black !== false) {
283 $this->logecho("DOMAIN blacklisted - {$email} - moving to another pool");
284 $this->updateServer($p, $black);
289 if ($this->poolHasDomain($email) > $this->max_to_domain) {
291 // push it to a 'domain specific queue'
292 $this->logecho("REQUEING - maxed out that domain - {$email}");
293 $this->pushQueueDomain($p, $email);
301 $this->run($p->id,$email);
306 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
307 if (!empty($this->next_queue)) {
309 foreach($this->next_queue as $p) {
310 $this->updateServer($p);
315 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
316 // we should have a time limit here...
317 while(count($this->pool)) {
325 $this->logecho("DONE");
330 function isBlacklisted($email)
332 // return current server id..
333 if (empty($ff->Core_Notify['servers'])) {
337 if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
342 $ea = explode('@',$email);
343 $dom = strtolower(array_pop($ea));
344 if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
347 return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
350 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
351 function updateServer($w, $exclude = -1)
353 $ff = HTML_FlexyFramework::get();
355 if (empty($ff->Core_Notify['servers'])) {
358 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
359 if ($exclude == $num ) {
360 $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
364 $w->server_id = $num;
366 $w->act_when = $w->sqlValue('NOW + INTERVAL 1 MINUTE');
373 function generateNotifications()
375 // this should check each module for 'GenerateNotifications.php' class..
376 //and run it if found..
377 $ff = HTML_FlexyFramework::get();
379 $disabled = explode(',', $ff->disable);
381 $modules = array_reverse($this->modulesList());
383 // move 'project' one to the end...
385 foreach ($modules as $module){
386 if(in_array($module, $disabled)){
389 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
390 if(!file_exists($file)){
395 $class = "Pman_{$module}_GenerateNotifications";
397 if(!method_exists($x, 'generate')){
407 function assignQueues()
409 $ff = HTML_FlexyFramework::get();
411 if (empty($ff->Core_Notify['servers'])) {
415 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
416 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
418 // only run this on the main server...
419 if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
423 $num_servers = count(array_keys($ff->Core_Notify['servers']));
424 $p = DB_DataObject::factory($this->table);
430 act_start < NOW() + INTERVAL 3 HOUR
435 if ($p->count() < 1) {
438 $p = DB_DataObject::factory($this->table);
439 // 6 seconds on this machne...
444 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END +1) % {$num_servers})
450 act_start < NOW() + INTERVAL 3 HOUR
462 function run($id, $email='', $cmdOpts="")
465 static $renice = false;
467 require_once 'System.php';
468 $renice = System::which('renice');
474 $tn = $this->tempName('stdout', true);
475 $descriptorspec = array(
476 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
477 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
478 2 => array("pipe", "w") // stderr is a file to write to
483 require_once 'System.php';
484 $php = System::which('php');
487 $sn = $_SERVER["SCRIPT_NAME"];
489 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
490 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
494 if (!empty($this->send_to)) {
495 $app .= ' --sent-to='.escapeshellarg($this->send_to);
497 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
501 //$this->logecho("call proc_open $cmd");
504 if ($this->max_pool_size === 1) {
505 $this->logecho("call passthru [{$email}] $cmd");
511 if (!empty($this->opts['dryrun'])) {
512 $this->logecho("DRY RUN");
516 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
517 $info = proc_get_status($p);
519 if ($this->nice_level !== false) {
520 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
523 $this->pool[] = array(
525 'pid' => $info['pid'],
535 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
543 foreach($this->pool as $p) {
545 //echo "CHECK PID: " . $p['pid'] . "\n";
546 $info = proc_get_status($p['proc']);
549 // update if necessday.
550 if ($info['pid'] && $p['pid'] != $info['pid']) {
551 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
552 $p['pid'] = $info['pid'];
555 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
557 if ($info['running']) {
559 //if (file_exists('/proc/'.$p['pid'])) {
560 $runtime = time() - $p['started'];
561 //echo "RUNTIME ({$p['pid']}): $runtime\n";
562 if ($runtime > $this->maxruntime) {
564 proc_terminate($p['proc'], 9);
565 //fclose($p['pipes'][1]);
566 fclose($p['pipes'][0]);
567 fclose($p['pipes'][2]);
568 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
572 $w = DB_DataObject::factory($this->table);
573 $w->get($p['notify_id']);
575 if ($this->log_events) {
576 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
578 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
587 fclose($p['pipes'][0]);
588 fclose($p['pipes'][2]);
589 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
590 //fclose($p['pipes'][1]);
592 proc_close($p['proc']);
596 //if (file_exists('/proc/'.$p['pid'])) {
600 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
602 // at this point we could pop onto the queue the
603 $this->popQueueDomain($p['email']);
607 $this->logecho("POOL SIZE: ". count($pool) );
609 if (count($pool) < $this->max_pool_size) {
616 * see if pool is already trying to deliver to this domain.?
617 * -- if so it get's pushed to the end of the queue.
620 function poolHasDomain($email)
623 $ea = explode('@',$email);
624 $dom = strtolower(array_pop($ea));
625 foreach($this->pool as $p) {
626 $ea = explode('@',$p['email']);
627 $mdom = strtolower(array_pop($ea));
635 function popQueueDomain($email)
637 $ea = explode('@',$email);
638 $dom = strtolower(array_pop($ea));
639 if (empty($this->domain_queue[$dom])) {
642 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
646 function pushQueueDomain($e, $email)
648 if ($this->domain_queue === false) {
649 $this->next_queue[] = $e;
653 $ea = explode('@',$email);
654 $dom = strtolower(array_pop($ea));
655 if (!isset($this->domain_queue[$dom])) {
656 $this->domain_queue[$dom] = array();
658 $this->domain_queue[$dom][] = $e;
660 function remainingDomainQueue()
663 foreach($this->domain_queue as $dom => $ar) {
664 $ret = array_merge($ret, $ar);
666 $this->domain_queue = false;
674 $this->logecho("DONE");
677 function logecho($str)
679 echo date("Y-m-d H:i:s - ") . $str . "\n";