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