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 time a child is allowed to run - defaut 2 minutes
102 var $maxruntime = 120;
104 var $table = 'core_notify';
105 var $target = 'Core/NotifySend';
106 var $evtype = ''; // any notification...
107 // this script should only handle EMAIL notifications..
111 $ff = HTML_FlexyFramework::get();
113 die("access denied");
115 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
121 function parseArgs(&$opts)
123 if ($opts['debug']) {
124 DB_DataObject::debugLevel($opts['debug']);
128 if (!empty($opts['poolsize'])) {
129 $this->max_pool_size = $opts['poolsize'];
132 if (empty($opts['limit'])) {
133 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
136 if (!empty($opts['old'])) {
137 $opts['list'] = 1; // force listing..
140 $this->force = empty($opts['force']) ? 0 : 1;
142 if (!empty($opts['send-to'])) {
143 $this->send_to = $opts['send-to'];
148 function get($r,$opts=array())
150 $this->parseArgs($opts);
152 //date_default_timezone_set('UTC');
155 $this->generateNotifications();
158 //DB_DataObject::debugLevel(1);
159 $w = DB_DataObject::factory($this->table);
162 if (!empty($opts['old'])) {
163 // show old and new...
165 $w->orderBy('act_when DESC'); // latest first
166 $w->limit($opts['limit']); // we can run
167 $total = min($w->count(), $opts['limit']);
171 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
172 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
174 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
176 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
179 $w->orderBy('act_when ASC'); // oldest first.
180 $total = min($w->count(), $opts['limit']);
181 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
183 $w->limit($opts['limit']); // we can run 1000 ...
186 if (!empty($this->evtype)) {
187 $w->evtype = $this->evtype;
193 $ar = array(); // $w->fetchAll();
195 if (!empty($opts['list'])) {
198 while ($w->fetch()) {
202 $this->logecho("{$w->id} : {$w->person()->email} email : ".
203 $o->toEventString()." ". $w->status() );
208 //echo "BATCH SIZE: ". count($ar) . "\n";
217 $this->logecho("BATCH SIZE: ". (count($ar) + $total) );
220 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
222 if (empty($pushed)) {
231 $p = array_shift($ar);
232 if (!$this->poolfree()) {
233 array_unshift($ar,$p); /// put it back on..
237 $email = $p->person() ? $p->person()->email : $p->to_email;
239 if ($this->poolHasDomain($email) > $this->max_to_domain) {
241 if ($pushed === false) {
242 // we only try once to requeue..
254 $this->run($p->id,$email);
260 // we should have a time limit here...
261 while(count($this->pool)) {
266 foreach($requeue as $p) {
268 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
274 $this->logecho("DONE");
278 function generateNotifications()
280 // this should check each module for 'GenerateNotifications.php' class..
281 //and run it if found..
282 $ff = HTML_FlexyFramework::get();
284 $disabled = explode(',', $ff->disable);
286 $modules = array_reverse($this->modulesList());
288 // move 'project' one to the end...
290 foreach ($modules as $module){
291 if(in_array($module, $disabled)){
294 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
295 if(!file_exists($file)){
300 $class = "Pman_{$module}_GenerateNotifications";
302 if(!method_exists($x, 'generate')){
314 function run($id, $email, $cmdOpts="")
317 static $renice = false;
319 require_once 'System.php';
320 $renice = System::which('renice');
324 $tnx = tempnam(ini_get('session.save_path'),'stdout');
326 $tn = $tnx . '.stdout';
327 $descriptorspec = array(
328 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
329 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
330 2 => array("pipe", "w") // stderr is a file to write to
335 require_once 'System.php';
336 $php = System::which('php');
339 $sn = $_SERVER["SCRIPT_NAME"];
341 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
342 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
346 if (!empty($this->send_to)) {
347 $app .= ' --sent-to='.escapeshellarg($this->send_to);
349 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
353 $this->logecho("call proc_open $cmd");
356 if ($this->max_pool_size === 1) {
362 if (!empty($this->opts['dryrun'])) {
363 $this->logecho("DRY RUN");
367 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
368 $info = proc_get_status($p);
370 if ($this->nice_level !== false) {
371 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
374 $this->pool[] = array(
376 'pid' => $info['pid'],
386 $this->logecho("RUN ({$info['pid']}) $cmd ");
394 foreach($this->pool as $p) {
396 //echo "CHECK PID: " . $p['pid'] . "\n";
397 $info = proc_get_status($p['proc']);
400 // update if necessday.
401 if ($info['pid'] && $p['pid'] != $info['pid']) {
402 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
403 $p['pid'] = $info['pid'];
406 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
408 if ($info['running']) {
410 //if (file_exists('/proc/'.$p['pid'])) {
411 $runtime = time() - $p['started'];
412 //echo "RUNTIME ({$p['pid']}): $runtime\n";
413 if ($runtime > $this->maxruntime) {
415 proc_terminate($p['proc'], 9);
416 //fclose($p['pipes'][1]);
417 fclose($p['pipes'][0]);
418 fclose($p['pipes'][2]);
419 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
422 $w = DB_DataObject::factory($this->table);
423 $w->get($p['notify_id']);
425 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
426 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30 MINUTES'));
436 fclose($p['pipes'][0]);
437 fclose($p['pipes'][2]);
438 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
439 //fclose($p['pipes'][1]);
441 proc_close($p['proc']);
445 //if (file_exists('/proc/'.$p['pid'])) {
449 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
453 $this->logecho("POOL SIZE: ". count($pool) );
455 if (count($pool) < $this->max_pool_size) {
462 * see if pool is already trying to deliver to this domain.?
463 * -- if so it get's pushed to the end of the queue.
466 function poolHasDomain($email)
469 $ea = explode('@',$email);
470 $dom = strtolower(array_pop($ea));
471 foreach($this->pool as $p) {
472 $ea = explode('@',$p['email']);
473 $mdom = strtolower(array_pop($ea));
484 $this->logecho("DONE");
487 function logecho($str)
489 echo date("Y-m-d H:i:s - ") . $str . "\n";