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...',
60 'desc' => 'Generate notifications for a table, eg. cash_invoice',
67 'desc' => 'Limit search for no. to send to ',
74 'desc' => 'Dry run - do not send.',
81 'desc' => 'Pool size',
89 * @var $nice_level Unix 'nice' level to stop it jamming server up.
91 var $nice_level = false;
93 * @var $max_pool_size maximum runners to start at once.
95 var $max_pool_size = 10;
97 * @var $max_to_domain maximum connections to make to a single domain
99 var $max_to_domain = 10;
102 * @var $maxruntime - maximum time a child is allowed to run - defaut 2 minutes
104 var $maxruntime = 120;
106 var $table = 'core_notify';
107 var $target = 'Core/NotifySend';
108 var $evtype = ''; // any notification...
109 // this script should only handle EMAIL notifications..
113 $ff = HTML_FlexyFramework::get();
115 die("access denied");
117 HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
123 function parseArgs(&$opts)
125 if ($opts['debug']) {
126 DB_DataObject::debugLevel($opts['debug']);
130 if (!empty($opts['poolsize'])) {
131 $this->max_pool_size = $opts['poolsize'];
134 if (empty($opts['limit'])) {
135 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
138 if (!empty($opts['old'])) {
139 $opts['list'] = 1; // force listing..
142 $this->force = empty($opts['force']) ? 0 : 1;
144 if (!empty($opts['send-to'])) {
145 $this->send_to = $opts['send-to'];
150 function get($r,$opts)
152 $this->parseArgs($opts);
154 //date_default_timezone_set('UTC');
159 $w = DB_DataObject::factory('core_notify_recur');
160 if (is_a($w, 'DB_DataObject')) {
161 $w->generateNotifications();
163 if (!empty($opts['generate'])) {
164 $w = DB_DataObject::factory($opts['generate']);
165 if (is_a($w, 'DB_DataObject')) {
166 $w->generateNotifications();
173 //DB_DataObject::debugLevel(1);
174 $w = DB_DataObject::factory($this->table);
177 if (!empty($opts['old'])) {
178 // show old and new...
180 $w->orderBy('act_when DESC'); // latest first
181 $w->limit($opts['limit']); // we can run
182 $total = min($w->count(), $opts['limit']);
186 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
187 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
189 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
191 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
194 $w->orderBy('act_when ASC'); // oldest first.
195 $total = min($w->count(), $opts['limit']);
196 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
198 $w->limit($opts['limit']); // we can run 1000 ...
201 if (!empty($this->evtype)) {
202 $w->evtype = $this->evtype;
208 $ar = array(); // $w->fetchAll();
210 if (!empty($opts['list'])) {
213 while ($w->fetch()) {
217 $this->logecho("{$w->id} : {$w->person()->email} email : ".
218 $o->toEventString()." ". $w->status() );
223 //echo "BATCH SIZE: ". count($ar) . "\n";
232 $this->logecho("BATCH SIZE: ". (count($ar) + $total) );
235 $this->logecho("COMPLETED MAIN QUEUE - running delated");
237 if (empty($pushed)) {
246 $p = array_shift($ar);
247 if (!$this->poolfree()) {
248 array_unshift($ar,$p); /// put it back on..
252 if ($this->poolHasDomain($p->person()->email) > $this->max_to_domain) {
254 if ($pushed === false) {
255 // we only try once to requeue..
267 $this->run($p->id,$p->person()->email);
273 // we should have a time limit here...
274 while(count($this->pool)) {
279 foreach($requeue as $p) {
281 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
287 $this->logecho("DONE");
291 function run($id, $email, $cmdOpts="")
294 static $renice = false;
296 require_once 'System.php';
297 $renice = System::which('renice');
301 $tnx = tempnam(ini_get('session.save_path'),'stdout');
303 $tn = $tnx . '.stdout';
304 $descriptorspec = array(
305 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
306 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
307 2 => array("pipe", "w") // stderr is a file to write to
312 require_once 'System.php';
313 $php = System::which('php');
316 $sn = $_SERVER["SCRIPT_NAME"];
318 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
319 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
323 if (!empty($this->send_to)) {
324 $app .= ' --sent-to='.escapeshellarg($this->send_to);
326 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
330 $this->logecho("call proc_open $cmd");
333 if ($this->max_pool_size === 1) {
339 if (!empty($this->opts['dryrun'])) {
340 $this->logecho("DRY RUN");
344 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
345 $info = proc_get_status($p);
347 if ($this->nice_level !== false) {
348 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
351 $this->pool[] = array(
353 'pid' => $info['pid'],
363 $this->logecho("RUN ({$info['pid']}) $cmd ");
371 foreach($this->pool as $p) {
373 //echo "CHECK PID: " . $p['pid'] . "\n";
374 $info = proc_get_status($p['proc']);
377 // update if necessday.
378 if ($info['pid'] && $p['pid'] != $info['pid']) {
379 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
380 $p['pid'] = $info['pid'];
383 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
385 if ($info['running']) {
387 //if (file_exists('/proc/'.$p['pid'])) {
388 $runtime = time() - $p['started'];
389 //echo "RUNTIME ({$p['pid']}): $runtime\n";
390 if ($runtime > $this->maxruntime) {
392 proc_terminate($p['proc'], 9);
393 //fclose($p['pipes'][1]);
394 fclose($p['pipes'][0]);
395 fclose($p['pipes'][2]);
396 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
399 $w = DB_DataObject::factory($this->table);
400 $w->get($p['notify_id']);
402 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
403 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30 MINUTES'));
413 fclose($p['pipes'][0]);
414 fclose($p['pipes'][2]);
415 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
416 //fclose($p['pipes'][1]);
418 proc_close($p['proc']);
422 //if (file_exists('/proc/'.$p['pid'])) {
426 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
430 $this->logecho("POOL SIZE: ". count($pool) );
432 if (count($pool) < $this->max_pool_size) {
439 * see if pool is already trying to deliver to this domain.?
440 * -- if so it get's pushed to the end of the queue.
443 function poolHasDomain($email)
446 $dom = strtolower(array_pop(explode('@',$email)));
447 foreach($this->pool as $p) {
448 $mdom = strtolower(array_pop(explode('@',$p['email'])));
459 $this->logecho("DONE");
462 function logecho($str)
464 echo date("Y-m-d H:i:s - ") . $str . "\n";