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..',
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 $sig = $_SERVER["SCRIPT_NAME"] .'|'. __FILE__;
119 HTML_FlexyFramework::ensureSingle($sig, $this);
126 function get($r,$opts)
128 if ($opts['debug']) {
129 DB_DataObject::debugLevel($opts['debug']);
133 if (!empty($opts['poolsize'])) {
134 $this->max_pool_size = $opts['poolsize'];
137 if (empty($opts['limit'])) {
138 $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
140 //date_default_timezone_set('UTC');
142 $showold = !empty($opts['old']);
143 if (!empty($opts['old'])) {
144 $opts['list'] = 1; // force listing..
147 $this->force = empty($opts['force']) ? 0 : 1;
149 if (!empty($opts['send-to'])) {
150 $this->send_to = $opts['send-to'];
154 $w = DB_DataObject::factory('core_notify_recur');
155 if (is_a($w, 'DB_DataObject')) {
156 $w->generateNotifications();
158 if (!empty($opts['generate'])) {
159 $w = DB_DataObject::factory($opts['generate']);
160 if (is_a($w, 'DB_DataObject')) {
161 $w->generateNotifications();
168 //DB_DataObject::debugLevel(1);
169 $w = DB_DataObject::factory($this->table);
176 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
177 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
179 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
181 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
184 $w->orderBy('act_when ASC'); // oldest first.
186 $this->logecho("QUEUE is {$w->count()}");
188 $w->limit($opts['limit']); // we can run 1000 ...
190 $w->orderBy('act_when DESC'); // latest first
191 $w->limit($opts['limit']); // we can run 1000 ...
193 if (!empty($this->evtype)) {
194 $w->evtype = $this->evtype;
200 $ar = $w->fetchAll();
202 if (!empty($opts['list'])) {
204 die("Nothing in Queue\n");
210 $this->logecho("$w->id : $w->person_id_email email : ".
211 $o->toEventString()." ". $w->status() );
216 //echo "BATCH SIZE: ". count($ar) . "\n";
222 $this->logecho("BATCH SIZE: ". count($ar) );
225 $this->logecho("COMPLETED MAIN QUEUE - running delated");
227 if (empty($pushed)) {
236 $p = array_shift($ar);
237 if (!$this->poolfree()) {
238 array_unshift($ar,$p); /// put it back on..
242 if ($this->poolHasDomain($p->person_id_email) > $this->max_to_domain) {
244 if ($pushed === false) {
245 // we only try once to requeue..
257 $this->run($p->id,$p->person_id_email);
263 // we should have a time limit here...
264 while(count($this->pool)) {
269 foreach($requeue as $p) {
271 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
277 $this->logecho("DONE");
281 function run($id, $email, $cmdOpts="")
284 static $renice = false;
286 require_once 'System.php';
287 $renice = System::which('renice');
291 $tnx = tempnam(ini_get('session.save_path'),'stdout');
293 $tn = $tnx . '.stdout';
294 $descriptorspec = array(
295 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
296 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
297 2 => array("pipe", "w") // stderr is a file to write to
302 require_once 'System.php';
303 $php = System::which('php');
306 $sn = $_SERVER["SCRIPT_NAME"];
308 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
309 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
313 if (!empty($this->send_to)) {
314 $app .= ' --sent-to='.escapeshellarg($this->send_to);
316 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
320 $this->logecho("call proc_open $cmd");
323 if ($this->max_pool_size === 1) {
329 if (!empty($this->opts['dryrun'])) {
330 $this->logecho("DRY RUN");
334 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
335 $info = proc_get_status($p);
337 if ($this->nice_level !== false) {
338 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
341 $this->pool[] = array(
343 'pid' => $info['pid'],
352 $this->logecho("RUN ({$info['pid']}) $cmd ");
360 foreach($this->pool as $p) {
362 //echo "CHECK PID: " . $p['pid'] . "\n";
363 $info = proc_get_status($p['proc']);
366 // update if necessday.
367 if ($info['pid'] && $p['pid'] != $info['pid']) {
368 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
369 $p['pid'] = $info['pid'];
372 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
374 if ($info['running']) {
376 //if (file_exists('/proc/'.$p['pid'])) {
377 $runtime = time() - $p['started'];
378 //echo "RUNTIME ({$p['pid']}): $runtime\n";
379 if ($runtime > $this->maxruntime) {
381 proc_terminate($p['proc'], 9);
382 //fclose($p['pipes'][1]);
383 fclose($p['pipes'][0]);
384 fclose($p['pipes'][2]);
385 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
394 fclose($p['pipes'][0]);
395 fclose($p['pipes'][2]);
396 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
397 //fclose($p['pipes'][1]);
399 proc_close($p['proc']);
403 //if (file_exists('/proc/'.$p['pid'])) {
407 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
411 $this->logecho("POOL SIZE: ". count($pool) );
413 if (count($pool) < $this->max_pool_size) {
420 * see if pool is already trying to deliver to this domain.?
421 * -- if so it get's pushed to the end of the queue.
424 function poolHasDomain($email)
427 $dom = strtolower(array_pop(explode('@',$email)));
428 foreach($this->pool as $p) {
429 $mdom = strtolower(array_pop(explode('@',$p['email'])));
440 $this->logecho("DONE");
443 function logecho($str)
445 echo date("Y-m-d H:i:s - ") . $str . "\n";