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