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