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'];
168 function get($r,$opts=array())
170 $this->parseArgs($opts);
172 //date_default_timezone_set('UTC');
175 $this->generateNotifications();
177 $this->assignQueues();
179 //DB_DataObject::debugLevel(1);
180 $w = DB_DataObject::factory($this->table);
183 if (!empty($opts['old'])) {
184 // show old and new...
186 $w->orderBy('act_when DESC'); // latest first
187 $w->limit($opts['limit']); // we can run
188 $total = min($w->count(), $opts['limit']);
192 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
193 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
195 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
197 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
200 $w->orderBy('act_when ASC'); // oldest first.
201 $total = min($w->count(), $opts['limit']);
202 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
204 $w->limit($opts['limit']); // we can run 1000 ...
207 if (!empty($this->evtype)) {
208 $w->evtype = $this->evtype;
211 $ff = HTML_FlexyFramework::get();
212 if (!empty($ff->Core_Notify['servers'])) {
213 if (!isset($ff->Core_Notify['servers'][gethostname()])) {
214 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
216 $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
222 $this->addFilter($w);
227 $ar = array(); // $w->fetchAll();
229 if (!empty($opts['list'])) {
232 while ($w->fetch()) {
236 $this->logecho("{$w->id} : {$w->person()->email} email : ".
237 $o->toEventString()." ". $w->status() );
242 //echo "BATCH SIZE: ". count($ar) . "\n";
246 // only add if we don't have any queued up..
247 if (empty($ar) && $w->fetch()) {
252 $this->logecho("BATCH SIZE: ". (count($ar) + $total) );
255 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
257 if (empty($pushed)) {
266 $p = array_shift($ar);
267 if (!$this->poolfree()) {
268 array_unshift($ar,$p); /// put it back on..
272 $email = $p->person() ? $p->person()->email : $p->to_email;
274 if ($this->poolHasDomain($email) > $this->max_to_domain) {
276 if ($pushed === false) {
277 // we only try once to requeue..
289 $this->run($p->id,$email);
295 // we should have a time limit here...
296 while(count($this->pool)) {
301 foreach($requeue as $p) {
303 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
309 $this->logecho("DONE");
316 function generateNotifications()
318 // this should check each module for 'GenerateNotifications.php' class..
319 //and run it if found..
320 $ff = HTML_FlexyFramework::get();
322 $disabled = explode(',', $ff->disable);
324 $modules = array_reverse($this->modulesList());
326 // move 'project' one to the end...
328 foreach ($modules as $module){
329 if(in_array($module, $disabled)){
332 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
333 if(!file_exists($file)){
338 $class = "Pman_{$module}_GenerateNotifications";
340 if(!method_exists($x, 'generate')){
350 function assignQueues()
352 $ff = HTML_FlexyFramework::get();
354 if (empty($ff->Core_Notify['servers'])) {
358 $num_servers = count(array_keys($ff->Core_Notify['servers']));
359 $p = DB_DataObject::factory($this->table);
360 // 6 seconds on this machne...
365 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END +1) % {$num_servers})
383 function run($id, $email='', $cmdOpts="")
386 static $renice = false;
388 require_once 'System.php';
389 $renice = System::which('renice');
395 $tn = $this->tempName('stdout', true);
396 $descriptorspec = array(
397 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
398 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
399 2 => array("pipe", "w") // stderr is a file to write to
404 require_once 'System.php';
405 $php = System::which('php');
408 $sn = $_SERVER["SCRIPT_NAME"];
410 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
411 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
415 if (!empty($this->send_to)) {
416 $app .= ' --sent-to='.escapeshellarg($this->send_to);
418 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
422 $this->logecho("call proc_open $cmd");
425 if ($this->max_pool_size === 1) {
431 if (!empty($this->opts['dryrun'])) {
432 $this->logecho("DRY RUN");
436 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
437 $info = proc_get_status($p);
439 if ($this->nice_level !== false) {
440 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
443 $this->pool[] = array(
445 'pid' => $info['pid'],
455 $this->logecho("RUN ({$info['pid']}) $cmd ");
463 foreach($this->pool as $p) {
465 //echo "CHECK PID: " . $p['pid'] . "\n";
466 $info = proc_get_status($p['proc']);
469 // update if necessday.
470 if ($info['pid'] && $p['pid'] != $info['pid']) {
471 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
472 $p['pid'] = $info['pid'];
475 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
477 if ($info['running']) {
479 //if (file_exists('/proc/'.$p['pid'])) {
480 $runtime = time() - $p['started'];
481 //echo "RUNTIME ({$p['pid']}): $runtime\n";
482 if ($runtime > $this->maxruntime) {
484 proc_terminate($p['proc'], 9);
485 //fclose($p['pipes'][1]);
486 fclose($p['pipes'][0]);
487 fclose($p['pipes'][2]);
488 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
492 $w = DB_DataObject::factory($this->table);
493 $w->get($p['notify_id']);
495 if ($this->log_events) {
496 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
498 $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
507 fclose($p['pipes'][0]);
508 fclose($p['pipes'][2]);
509 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
510 //fclose($p['pipes'][1]);
512 proc_close($p['proc']);
516 //if (file_exists('/proc/'.$p['pid'])) {
520 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
524 $this->logecho("POOL SIZE: ". count($pool) );
526 if (count($pool) < $this->max_pool_size) {
533 * see if pool is already trying to deliver to this domain.?
534 * -- if so it get's pushed to the end of the queue.
537 function poolHasDomain($email)
540 $ea = explode('@',$email);
541 $dom = strtolower(array_pop($ea));
542 foreach($this->pool as $p) {
543 $ea = explode('@',$p['email']);
544 $mdom = strtolower(array_pop($ea));
555 $this->logecho("DONE");
558 function logecho($str)
560 echo date("Y-m-d H:i:s - ") . $str . "\n";