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';
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);
198 if (!empty($this->evtype)) {
199 $w->evtype = $this->evtype;
204 if (!empty($opts['old'])) {
205 // show old and new...
207 $w->orderBy('act_when DESC'); // latest first
208 $w->limit($opts['limit']); // we can run
209 $total = min($w->count(), $opts['limit']);
213 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
214 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
216 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
218 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
221 $w->orderBy('act_when ASC'); // oldest first.
222 $total = min($w->count(), $opts['limit']);
223 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
225 $w->limit($opts['limit']); // we can run 1000 ...
237 $this->logecho("Nothing In Queue - DONE");
242 if (!empty($opts['list'])) {
245 while ($w->fetch()) {
249 $this->logecho("{$w->id} : {$w->person()->email} email : ".
250 $o->toEventString()." ". $w->status() );
255 //echo "BATCH SIZE: ". count($ar) . "\n";
259 // only add if we don't have any queued up..
260 if (empty($this->queue) && $w->fetch()) {
261 $this->queue[] = clone($w);
265 $this->logecho("BATCH SIZE: Queue=". count($this->queue) . " TOTAL = " . $total );
267 if (empty($this->queue)) {
268 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
269 if ($this->domain_queue !== false) {
270 $this->queue = $this->remainingDomainQueue();
274 break; // nothing more in queue.. and no remaining one
278 $p = array_shift($this->queue);
279 if (!$this->poolfree()) {
280 array_unshift($this->queue,$p); /// put it back on..
284 // not sure what happesn if person email and to_email is empty!!?
285 $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
287 $black = $this->server->isBlacklisted($email);
288 if ($black !== false) {
290 if (false === $this->server->updateNotifyToNextServer($p)) {
291 $p->updateState("????");
298 if ($this->poolHasDomain($email) > $this->max_to_domain) {
300 // push it to a 'domain specific queue'
301 $this->logecho("REQUEING - maxed out that domain - {$email}");
302 $this->pushQueueDomain($p, $email);
309 $this->run($p->id,$email);
314 $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
315 if (!empty($this->next_queue)) {
317 foreach($this->next_queue as $p) {
318 if (false === $this->server->updateNotifyToNextServer($p)) {
319 $p->updateState("????");
325 $this->logecho("QUEUE COMPLETE - waiting for pool to end");
326 // we should have a time limit here...
327 while(count($this->pool)) {
335 $this->logecho("DONE");
342 // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
346 function generateNotifications()
348 // this should check each module for 'GenerateNotifications.php' class..
349 //and run it if found..
350 $ff = HTML_FlexyFramework::get();
352 $disabled = explode(',', $ff->disable);
354 $modules = array_reverse($this->modulesList());
356 // move 'project' one to the end...
358 foreach ($modules as $module){
359 if(in_array($module, $disabled)){
362 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
363 if(!file_exists($file)){
368 $class = "Pman_{$module}_GenerateNotifications";
370 if(!method_exists($x, 'generate')){
380 function assignQueues()
383 DB_DataObject::Factory('core_notify_server')->assignQueues($this);
388 function run($id, $email='', $cmdOpts="")
391 static $renice = false;
393 require_once 'System.php';
394 $renice = System::which('renice');
400 $tn = $this->tempName('stdout', true);
401 $descriptorspec = array(
402 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
403 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
404 2 => array("pipe", "w") // stderr is a file to write to
409 require_once 'System.php';
410 $php = System::which('php');
413 $sn = $_SERVER["SCRIPT_NAME"];
415 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
416 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
420 if (!empty($this->send_to)) {
421 $app .= ' --sent-to='.escapeshellarg($this->send_to);
423 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
427 //$this->logecho("call proc_open $cmd");
430 if ($this->max_pool_size === 1) {
431 $this->logecho("call passthru [{$email}] $cmd");
437 if (!empty($this->opts['dryrun'])) {
438 $this->logecho("DRY RUN");
442 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
443 $info = proc_get_status($p);
445 if ($this->nice_level !== false) {
446 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
449 $this->pool[] = array(
451 'pid' => $info['pid'],
461 $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
469 foreach($this->pool as $p) {
471 //echo "CHECK PID: " . $p['pid'] . "\n";
472 $info = proc_get_status($p['proc']);
475 // update if necessday.
476 if ($info['pid'] && $p['pid'] != $info['pid']) {
477 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
478 $p['pid'] = $info['pid'];
481 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
483 if ($info['running']) {
485 //if (file_exists('/proc/'.$p['pid'])) {
486 $runtime = time() - $p['started'];
487 //echo "RUNTIME ({$p['pid']}): $runtime\n";
488 if ($runtime > $this->maxruntime) {
490 proc_terminate($p['proc'], 9);
491 //fclose($p['pipes'][1]);
492 fclose($p['pipes'][0]);
493 fclose($p['pipes'][2]);
494 $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
498 $w = DB_DataObject::factory($this->table);
499 $w->get($p['notify_id']);
501 if ($this->log_events) {
502 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
504 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
513 fclose($p['pipes'][0]);
514 fclose($p['pipes'][2]);
515 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
516 //fclose($p['pipes'][1]);
518 proc_close($p['proc']);
522 //if (file_exists('/proc/'.$p['pid'])) {
526 $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) );
528 // at this point we could pop onto the queue the
529 $this->popQueueDomain($p['email']);
533 $this->logecho("POOL SIZE: ". count($pool) );
535 if (count($pool) < $this->max_pool_size) {
542 * see if pool is already trying to deliver to this domain.?
543 * -- if so it get's pushed to the end of the queue.
546 function poolHasDomain($email)
549 $ea = explode('@',$email);
550 $dom = strtolower(array_pop($ea));
551 foreach($this->pool as $p) {
552 $ea = explode('@',$p['email']);
553 $mdom = strtolower(array_pop($ea));
561 function popQueueDomain($email)
563 $ea = explode('@',$email);
564 $dom = strtolower(array_pop($ea));
565 if (empty($this->domain_queue[$dom])) {
568 array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
572 function pushQueueDomain($e, $email)
574 if ($this->domain_queue === false) {
575 $this->next_queue[] = $e;
579 $ea = explode('@',$email);
580 $dom = strtolower(array_pop($ea));
581 if (!isset($this->domain_queue[$dom])) {
582 $this->domain_queue[$dom] = array();
584 $this->domain_queue[$dom][] = $e;
586 function remainingDomainQueue()
589 foreach($this->domain_queue as $dom => $ar) {
590 $ret = array_merge($ret, $ar);
592 $this->domain_queue = false;
600 $this->logecho("DONE");
603 function logecho($str)
605 echo date("Y-m-d H:i:s - ") . $str . "\n";