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