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