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