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         
156         
157        // phpinfo();exit;
158         if (!empty($opts['generate'])) {
159             $w = DB_DataObject::factory($opts['generate']);
160             if (is_a($w, 'DB_DataObject')) {
161                 $w->generateNotifications();
162             }
163             exit;
164         }
165      
166      
167         
168         $w = DB_DataObject::factory('core_notify_recur');
169         if (is_a($w, 'DB_DataObject')) {
170             $w->generateNotifications();
171         }
172         
173         //DB_DataObject::debugLevel(1);
174         $w = DB_DataObject::factory($this->table);
175         $total = 0;
176         
177         if (!empty($opts['old'])) {
178             // show old and new...
179             
180             $w->orderBy('act_when DESC'); // latest first
181             $w->limit($opts['limit']); // we can run 
182             $total = min($w->count(), $opts['limit']);
183         } else {   
184             // standard
185             
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..
188             
189             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
190             if (!$this->force) {
191                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
192             }
193     
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']));
197             
198             $w->limit($opts['limit']); // we can run 1000 ...
199         }
200         
201         if (!empty($this->evtype)) {
202             $w->evtype = $this->evtype;
203         }
204         
205         $w->autoJoin();
206         $w->find();
207         
208         $ar = array(); // $w->fetchAll();
209         
210         if (!empty($opts['list'])) {
211             
212             
213             while ($w->fetch()) { 
214                 $o = $w->object();
215                 
216                 
217                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
218                         $o->toEventString()."    ". $w->status()  );
219             }
220             exit;
221         }
222         
223         //echo "BATCH SIZE: ".  count($ar) . "\n";
224         $pushed = array();
225         $requeue = array();
226         while (true) {
227             if ($w->fetch()) {
228                 $ar[] = clone($w);
229                 $total--;
230             }
231             
232             $this->logecho("BATCH SIZE: ".  (count($ar) + $total) );
233             
234             if (empty($ar)) {
235                 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
236                 
237                 if (empty($pushed)) {
238                     break;
239                 }
240                 $ar = $pushed;
241                 $pushed = false;
242                 continue;
243             }
244             
245             
246             $p = array_shift($ar);
247             if (!$this->poolfree()) {
248                 array_unshift($ar,$p); /// put it back on..
249                 sleep(3);
250                 continue;
251             }
252             $email = $p->person() ? $p->person()->email : $p->to_email;
253             
254             if ($this->poolHasDomain($email) > $this->max_to_domain) {
255                 
256                 if ($pushed === false) {
257                     // we only try once to requeue..
258                     $requeue[] = $p;
259                     continue;
260                 }
261                 $pushed[] = $p;
262                 
263                 
264                 //sleep(3);
265                 continue;
266             }
267             
268             
269             $this->run($p->id,$email);
270             
271             
272             
273         }
274         
275         // we should have a time limit here...
276         while(count($this->pool)) {
277             $this->poolfree();
278              sleep(3);
279         }
280          
281         foreach($requeue as $p) {
282             $pp = clone($p);
283             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
284             $p->update($pp);
285             
286         }
287         
288         
289         $this->logecho("DONE");
290         exit;
291     }
292     
293     function generateNotifications()
294     {
295         // this should check each module for 'GenerateNotifications.php' class..
296         //and run it if found..
297        
298      
299         $modules = array_reverse($this->modulesList());
300         
301         // move 'project' one to the end...
302         
303         foreach ($modules as $module){
304             if(in_array($module, $this->disabled)){
305                 continue;
306             }
307             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
308             if(!file_exists($file)){
309                 continue;
310             }
311             
312             require_once $file;
313             $class = "Pman_{$module}_GenerateNotifications";
314             $x = new $class;
315             if(!method_exists($x, 'generate')){
316                 continue;
317             };
318             //echo "$module\n";
319             $x->generate($this);
320         }
321                 
322     
323     }
324     
325     
326     
327     function run($id, $email, $cmdOpts="")
328     {
329         
330         static $renice = false;
331         if (!$renice) {
332             require_once 'System.php';
333             $renice = System::which('renice');
334         }
335         
336         // phpinfo();exit;
337         $tnx = tempnam(ini_get('session.save_path'),'stdout');
338         unlink($tnx);
339         $tn =  $tnx . '.stdout';
340         $descriptorspec = array(
341             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
342             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
343             2 => array("pipe", "w") // stderr is a file to write to
344          );
345         
346         static $php = false;
347         if (!$php) {
348             require_once 'System.php';
349             $php = System::which('php');
350         }
351         
352         $sn =  $_SERVER["SCRIPT_NAME"];
353         
354         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
355         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
356         if ($this->force) {
357             $app .= ' -f';
358         }
359         if (!empty($this->send_to)) {
360             $app .= ' --sent-to='.escapeshellarg($this->send_to);
361         }
362         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
363         
364        
365         $pipe = array();
366         $this->logecho("call proc_open $cmd");
367         
368         
369         if ($this->max_pool_size === 1) {
370             passthru($cmd);
371             return;
372         }
373         
374         
375         if (!empty($this->opts['dryrun'])) {
376             $this->logecho("DRY RUN");
377             return;
378         }
379         
380         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
381         $info =  proc_get_status($p);
382         
383         if ($this->nice_level !== false) { 
384             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
385             `$rcmd`;
386         } 
387         $this->pool[] = array(
388                 'proc' => $p,
389                 'pid' => $info['pid'],
390                 'out' => $tn,
391                 'cmd' => $cmd,
392                 'email' => $email,
393                 'pipes' => $pipes,
394                 'notify_id' => $id,
395                 'started' => time()
396             
397                 
398         );
399         $this->logecho("RUN ({$info['pid']}) $cmd ");
400     }
401     
402     function poolfree()
403     {
404         $pool = array();
405         clearstatcache();
406          
407         foreach($this->pool as $p) {
408              
409             //echo "CHECK PID: " . $p['pid'] . "\n";
410             $info =  proc_get_status($p['proc']);
411             //var_dump($info);
412             
413             // update if necessday.
414             if ($info['pid'] && $p['pid'] != $info['pid']) {
415                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
416                 $p['pid'] = $info['pid'];
417             }
418             
419             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
420             
421             if ($info['running']) {
422             
423                 //if (file_exists('/proc/'.$p['pid'])) {
424                 $runtime = time() - $p['started'];
425                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
426                 if ($runtime > $this->maxruntime) {
427                     
428                     proc_terminate($p['proc'], 9);
429                     //fclose($p['pipes'][1]);
430                     fclose($p['pipes'][0]);
431                     fclose($p['pipes'][2]);
432                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
433                     @unlink($p['out']);
434                     
435                     $w = DB_DataObject::factory($this->table);
436                     $w->get($p['notify_id']);
437                     $ww = clone($w);
438                     $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
439                     $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30  MINUTES'));
440                     $w->update($ww);
441                     
442                     
443                     continue;
444                 }
445                 
446                 $pool[] = $p;
447                 continue;
448             }
449             fclose($p['pipes'][0]);
450             fclose($p['pipes'][2]);
451             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
452             //fclose($p['pipes'][1]);
453             
454             proc_close($p['proc']);
455             
456             
457             //clearstatcache();
458             //if (file_exists('/proc/'.$p['pid'])) {
459             //    $pool[] = $p;
460             //    continue;
461             //}
462             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
463             @unlink($p['out']);
464             //unlink($p['out']);
465         }
466         $this->logecho("POOL SIZE: ". count($pool) );
467         $this->pool = $pool;
468         if (count($pool) < $this->max_pool_size) {
469             return true;
470         }
471         return false;
472         
473     }
474     /**
475      * see if pool is already trying to deliver to this domain.?
476      * -- if so it get's pushed to the end of the queue.
477      *
478      */
479     function poolHasDomain($email)
480     {
481         $ret = 0;
482         $dom = strtolower(array_pop(explode('@',$email)));
483         foreach($this->pool as $p) {
484             $mdom = strtolower(array_pop(explode('@',$p['email'])));
485             if ($mdom == $dom) {
486                 $ret++;
487             }
488         }
489         return $ret;
490         
491     }
492
493     function output()
494     {
495         $this->logecho("DONE");
496         exit;
497     }
498     function logecho($str)
499     {
500         echo date("Y-m-d H:i:s - ") . $str . "\n";
501     }
502 }