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');
160 if (!empty($opts['generate'])) {
161 $w = DB_DataObject::factory($opts['generate']);
162 if (is_a($w, 'DB_DataObject')) {
163 $w->generateNotifications();
170 $w = DB_DataObject::factory('core_notify_recur');
171 if (is_a($w, 'DB_DataObject')) {
172 $w->generateNotifications();
175 //DB_DataObject::debugLevel(1);
176 $w = DB_DataObject::factory($this->table);
179 if (!empty($opts['old'])) {
180 // show old and new...
182 $w->orderBy('act_when DESC'); // latest first
183 $w->limit($opts['limit']); // we can run
184 $total = min($w->count(), $opts['limit']);
188 //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
189 $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
191 $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
193 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
196 $w->orderBy('act_when ASC'); // oldest first.
197 $total = min($w->count(), $opts['limit']);
198 $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
200 $w->limit($opts['limit']); // we can run 1000 ...
203 if (!empty($this->evtype)) {
204 $w->evtype = $this->evtype;
210 $ar = array(); // $w->fetchAll();
212 if (!empty($opts['list'])) {
215 while ($w->fetch()) {
219 $this->logecho("{$w->id} : {$w->person()->email} email : ".
220 $o->toEventString()." ". $w->status() );
225 //echo "BATCH SIZE: ". count($ar) . "\n";
234 $this->logecho("BATCH SIZE: ". (count($ar) + $total) );
237 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
239 if (empty($pushed)) {
248 $p = array_shift($ar);
249 if (!$this->poolfree()) {
250 array_unshift($ar,$p); /// put it back on..
254 $email = $p->person() ? $p->person()->email : $p->to_email;
256 if ($this->poolHasDomain($email) > $this->max_to_domain) {
258 if ($pushed === false) {
259 // we only try once to requeue..
271 $this->run($p->id,$email);
277 // we should have a time limit here...
278 while(count($this->pool)) {
283 foreach($requeue as $p) {
285 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
291 $this->logecho("DONE");
295 function generateNotifications()
297 // this should check each module for 'GenerateNotifications.php' class..
298 //and run it if found..
301 $modules = array_reverse($this->modulesList());
303 // move 'project' one to the end...
305 foreach ($modules as $module){
306 if(in_array($module, $this->disabled)){
309 $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
310 if(!file_exists($file)){
315 $class = "Pman_{$module}_GenerateNotifications";
317 if(!method_exists($x, 'generate')){
329 function run($id, $email, $cmdOpts="")
332 static $renice = false;
334 require_once 'System.php';
335 $renice = System::which('renice');
339 $tnx = tempnam(ini_get('session.save_path'),'stdout');
341 $tn = $tnx . '.stdout';
342 $descriptorspec = array(
343 0 => array("pipe", 'r'), // stdin is a pipe that the child will read from
344 1 => array("file", $tn, 'w'), // stdout is a pipe that the child will write to
345 2 => array("pipe", "w") // stderr is a file to write to
350 require_once 'System.php';
351 $php = System::which('php');
354 $sn = $_SERVER["SCRIPT_NAME"];
356 $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
357 $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . ' ' . $this->target . '/'. $id;
361 if (!empty($this->send_to)) {
362 $app .= ' --sent-to='.escapeshellarg($this->send_to);
364 $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
368 $this->logecho("call proc_open $cmd");
371 if ($this->max_pool_size === 1) {
377 if (!empty($this->opts['dryrun'])) {
378 $this->logecho("DRY RUN");
382 $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
383 $info = proc_get_status($p);
385 if ($this->nice_level !== false) {
386 $rcmd = "$renice {$this->nice_level} {$info['pid']}";
389 $this->pool[] = array(
391 'pid' => $info['pid'],
401 $this->logecho("RUN ({$info['pid']}) $cmd ");
409 foreach($this->pool as $p) {
411 //echo "CHECK PID: " . $p['pid'] . "\n";
412 $info = proc_get_status($p['proc']);
415 // update if necessday.
416 if ($info['pid'] && $p['pid'] != $info['pid']) {
417 $this->logecho("CHANING PID FROM " . $p['pid'] . " TO ". $info['pid']);
418 $p['pid'] = $info['pid'];
421 //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
423 if ($info['running']) {
425 //if (file_exists('/proc/'.$p['pid'])) {
426 $runtime = time() - $p['started'];
427 //echo "RUNTIME ({$p['pid']}): $runtime\n";
428 if ($runtime > $this->maxruntime) {
430 proc_terminate($p['proc'], 9);
431 //fclose($p['pipes'][1]);
432 fclose($p['pipes'][0]);
433 fclose($p['pipes'][2]);
434 $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
437 $w = DB_DataObject::factory($this->table);
438 $w->get($p['notify_id']);
440 $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
441 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30 MINUTES'));
451 fclose($p['pipes'][0]);
452 fclose($p['pipes'][2]);
453 //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
454 //fclose($p['pipes'][1]);
456 proc_close($p['proc']);
460 //if (file_exists('/proc/'.$p['pid'])) {
464 $this->logecho("ENDED: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) );
468 $this->logecho("POOL SIZE: ". count($pool) );
470 if (count($pool) < $this->max_pool_size) {
477 * see if pool is already trying to deliver to this domain.?
478 * -- if so it get's pushed to the end of the queue.
481 function poolHasDomain($email)
484 $dom = strtolower(array_pop(explode('@',$email)));
485 foreach($this->pool as $p) {
486 $mdom = strtolower(array_pop(explode('@',$p['email'])));
497 $this->logecho("DONE");
500 function logecho($str)
502 echo date("Y-m-d H:i:s - ") . $str . "\n";