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);
176 if (!empty($opts['old'])) {
177 // show old and new...
179 $w->orderBy('act_when DESC'); // latest first
180 $w->limit($opts['limit']); // we can run
185 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
186 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
188 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
190 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
193 $w->orderBy('act_when ASC'); // oldest first.
195 $this->logecho("QUEUE is {$w->count()}");
197 $w->limit($opts['limit']); // we can run 1000 ...
200 if (!empty($this->evtype)) {
201 $w->evtype = $this->evtype;
207 $ar = $w->fetchAll();
209 if (!empty($opts['list'])) {
211 die("Nothing in Queue\n");
217 $this->logecho("$w->id : $w->person_id_email email : ".
218 $o->toEventString()." ". $w->status() );
223 //echo "BATCH SIZE: ". count($ar) . "\n";
229 $this->logecho("BATCH SIZE: ". count($ar) );
232 $this->logecho("COMPLETED MAIN QUEUE - running delated");
234 if (empty($pushed)) {
243 $p = array_shift($ar);
244 if (!$this->poolfree()) {
245 array_unshift($ar,$p); /// put it back on..
249 if ($this->poolHasDomain($p->person_id_email) > $this->max_to_domain) {
251 if ($pushed === false) {
252 // we only try once to requeue..
264 $this->run($p->id,$p->person_id_email);
270 // we should have a time limit here...
271 while(count($this->pool)) {
276 foreach($requeue as $p) {
278 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
284 $this->logecho("DONE");
288 function run($id, $email, $cmdOpts="")
291 static $renice = false;
293 require_once 'System.php';
294 $renice = System::which('renice');
298 $tnx = tempnam(ini_get('session.save_path'),'stdout');
300 $tn = $tnx . '.stdout';
301 $descriptorspec = array(
302 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
303 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
304 2 => array("pipe", "w") // stderr is a file to write to
309 require_once 'System.php';
310 $php = System::which('php');
313 $sn = $_SERVER["SCRIPT_NAME"];
315 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
316 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
320 if (!empty($this->send_to)) {
321 $app .= ' --sent-to='.escapeshellarg($this->send_to);
323 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
327 $this->logecho("call proc_open $cmd");
330 if ($this->max_pool_size === 1) {
336 if (!empty($this->opts['dryrun'])) {
337 $this->logecho("DRY RUN");
341 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
342 $info = proc_get_status($p);
344 if ($this->nice_level !== false) {
345 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
348 $this->pool[] = array(
350 'pid' => $info['pid'],
359 $this->logecho("RUN ({$info['pid']}) $cmd ");
367 foreach($this->pool as $p) {
369 //echo "CHECK PID: " . $p['pid'] . "\n";
370 $info = proc_get_status($p['proc']);
373 // update if necessday.
374 if ($info['pid'] && $p['pid'] != $info['pid']) {
375 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
376 $p['pid'] = $info['pid'];
379 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
381 if ($info['running']) {
383 //if (file_exists('/proc/'.$p['pid'])) {
384 $runtime = time() - $p['started'];
385 //echo "RUNTIME ({$p['pid']}): $runtime\n";
386 if ($runtime > $this->maxruntime) {
388 proc_terminate($p['proc'], 9);
389 //fclose($p['pipes'][1]);
390 fclose($p['pipes'][0]);
391 fclose($p['pipes'][2]);
392 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
401 fclose($p['pipes'][0]);
402 fclose($p['pipes'][2]);
403 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
404 //fclose($p['pipes'][1]);
406 proc_close($p['proc']);
410 //if (file_exists('/proc/'.$p['pid'])) {
414 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
418 $this->logecho("POOL SIZE: ". count($pool) );
420 if (count($pool) < $this->max_pool_size) {
427 * see if pool is already trying to deliver to this domain.?
428 * -- if so it get's pushed to the end of the queue.
431 function poolHasDomain($email)
434 $dom = strtolower(array_pop(explode('@',$email)));
435 foreach($this->pool as $p) {
436 $mdom = strtolower(array_pop(explode('@',$p['email'])));
447 $this->logecho("DONE");
450 function logecho($str)
452 echo date("Y-m-d H:i:s - ") . $str . "\n";