debug
[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 seconds a child is allowed to run - defaut 2 minutes
101      */
102     var $maxruntime = 120;
103     
104     /**
105     * @var {Boolean} log_events - default true if events should be logged.
106     */
107     var $log_events = true;
108     /**
109     * @var {Number} try_again_minutes how long after failing to try again default = 30 if max runtime fails
110     */
111     var $try_again_minutes = 30;
112     
113     /**
114      * @var {String} table - the table that the class will query for notification events
115      */
116     var $table = 'core_notify';
117     /**
118      * @var {String} target - the application that will run for each Row in the table (eg. Pman/Core/NotifySend)
119      */
120     var $target = 'Core/NotifySend';
121     
122     
123     
124     var $evtype = ''; // any notification...
125                     // this script should only handle EMAIL notifications..
126                     
127     var $opts; 
128     var $force = false;
129     function getAuth()
130     {
131         $ff = HTML_FlexyFramework::get();
132         if (!$ff->cli) {
133             die("access denied");
134         }
135         HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
136         return true;
137     }
138     
139     var $pool = array();
140     
141     function parseArgs(&$opts)
142     {
143         if ($opts['debug']) {
144             DB_DataObject::debugLevel($opts['debug']);
145             print_r($opts);
146         }
147         $this->opts = $opts;
148         if (!empty($opts['poolsize'])) {
149             $this->max_pool_size = $opts['poolsize'];
150         }
151         
152         if (empty($opts['limit'])) {
153             $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
154         }
155         
156         if (!empty($opts['old'])) {
157             $opts['list'] = 1; // force listing..
158         }
159         
160         $this->force = empty($opts['force']) ? 0 : 1;
161      
162         if (!empty($opts['send-to'])) {
163             $this->send_to = $opts['send-to'];
164         }
165     }
166     
167     var $queue = array();
168     var $domain_queue = array(); // false to use nextquee
169     var $next_queue = array();
170     var $server_id;
171    
172     function get($r,$opts=array())    
173     {
174         $this->parseArgs($opts); 
175          
176         //date_default_timezone_set('UTC');
177         
178         
179         $this->generateNotifications();
180         
181         $this->assignQueues();
182         
183         //DB_DataObject::debugLevel(1);
184         $w = DB_DataObject::factory($this->table);
185         $total = 0;
186         
187         
188         
189         $ff = HTML_FlexyFramework::get();
190         if (!empty($ff->Core_Notify['servers'])) {
191             if (!isset($ff->Core_Notify['servers'][gethostname()])) {
192                 $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
193             }
194             $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
195         }
196         if (!empty($this->evtype)) {
197             $w->evtype = $this->evtype;
198         }
199         
200         
201         
202         if (!empty($opts['old'])) {
203             // show old and new...
204             
205             $w->orderBy('act_when DESC'); // latest first
206             $w->limit($opts['limit']); // we can run 
207             $total = min($w->count(), $opts['limit']);
208         } else {   
209             // standard
210             
211             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
212             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
213             
214             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
215             if (!$this->force) {
216                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
217             }
218     
219             $w->orderBy('act_when ASC'); // oldest first.
220             $total = min($w->count(), $opts['limit']);
221             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
222             
223             $w->limit($opts['limit']); // we can run 1000 ...
224         }
225         
226         
227         
228     
229         
230          
231         $w->autoJoin();
232         $total = $w->find();
233         
234         
235         
236         if (!empty($opts['list'])) {
237             
238             
239             while ($w->fetch()) { 
240                 $o = $w->object();
241                 
242                 
243                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
244                         $o->toEventString()."    ". $w->status()  );
245             }
246             exit;
247         }
248         
249         //echo "BATCH SIZE: ".  count($ar) . "\n";
250        
251         
252         while (true) {
253             // only add if we don't have any queued up..
254             if (empty($this->queue) && $w->fetch()) {
255                 $this->queue[] = clone($w);
256                 $total--;
257             }
258           
259             $this->logecho("BATCH SIZE: Queue=".  count($this->queue) . " TOTAL = " . $total  );
260             
261             if (empty($this->queue)) {
262                 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
263                 if ($this->domain_queue !== false) {
264                     $this->queue  = $this->remainingDomainQueue();
265                      
266                     continue;
267                 }
268                 break; // nothing more in queue.. and no remaining one
269             }
270             
271             
272             $p = array_shift($this->queue);
273             if (!$this->poolfree()) {
274                 array_unshift($this->queue,$p); /// put it back on..
275                 sleep(3);
276                 continue;
277             }
278             // not sure what happesn if person email and to_email is empty!!?
279             $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
280             
281             $black = $this->isBlacklisted($email);
282             if ($black !== false) {
283                 $this->logecho("DOMAIN blacklisted - {$email} - moving to another pool");
284                 $this->updateServer($p, $black);
285                 continue;
286             }
287              
288             
289             if ($this->poolHasDomain($email) > $this->max_to_domain) {
290                 
291                 // push it to a 'domain specific queue'
292                 $this->logecho("REQUEING - maxed out that domain - {$email}");
293                 $this->pushQueueDomain($p, $email);
294                   
295                 
296                 //sleep(3);
297                 continue;
298             }
299             
300             
301             $this->run($p->id,$email);
302             
303             
304             
305         }
306          $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
307         if (!empty($this->next_queue)) {
308              
309             foreach($this->next_queue as $p) {
310                 $this->updateServer($p);
311             }
312         }
313         
314         
315         $this->logecho("QUEUE COMPLETE - waiting for pool to end");
316         // we should have a time limit here...
317         while(count($this->pool)) {
318             $this->poolfree();
319             sleep(3);
320         }
321          
322         
323         
324         
325         $this->logecho("DONE");
326         exit;
327     }
328     
329     
330     function isBlacklisted($email)
331     {
332         // return current server id..
333         $this->logecho("CHECK BLACKLISTED - {$email}");
334         if (empty($ff->Core_Notify['servers'])) {
335             return false;
336         }
337       
338         if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
339             return false;
340         }
341        
342         // get the domain..
343         $ea = explode('@',$email);
344         $dom = strtolower(array_pop($ea));
345         
346         $this->logecho("CHECK BLACKLISTED DOM - {$dom}");
347         if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
348             return false;
349         }
350         $this->logecho("RETURN BLACKLISTED TRUE");
351         return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
352     }
353     
354     // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
355     function updateServer($w, $exclude = -1)
356     {
357         $ff = HTML_FlexyFramework::get();
358         static $num = 0;
359         if (empty($ff->Core_Notify['servers'])) {
360             return;
361         }
362         $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
363         if ($exclude == $num ) {
364             $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
365         }
366         // next server..
367         $pp = clone($w);
368         $w->server_id = $num;
369                     
370         $w->act_when = $w->sqlValue('NOW + INTERVAL 1 MINUTE');
371         $w->update($pp);
372         
373          
374     }
375   
376     
377     function generateNotifications()
378     {
379         // this should check each module for 'GenerateNotifications.php' class..
380         //and run it if found..
381         $ff = HTML_FlexyFramework::get();
382        
383         $disabled = explode(',', $ff->disable);
384
385         $modules = array_reverse($this->modulesList());
386         
387         // move 'project' one to the end...
388         
389         foreach ($modules as $module){
390             if(in_array($module, $disabled)){
391                 continue;
392             }
393             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
394             if(!file_exists($file)){
395                 continue;
396             }
397             
398             require_once $file;
399             $class = "Pman_{$module}_GenerateNotifications";
400             $x = new $class;
401             if(!method_exists($x, 'generate')){
402                 continue;
403             };
404             //echo "$module\n";
405             $x->generate($this);
406         }
407                 
408     
409     }
410     
411     function assignQueues()
412     {
413         $ff = HTML_FlexyFramework::get();
414         
415         if (empty($ff->Core_Notify['servers'])) {
416             return;
417         }
418         
419         if (!isset($ff->Core_Notify['servers'][gethostname()])) {
420             $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
421         }
422         // only run this on the main server...
423         if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
424             return;
425         }
426         
427         $num_servers = count(array_keys($ff->Core_Notify['servers']));
428         $p = DB_DataObject::factory($this->table);
429         $p->whereAdd("
430                 sent < '2000-01-01'
431                 and
432                 event_id = 0
433                 and
434                 act_start < NOW() +  INTERVAL 3 HOUR 
435                 and
436                 server_id < 0"
437             
438         );
439         if ($p->count() < 1) {
440             return;
441         }
442          $p = DB_DataObject::factory($this->table);
443         // 6 seconds on this machne...
444         $p->query("
445             UPDATE
446                 {$this->table}
447             SET
448                 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
449             WHERE
450                 sent < '2000-01-01'
451                 and
452                 event_id = 0
453                 and
454                 act_start < NOW() +  INTERVAL 3 HOUR 
455                 and
456                 server_id < 0
457             ORDER BY
458                 id ASC
459             LIMIT
460                 10000
461         ");
462
463         
464     }
465     
466     function run($id, $email='', $cmdOpts="")
467     {
468         
469         static $renice = false;
470         if (!$renice) {
471             require_once 'System.php';
472             $renice = System::which('renice');
473         }
474         
475         // phpinfo();exit;
476         
477         
478         $tn =  $this->tempName('stdout', true);
479         $descriptorspec = array(
480             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
481             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
482             2 => array("pipe", "w") // stderr is a file to write to
483          );
484         
485         static $php = false;
486         if (!$php) {
487             require_once 'System.php';
488             $php = System::which('php');
489         }
490         
491         $sn =  $_SERVER["SCRIPT_NAME"];
492         
493         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
494         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
495         if ($this->force) {
496             $app .= ' -f';
497         }
498         if (!empty($this->send_to)) {
499             $app .= ' --sent-to='.escapeshellarg($this->send_to);
500         }
501         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
502         
503        
504         $pipe = array();
505         //$this->logecho("call proc_open $cmd");
506         
507         
508         if ($this->max_pool_size === 1) {
509             $this->logecho("call passthru [{$email}] $cmd");
510             passthru($cmd);
511             return;
512         }
513         
514         
515         if (!empty($this->opts['dryrun'])) {
516             $this->logecho("DRY RUN");
517             return;
518         }
519         
520         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
521         $info =  proc_get_status($p);
522         
523         if ($this->nice_level !== false) { 
524             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
525             `$rcmd`;
526         } 
527         $this->pool[] = array(
528                 'proc' => $p,
529                 'pid' => $info['pid'],
530                 'out' => $tn,
531                 'cmd' => $cmd,
532                 'email' => $email,
533                 'pipes' => $pipes,
534                 'notify_id' => $id,
535                 'started' => time()
536             
537                 
538         );
539         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
540     }
541     
542     function poolfree()
543     {
544         $pool = array();
545         clearstatcache();
546          
547         foreach($this->pool as $p) {
548              
549             //echo "CHECK PID: " . $p['pid'] . "\n";
550             $info =  proc_get_status($p['proc']);
551             //var_dump($info);
552             
553             // update if necessday.
554             if ($info['pid'] && $p['pid'] != $info['pid']) {
555                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
556                 $p['pid'] = $info['pid'];
557             }
558             
559             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
560             
561             if ($info['running']) {
562             
563                 //if (file_exists('/proc/'.$p['pid'])) {
564                 $runtime = time() - $p['started'];
565                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
566                 if ($runtime > $this->maxruntime) {
567                     
568                     proc_terminate($p['proc'], 9);
569                     //fclose($p['pipes'][1]);
570                     fclose($p['pipes'][0]);
571                     fclose($p['pipes'][2]);
572                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
573                     @unlink($p['out']);
574                     
575                     // schedule again
576                     $w = DB_DataObject::factory($this->table);
577                     $w->get($p['notify_id']);
578                     $ww = clone($w);
579                     if ($this->log_events) {
580                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
581                     }
582                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
583                     $w->update($ww);
584                     
585                     continue;
586                 }
587                 
588                 $pool[] = $p;
589                 continue;
590             }
591             fclose($p['pipes'][0]);
592             fclose($p['pipes'][2]);
593             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
594             //fclose($p['pipes'][1]);
595             
596             proc_close($p['proc']);
597             
598             
599             //clearstatcache();
600             //if (file_exists('/proc/'.$p['pid'])) {
601             //    $pool[] = $p;
602             //    continue;
603             //}
604             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
605             @unlink($p['out']);
606             // at this point we could pop onto the queue the 
607             $this->popQueueDomain($p['email']);
608             
609             //unlink($p['out']);
610         }
611         $this->logecho("POOL SIZE: ". count($pool) );
612         $this->pool = $pool;
613         if (count($pool) < $this->max_pool_size) {
614             return true;
615         }
616         return false;
617         
618     }
619     /**
620      * see if pool is already trying to deliver to this domain.?
621      * -- if so it get's pushed to the end of the queue.
622      *
623      */
624     function poolHasDomain($email)
625     {
626         $ret = 0;
627         $ea = explode('@',$email);
628         $dom = strtolower(array_pop($ea));
629         foreach($this->pool as $p) {
630             $ea = explode('@',$p['email']);
631             $mdom = strtolower(array_pop($ea));
632             if ($mdom == $dom) {
633                 $ret++;
634             }
635         }
636         return $ret;
637         
638     }
639     function popQueueDomain($email)
640     {
641         $ea = explode('@',$email);
642         $dom = strtolower(array_pop($ea));
643         if (empty($this->domain_queue[$dom])) {
644             return;
645         }
646         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
647         
648     }
649     
650     function pushQueueDomain($e, $email)
651     {
652         if ($this->domain_queue === false) {
653             $this->next_queue[] = $e;
654             return;
655         }
656         
657         $ea = explode('@',$email);
658         $dom = strtolower(array_pop($ea));
659         if (!isset($this->domain_queue[$dom])) {
660             $this->domain_queue[$dom] = array();
661         }
662         $this->domain_queue[$dom][] = $e;
663     }
664     function remainingDomainQueue()
665     {
666         $ret = array();
667         foreach($this->domain_queue as $dom => $ar) {
668             $ret = array_merge($ret, $ar);
669         }
670         $this->domain_queue = false;
671         return $ret;
672     }
673     
674     
675
676     function output()
677     {
678         $this->logecho("DONE");
679         exit;
680     }
681     function logecho($str)
682     {
683         echo date("Y-m-d H:i:s - ") . $str . "\n";
684     }
685 }