missing $ff
[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         $ff = HTML_FlexyFramework::get();
334         //$this->logecho("CHECK BLACKLISTED - {$email}");
335         if (empty($ff->Core_Notify['servers'])) {
336             return false;
337         }
338       
339         if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
340             return false;
341         }
342        
343         // get the domain..
344         $ea = explode('@',$email);
345         $dom = strtolower(array_pop($ea));
346         
347         //$this->logecho("CHECK BLACKLISTED DOM - {$dom}");
348         if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
349             return false;
350         }
351         //$this->logecho("RETURN BLACKLISTED TRUE");
352         return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
353     }
354     
355     // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
356     function updateServer($w, $exclude = -1)
357     {
358         $ff = HTML_FlexyFramework::get();
359         static $num = 0;
360         if (empty($ff->Core_Notify['servers'])) {
361             return;
362         }
363         $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
364         if ($exclude == $num ) {
365             $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
366         }
367         // next server..
368         $pp = clone($w);
369         $w->server_id = $num;
370                     
371         $w->act_when = $w->sqlValue('NOW + INTERVAL 1 MINUTE');
372         $w->update($pp);
373         
374          
375     }
376   
377     
378     function generateNotifications()
379     {
380         // this should check each module for 'GenerateNotifications.php' class..
381         //and run it if found..
382         $ff = HTML_FlexyFramework::get();
383        
384         $disabled = explode(',', $ff->disable);
385
386         $modules = array_reverse($this->modulesList());
387         
388         // move 'project' one to the end...
389         
390         foreach ($modules as $module){
391             if(in_array($module, $disabled)){
392                 continue;
393             }
394             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
395             if(!file_exists($file)){
396                 continue;
397             }
398             
399             require_once $file;
400             $class = "Pman_{$module}_GenerateNotifications";
401             $x = new $class;
402             if(!method_exists($x, 'generate')){
403                 continue;
404             };
405             //echo "$module\n";
406             $x->generate($this);
407         }
408                 
409     
410     }
411     
412     function assignQueues()
413     {
414         $ff = HTML_FlexyFramework::get();
415         
416         if (empty($ff->Core_Notify['servers'])) {
417             return;
418         }
419         
420         if (!isset($ff->Core_Notify['servers'][gethostname()])) {
421             $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
422         }
423         // only run this on the main server...
424         if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
425             return;
426         }
427         
428         $num_servers = count(array_keys($ff->Core_Notify['servers']));
429         $p = DB_DataObject::factory($this->table);
430         $p->whereAdd("
431                 sent < '2000-01-01'
432                 and
433                 event_id = 0
434                 and
435                 act_start < NOW() +  INTERVAL 3 HOUR 
436                 and
437                 server_id < 0"
438             
439         );
440         if ($p->count() < 1) {
441             return;
442         }
443          $p = DB_DataObject::factory($this->table);
444         // 6 seconds on this machne...
445         $p->query("
446             UPDATE
447                 {$this->table}
448             SET
449                 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
450             WHERE
451                 sent < '2000-01-01'
452                 and
453                 event_id = 0
454                 and
455                 act_start < NOW() +  INTERVAL 3 HOUR 
456                 and
457                 server_id < 0
458             ORDER BY
459                 id ASC
460             LIMIT
461                 10000
462         ");
463
464         
465     }
466     
467     function run($id, $email='', $cmdOpts="")
468     {
469         
470         static $renice = false;
471         if (!$renice) {
472             require_once 'System.php';
473             $renice = System::which('renice');
474         }
475         
476         // phpinfo();exit;
477         
478         
479         $tn =  $this->tempName('stdout', true);
480         $descriptorspec = array(
481             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
482             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
483             2 => array("pipe", "w") // stderr is a file to write to
484          );
485         
486         static $php = false;
487         if (!$php) {
488             require_once 'System.php';
489             $php = System::which('php');
490         }
491         
492         $sn =  $_SERVER["SCRIPT_NAME"];
493         
494         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
495         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
496         if ($this->force) {
497             $app .= ' -f';
498         }
499         if (!empty($this->send_to)) {
500             $app .= ' --sent-to='.escapeshellarg($this->send_to);
501         }
502         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
503         
504        
505         $pipe = array();
506         //$this->logecho("call proc_open $cmd");
507         
508         
509         if ($this->max_pool_size === 1) {
510             $this->logecho("call passthru [{$email}] $cmd");
511             passthru($cmd);
512             return;
513         }
514         
515         
516         if (!empty($this->opts['dryrun'])) {
517             $this->logecho("DRY RUN");
518             return;
519         }
520         
521         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
522         $info =  proc_get_status($p);
523         
524         if ($this->nice_level !== false) { 
525             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
526             `$rcmd`;
527         } 
528         $this->pool[] = array(
529                 'proc' => $p,
530                 'pid' => $info['pid'],
531                 'out' => $tn,
532                 'cmd' => $cmd,
533                 'email' => $email,
534                 'pipes' => $pipes,
535                 'notify_id' => $id,
536                 'started' => time()
537             
538                 
539         );
540         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
541     }
542     
543     function poolfree()
544     {
545         $pool = array();
546         clearstatcache();
547          
548         foreach($this->pool as $p) {
549              
550             //echo "CHECK PID: " . $p['pid'] . "\n";
551             $info =  proc_get_status($p['proc']);
552             //var_dump($info);
553             
554             // update if necessday.
555             if ($info['pid'] && $p['pid'] != $info['pid']) {
556                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
557                 $p['pid'] = $info['pid'];
558             }
559             
560             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
561             
562             if ($info['running']) {
563             
564                 //if (file_exists('/proc/'.$p['pid'])) {
565                 $runtime = time() - $p['started'];
566                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
567                 if ($runtime > $this->maxruntime) {
568                     
569                     proc_terminate($p['proc'], 9);
570                     //fclose($p['pipes'][1]);
571                     fclose($p['pipes'][0]);
572                     fclose($p['pipes'][2]);
573                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
574                     @unlink($p['out']);
575                     
576                     // schedule again
577                     $w = DB_DataObject::factory($this->table);
578                     $w->get($p['notify_id']);
579                     $ww = clone($w);
580                     if ($this->log_events) {
581                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
582                     }
583                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
584                     $w->update($ww);
585                     
586                     continue;
587                 }
588                 
589                 $pool[] = $p;
590                 continue;
591             }
592             fclose($p['pipes'][0]);
593             fclose($p['pipes'][2]);
594             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
595             //fclose($p['pipes'][1]);
596             
597             proc_close($p['proc']);
598             
599             
600             //clearstatcache();
601             //if (file_exists('/proc/'.$p['pid'])) {
602             //    $pool[] = $p;
603             //    continue;
604             //}
605             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
606             @unlink($p['out']);
607             // at this point we could pop onto the queue the 
608             $this->popQueueDomain($p['email']);
609             
610             //unlink($p['out']);
611         }
612         $this->logecho("POOL SIZE: ". count($pool) );
613         $this->pool = $pool;
614         if (count($pool) < $this->max_pool_size) {
615             return true;
616         }
617         return false;
618         
619     }
620     /**
621      * see if pool is already trying to deliver to this domain.?
622      * -- if so it get's pushed to the end of the queue.
623      *
624      */
625     function poolHasDomain($email)
626     {
627         $ret = 0;
628         $ea = explode('@',$email);
629         $dom = strtolower(array_pop($ea));
630         foreach($this->pool as $p) {
631             $ea = explode('@',$p['email']);
632             $mdom = strtolower(array_pop($ea));
633             if ($mdom == $dom) {
634                 $ret++;
635             }
636         }
637         return $ret;
638         
639     }
640     function popQueueDomain($email)
641     {
642         $ea = explode('@',$email);
643         $dom = strtolower(array_pop($ea));
644         if (empty($this->domain_queue[$dom])) {
645             return;
646         }
647         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
648         
649     }
650     
651     function pushQueueDomain($e, $email)
652     {
653         if ($this->domain_queue === false) {
654             $this->next_queue[] = $e;
655             return;
656         }
657         
658         $ea = explode('@',$email);
659         $dom = strtolower(array_pop($ea));
660         if (!isset($this->domain_queue[$dom])) {
661             $this->domain_queue[$dom] = array();
662         }
663         $this->domain_queue[$dom][] = $e;
664     }
665     function remainingDomainQueue()
666     {
667         $ret = array();
668         foreach($this->domain_queue as $dom => $ar) {
669             $ret = array_merge($ret, $ar);
670         }
671         $this->domain_queue = false;
672         return $ret;
673     }
674     
675     
676
677     function output()
678     {
679         $this->logecho("DONE");
680         exit;
681     }
682     function logecho($str)
683     {
684         echo date("Y-m-d H:i:s - ") . $str . "\n";
685     }
686 }