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