Notify.php
[Pman.Core] / Notify.php
1 <?php
2 require_once 'Pman.php';
3
4 /**
5  * notification script runner
6  *
7  * This does not actualy send stuf out, it only starts the NotifySend/{id}
8  * which does the actuall notifcations.
9  *
10  * It manages a pool of notifiers.
11  * 
12  * 
13  */
14
15
16 class Pman_Core_Notify extends Pman
17 {
18     
19     static $cli_desc = "Runs the notification queue (usually from cron)
20                         Normally used to sends out emails to anyone in the notification list.
21     
22                         /etc/cron.d/pman-core-notify
23                         * *  * * *     www-data     /usr/bin/php /home/gitlive/web.mtrack/admin.php  Core/Notify > /dev/null
24     
25 ";
26     
27     static $cli_opts = array(
28         'debug' => array(
29             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
30             'default' => 0,
31             'short' => 'v',
32             'min' => 1,
33             'max' => 1,
34             
35         ),
36         'list' => array(
37             'desc' => 'List message to send, do not send them..',
38             'default' => 0,
39             'short' => 'l',
40             'min' => 0,
41             'max' => 0,
42             
43         ),
44         'old' => array(
45             'desc' => 'Show old messages.. (and new messages...)',
46             'default' => 0,
47             'short' => 'o',
48             'min' => 0,
49             'max' => 0,
50             
51         ),
52         'force' => array(
53             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
54             'default' => 0,
55             'short' => 'f',
56             'min' => 0,
57             'max' => 0,
58         ),
59        /* removed - use GenerateNotifcations.php hooked classes
60          'generate' =>  'Generate notifications for a table, eg. cash_invoice',
61             
62         ),
63         */
64          'limit' => array(
65             'desc' => 'Limit search for no. to send to ',
66             'default' => 1000,
67             'short' => 'L',
68             'min' => 0,
69             'max' => 999,
70         ),
71         'dryrun' => array(
72             'desc' => 'Dry run - do not send.',
73             'default' => 0,
74             'short' => 'D',
75             'min' => 0,
76             'max' => 0,
77         ),
78         'poolsize' => array(
79             'desc' => 'Pool size',
80             'default' => 10,
81             'short' => 'P',
82             'min' => 0,
83             'max' => 100,
84         ),
85     );
86     /**
87      * @var $nice_level Unix 'nice' level to stop it jamming server up.
88      */
89     var $nice_level = false;
90     /**
91      * @var $max_pool_size maximum runners to start at once.
92      */
93     var $max_pool_size = 10;
94     /**
95      * @var $max_to_domain maximum connections to make to a single domain
96      */
97     var $max_to_domain = 10;
98     
99     /**
100      * @var $maxruntime - maximum time a child is allowed to run - defaut 2 minutes
101      */
102     var $maxruntime = 120;
103     
104     var $table = 'core_notify';
105     var $target = 'Core/NotifySend';
106     var $evtype = ''; // any notification...
107                     // this script should only handle EMAIL notifications..
108     var $force = false;
109     function getAuth()
110     {
111         $ff = HTML_FlexyFramework::get();
112         if (!$ff->cli) {
113             die("access denied");
114         }
115         HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
116         return true;
117     }
118     
119     var $pool = array();
120     
121     function parseArgs(&$opts)
122     {
123         if ($opts['debug']) {
124             DB_DataObject::debugLevel($opts['debug']);
125             print_r($opts);
126         }
127         $this->opts = $opts;
128         if (!empty($opts['poolsize'])) {
129             $this->max_pool_size = $opts['poolsize'];
130         }
131         
132         if (empty($opts['limit'])) {
133             $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
134         }
135         
136         if (!empty($opts['old'])) {
137             $opts['list'] = 1; // force listing..
138         }
139         
140         $this->force = empty($opts['force']) ? 0 : 1;
141      
142         if (!empty($opts['send-to'])) {
143             $this->send_to = $opts['send-to'];
144         }
145     }
146     
147     
148     function get($r,$opts)    
149     {
150         $this->parseArgs($opts); 
151          
152         //date_default_timezone_set('UTC');
153         
154         
155         $this->generateNotifications();
156         
157          
158         //DB_DataObject::debugLevel(1);
159         $w = DB_DataObject::factory($this->table);
160         $total = 0;
161         
162         if (!empty($opts['old'])) {
163             // show old and new...
164             
165             $w->orderBy('act_when DESC'); // latest first
166             $w->limit($opts['limit']); // we can run 
167             $total = min($w->count(), $opts['limit']);
168         } else {   
169             // standard
170             
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..
173             
174             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
175             if (!$this->force) {
176                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
177             }
178     
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']));
182             
183             $w->limit($opts['limit']); // we can run 1000 ...
184         }
185         
186         if (!empty($this->evtype)) {
187             $w->evtype = $this->evtype;
188         }
189         
190         $w->autoJoin();
191         $w->find();
192         
193         $ar = array(); // $w->fetchAll();
194         
195         if (!empty($opts['list'])) {
196             
197             
198             while ($w->fetch()) { 
199                 $o = $w->object();
200                 
201                 
202                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
203                         $o->toEventString()."    ". $w->status()  );
204             }
205             exit;
206         }
207         
208         //echo "BATCH SIZE: ".  count($ar) . "\n";
209         $pushed = array();
210         $requeue = array();
211         while (true) {
212             if ($w->fetch()) {
213                 $ar[] = clone($w);
214                 $total--;
215             }
216             
217             $this->logecho("BATCH SIZE: ".  (count($ar) + $total) );
218             
219             if (empty($ar)) {
220                 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
221                 
222                 if (empty($pushed)) {
223                     break;
224                 }
225                 $ar = $pushed;
226                 $pushed = false;
227                 continue;
228             }
229             
230             
231             $p = array_shift($ar);
232             if (!$this->poolfree()) {
233                 array_unshift($ar,$p); /// put it back on..
234                 sleep(3);
235                 continue;
236             }
237             $email = $p->person() ? $p->person()->email : $p->to_email;
238             
239             if ($this->poolHasDomain($email) > $this->max_to_domain) {
240                 
241                 if ($pushed === false) {
242                     // we only try once to requeue..
243                     $requeue[] = $p;
244                     continue;
245                 }
246                 $pushed[] = $p;
247                 
248                 
249                 //sleep(3);
250                 continue;
251             }
252             
253             
254             $this->run($p->id,$email);
255             
256             
257             
258         }
259         
260         // we should have a time limit here...
261         while(count($this->pool)) {
262             $this->poolfree();
263              sleep(3);
264         }
265          
266         foreach($requeue as $p) {
267             $pp = clone($p);
268             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
269             $p->update($pp);
270             
271         }
272         
273         
274         $this->logecho("DONE");
275         exit;
276     }
277     
278     function generateNotifications()
279     {
280         // this should check each module for 'GenerateNotifications.php' class..
281         //and run it if found..
282        
283      
284         $modules = array_reverse($this->modulesList());
285         
286         // move 'project' one to the end...
287         
288         foreach ($modules as $module){
289             if(in_array($module, $this->disabled)){
290                 continue;
291             }
292             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
293             if(!file_exists($file)){
294                 continue;
295             }
296             
297             require_once $file;
298             $class = "Pman_{$module}_GenerateNotifications";
299             $x = new $class;
300             if(!method_exists($x, 'generate')){
301                 continue;
302             };
303             //echo "$module\n";
304             $x->generate($this);
305         }
306                 
307     
308     }
309     
310     
311     
312     function run($id, $email, $cmdOpts="")
313     {
314         
315         static $renice = false;
316         if (!$renice) {
317             require_once 'System.php';
318             $renice = System::which('renice');
319         }
320         
321         // phpinfo();exit;
322         $tnx = tempnam(ini_get('session.save_path'),'stdout');
323         unlink($tnx);
324         $tn =  $tnx . '.stdout';
325         $descriptorspec = array(
326             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
327             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
328             2 => array("pipe", "w") // stderr is a file to write to
329          );
330         
331         static $php = false;
332         if (!$php) {
333             require_once 'System.php';
334             $php = System::which('php');
335         }
336         
337         $sn =  $_SERVER["SCRIPT_NAME"];
338         
339         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
340         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
341         if ($this->force) {
342             $app .= ' -f';
343         }
344         if (!empty($this->send_to)) {
345             $app .= ' --sent-to='.escapeshellarg($this->send_to);
346         }
347         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
348         
349        
350         $pipe = array();
351         $this->logecho("call proc_open $cmd");
352         
353         
354         if ($this->max_pool_size === 1) {
355             passthru($cmd);
356             return;
357         }
358         
359         
360         if (!empty($this->opts['dryrun'])) {
361             $this->logecho("DRY RUN");
362             return;
363         }
364         
365         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
366         $info =  proc_get_status($p);
367         
368         if ($this->nice_level !== false) { 
369             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
370             `$rcmd`;
371         } 
372         $this->pool[] = array(
373                 'proc' => $p,
374                 'pid' => $info['pid'],
375                 'out' => $tn,
376                 'cmd' => $cmd,
377                 'email' => $email,
378                 'pipes' => $pipes,
379                 'notify_id' => $id,
380                 'started' => time()
381             
382                 
383         );
384         $this->logecho("RUN ({$info['pid']}) $cmd ");
385     }
386     
387     function poolfree()
388     {
389         $pool = array();
390         clearstatcache();
391          
392         foreach($this->pool as $p) {
393              
394             //echo "CHECK PID: " . $p['pid'] . "\n";
395             $info =  proc_get_status($p['proc']);
396             //var_dump($info);
397             
398             // update if necessday.
399             if ($info['pid'] && $p['pid'] != $info['pid']) {
400                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
401                 $p['pid'] = $info['pid'];
402             }
403             
404             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
405             
406             if ($info['running']) {
407             
408                 //if (file_exists('/proc/'.$p['pid'])) {
409                 $runtime = time() - $p['started'];
410                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
411                 if ($runtime > $this->maxruntime) {
412                     
413                     proc_terminate($p['proc'], 9);
414                     //fclose($p['pipes'][1]);
415                     fclose($p['pipes'][0]);
416                     fclose($p['pipes'][2]);
417                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
418                     @unlink($p['out']);
419                     
420                     $w = DB_DataObject::factory($this->table);
421                     $w->get($p['notify_id']);
422                     $ww = clone($w);
423                     $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
424                     $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30  MINUTES'));
425                     $w->update($ww);
426                     
427                     
428                     continue;
429                 }
430                 
431                 $pool[] = $p;
432                 continue;
433             }
434             fclose($p['pipes'][0]);
435             fclose($p['pipes'][2]);
436             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
437             //fclose($p['pipes'][1]);
438             
439             proc_close($p['proc']);
440             
441             
442             //clearstatcache();
443             //if (file_exists('/proc/'.$p['pid'])) {
444             //    $pool[] = $p;
445             //    continue;
446             //}
447             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
448             @unlink($p['out']);
449             //unlink($p['out']);
450         }
451         $this->logecho("POOL SIZE: ". count($pool) );
452         $this->pool = $pool;
453         if (count($pool) < $this->max_pool_size) {
454             return true;
455         }
456         return false;
457         
458     }
459     /**
460      * see if pool is already trying to deliver to this domain.?
461      * -- if so it get's pushed to the end of the queue.
462      *
463      */
464     function poolHasDomain($email)
465     {
466         $ret = 0;
467         $dom = strtolower(array_pop(explode('@',$email)));
468         foreach($this->pool as $p) {
469             $mdom = strtolower(array_pop(explode('@',$p['email'])));
470             if ($mdom == $dom) {
471                 $ret++;
472             }
473         }
474         return $ret;
475         
476     }
477
478     function output()
479     {
480         $this->logecho("DONE");
481         exit;
482     }
483     function logecho($str)
484     {
485         echo date("Y-m-d H:i:s - ") . $str . "\n";
486     }
487 }