PHP8
[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     var $server_id;
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'][gethostname()])) {
431             $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
432         }
433         // only run this on the main server...
434         if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
435             return;
436         }
437         
438         $num_servers = count(array_keys($ff->Core_Notify['servers']));
439         $p = DB_DataObject::factory($this->table);
440         $p->whereAdd("
441                 sent < '2000-01-01'
442                 and
443                 event_id = 0
444                 and
445                 act_start < NOW() +  INTERVAL 3 HOUR 
446                 and
447                 server_id < 0"
448             
449         );
450         if ($p->count() < 1) {
451             return;
452         }
453          $p = DB_DataObject::factory($this->table);
454         // 6 seconds on this machne...
455         $p->query("
456             UPDATE
457                 {$this->table}
458             SET
459                 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
460             WHERE
461                 sent < '2000-01-01'
462                 and
463                 event_id = 0
464                 and
465                 act_start < NOW() +  INTERVAL 3 HOUR 
466                 and
467                 server_id < 0
468             ORDER BY
469                 id ASC
470             LIMIT
471                 10000
472         ");
473
474         
475     }
476     
477     function run($id, $email='', $cmdOpts="")
478     {
479         
480         static $renice = false;
481         if (!$renice) {
482             require_once 'System.php';
483             $renice = System::which('renice');
484         }
485         
486         // phpinfo();exit;
487         
488         
489         $tn =  $this->tempName('stdout', true);
490         $descriptorspec = array(
491             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
492             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
493             2 => array("pipe", "w") // stderr is a file to write to
494          );
495         
496         static $php = false;
497         if (!$php) {
498             require_once 'System.php';
499             $php = System::which('php');
500         }
501         
502         $sn =  $_SERVER["SCRIPT_NAME"];
503         
504         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
505         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
506         if ($this->force) {
507             $app .= ' -f';
508         }
509         if (!empty($this->send_to)) {
510             $app .= ' --sent-to='.escapeshellarg($this->send_to);
511         }
512         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
513         
514        
515         $pipe = array();
516         //$this->logecho("call proc_open $cmd");
517         
518         
519         if ($this->max_pool_size === 1) {
520             $this->logecho("call passthru [{$email}] $cmd");
521             passthru($cmd);
522             return;
523         }
524         
525         
526         if (!empty($this->opts['dryrun'])) {
527             $this->logecho("DRY RUN");
528             return;
529         }
530         
531         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
532         $info =  proc_get_status($p);
533         
534         if ($this->nice_level !== false) { 
535             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
536             `$rcmd`;
537         } 
538         $this->pool[] = array(
539                 'proc' => $p,
540                 'pid' => $info['pid'],
541                 'out' => $tn,
542                 'cmd' => $cmd,
543                 'email' => $email,
544                 'pipes' => $pipes,
545                 'notify_id' => $id,
546                 'started' => time()
547             
548                 
549         );
550         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
551     }
552     
553     function poolfree()
554     {
555         $pool = array();
556         clearstatcache();
557          
558         foreach($this->pool as $p) {
559              
560             //echo "CHECK PID: " . $p['pid'] . "\n";
561             $info =  proc_get_status($p['proc']);
562             //var_dump($info);
563             
564             // update if necessday.
565             if ($info['pid'] && $p['pid'] != $info['pid']) {
566                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
567                 $p['pid'] = $info['pid'];
568             }
569             
570             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
571             
572             if ($info['running']) {
573             
574                 //if (file_exists('/proc/'.$p['pid'])) {
575                 $runtime = time() - $p['started'];
576                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
577                 if ($runtime > $this->maxruntime) {
578                     
579                     proc_terminate($p['proc'], 9);
580                     //fclose($p['pipes'][1]);
581                     fclose($p['pipes'][0]);
582                     fclose($p['pipes'][2]);
583                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
584                     @unlink($p['out']);
585                     
586                     // schedule again
587                     $w = DB_DataObject::factory($this->table);
588                     $w->get($p['notify_id']);
589                     $ww = clone($w);
590                     if ($this->log_events) {
591                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
592                     }
593                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
594                     $w->update($ww);
595                     
596                     continue;
597                 }
598                 
599                 $pool[] = $p;
600                 continue;
601             }
602             fclose($p['pipes'][0]);
603             fclose($p['pipes'][2]);
604             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
605             //fclose($p['pipes'][1]);
606             
607             proc_close($p['proc']);
608             
609             
610             //clearstatcache();
611             //if (file_exists('/proc/'.$p['pid'])) {
612             //    $pool[] = $p;
613             //    continue;
614             //}
615             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
616             @unlink($p['out']);
617             // at this point we could pop onto the queue the 
618             $this->popQueueDomain($p['email']);
619             
620             //unlink($p['out']);
621         }
622         $this->logecho("POOL SIZE: ". count($pool) );
623         $this->pool = $pool;
624         if (count($pool) < $this->max_pool_size) {
625             return true;
626         }
627         return false;
628         
629     }
630     /**
631      * see if pool is already trying to deliver to this domain.?
632      * -- if so it get's pushed to the end of the queue.
633      *
634      */
635     function poolHasDomain($email)
636     {
637         $ret = 0;
638         $ea = explode('@',$email);
639         $dom = strtolower(array_pop($ea));
640         foreach($this->pool as $p) {
641             $ea = explode('@',$p['email']);
642             $mdom = strtolower(array_pop($ea));
643             if ($mdom == $dom) {
644                 $ret++;
645             }
646         }
647         return $ret;
648         
649     }
650     function popQueueDomain($email)
651     {
652         $ea = explode('@',$email);
653         $dom = strtolower(array_pop($ea));
654         if (empty($this->domain_queue[$dom])) {
655             return;
656         }
657         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
658         
659     }
660     
661     function pushQueueDomain($e, $email)
662     {
663         if ($this->domain_queue === false) {
664             $this->next_queue[] = $e;
665             return;
666         }
667         
668         $ea = explode('@',$email);
669         $dom = strtolower(array_pop($ea));
670         if (!isset($this->domain_queue[$dom])) {
671             $this->domain_queue[$dom] = array();
672         }
673         $this->domain_queue[$dom][] = $e;
674     }
675     function remainingDomainQueue()
676     {
677         $ret = array();
678         foreach($this->domain_queue as $dom => $ar) {
679             $ret = array_merge($ret, $ar);
680         }
681         $this->domain_queue = false;
682         return $ret;
683     }
684     
685     
686
687     function output()
688     {
689         $this->logecho("DONE");
690         exit;
691     }
692     function logecho($str)
693     {
694         echo date("Y-m-d H:i:s - ") . $str . "\n";
695     }
696 }