fix sent update
[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         $w->server_id = $this->server->id;
210
211         
212         if (!empty($opts['old'])) {
213             // show old and new...
214             
215             $w->orderBy('act_when DESC'); // latest first
216             $w->limit($opts['limit']); // we can run 
217             $total = min($w->count(), $opts['limit']);
218         } else {   
219             // standard
220             
221             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
222             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
223             
224             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
225             if (!$this->force) {
226                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
227             }
228             
229     
230             $w->orderBy('act_when ASC'); // oldest first.
231             $total = min($w->count(), $opts['limit']);
232             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
233             
234             $w->limit($opts['limit']); // we can run 1000 ...
235         }
236         
237         
238     
239         
240          
241         $w->autoJoin();
242         $total = $w->find();
243         
244         if (empty($total)) {
245             $this->logecho("Nothing In Queue - DONE");
246             exit;
247         }
248         
249         
250         if (!empty($opts['list'])) {
251             
252             
253             while ($w->fetch()) { 
254                 $o = $w->object();
255                 
256                 
257                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
258                         $o->toEventString()."    ". $w->status()  );
259             }
260             exit;
261         }
262         
263         //echo "BATCH SIZE: ".  count($ar) . "\n";
264        
265         
266         while (true) {
267             // only add if we don't have any queued up..
268             if (empty($this->queue) && $w->fetch()) {
269                 $this->queue[] = clone($w);
270                 $total--;
271             }
272           
273             $this->logecho("BATCH SIZE: Queue=".  count($this->queue) . " TOTAL = " . $total  );
274             
275             if (empty($this->queue)) {
276                 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
277                 if ($this->domain_queue !== false) {
278                     $this->queue  = $this->remainingDomainQueue();
279                      
280                     continue;
281                 }
282                 break; // nothing more in queue.. and no remaining one
283             }
284             
285             
286             $p = array_shift($this->queue);
287             if (!$this->poolfree()) {
288                 array_unshift($this->queue,$p); /// put it back on..
289                 sleep(3);
290                 continue;
291             }
292             // not sure what happesn if person email and to_email is empty!!?
293             $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
294             
295             $black = $this->server->isBlacklisted($email);
296             if ($black !== false) {
297                 $this->logecho("Blacklisted - try giving it to next server");
298                 if (false === $this->server->updateNotifyToNextServer($p)) {
299                     $ev = $this->addEvent('NOTIFY', $p, 'BLACKLISTED  FROM our DB');
300                     // we dont have an althenative server to update it with.
301                     $this->logecho("Blacklisted - next server did not work - try again in 30 mins");
302                     $this->server->updateNotifyToNextServer($w,  date("Y-m-d H:i:s",  strtotime('NOW +  30 MINUTES')),true);
303                    // $this->errorHandler( $ev->remarks);
304                    
305                 }
306                 
307                 continue;
308             }
309              
310             
311             if ($this->poolHasDomain($email) > $this->max_to_domain) {
312                 
313                 // push it to a 'domain specific queue'
314                 $this->logecho("REQUEING - maxed out that domain - {$email}");
315                 $this->pushQueueDomain($p, $email);
316                    
317                 //sleep(3);
318                 continue;
319             }
320             
321             
322             $this->run($p->id,$email);
323             
324             
325             
326         }
327         $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
328         if (!empty($this->next_queue)) {
329              
330             foreach($this->next_queue as $p) {
331                 if (false === $this->server->updateNotifyToNextServer($p)) {
332                     $p->updateState("????");
333                 }
334             }
335         }
336         
337         
338         $this->logecho("QUEUE COMPLETE - waiting for pool to end");
339         // we should have a time limit here...
340         while(count($this->pool)) {
341             $this->poolfree();
342             sleep(3);
343         }
344          
345         
346         
347         
348         $this->logecho("DONE");
349         exit;
350     }
351     
352     
353    
354     
355     // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
356      
357   
358     
359     function generateNotifications()
360     {
361         // this should check each module for 'GenerateNotifications.php' class..
362         //and run it if found..
363         $ff = HTML_FlexyFramework::get();
364        
365         $disabled = explode(',', $ff->disable);
366
367         $modules = array_reverse($this->modulesList());
368         
369         // move 'project' one to the end...
370         
371         foreach ($modules as $module){
372             if(in_array($module, $disabled)){
373                 continue;
374             }
375             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
376             if(!file_exists($file)){
377                 continue;
378             }
379             
380             require_once $file;
381             $class = "Pman_{$module}_GenerateNotifications";
382             $x = new $class;
383             if(!method_exists($x, 'generate')){
384                 continue;
385             };
386             //echo "$module\n";
387             $x->generate($this);
388         }
389                 
390     
391     }
392     
393      
394     
395     function run($id, $email='', $cmdOpts="")
396     {
397         
398         static $renice = false;
399         if (!$renice) {
400             require_once 'System.php';
401             $renice = System::which('renice');
402         }
403         
404         // phpinfo();exit;
405         
406         
407         $tn =  $this->tempName('stdout', true);
408         $tne =  $this->tempName('stderr', true);
409         $descriptorspec = array(
410             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
411             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
412             2 => array("file", $tne, 'w'),   // stderr is a file to 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                 'oute' => $tne,
463                 'cmd' => $cmd,
464                 'email' => $email,
465                 'pipes' => $pipes,
466                 'notify_id' => $id,
467                 'started' => time()
468             
469                 
470         );
471         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
472     }
473     
474     function poolfree()
475     {
476         $pool = array();
477         clearstatcache();
478          
479         foreach($this->pool as $p) {
480              
481             //echo "CHECK PID: " . $p['pid'] . "\n";
482             
483             
484             $info =  proc_get_status($p['proc']);
485             //var_dump($info);
486             
487             // update if necessday.
488             if ($info['pid'] && $p['pid'] != $info['pid']) {
489                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
490                 $p['pid'] = $info['pid'];
491             }
492             
493             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
494             
495             if ($info['running']) {
496             
497                 //if (file_exists('/proc/'.$p['pid'])) {
498                 $runtime = time() - $p['started'];
499                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
500                 if ($runtime > $this->maxruntime) {
501                     
502                     proc_terminate($p['proc'], 9);
503                     //fclose($p['pipes'][1]);
504                     fclose($p['pipes'][0]);
505                     
506                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
507                     @unlink($p['out']);
508                     @unlink($p['oute']);
509                     
510                     // schedule again
511                     $w = DB_DataObject::factory($this->table);
512                     $w->get($p['notify_id']);
513                     $ww = clone($w);
514                     if ($this->log_events) {
515                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
516                     }
517                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
518                     $w->update($ww);
519                     
520                     continue;
521                 }
522                 
523                 $pool[] = $p;
524                 continue;
525             }
526             fclose($p['pipes'][0]);
527             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
528             //fclose($p['pipes'][1]);
529             
530             proc_close($p['proc']);
531              sleep(1);
532             clearstatcache();
533             if (file_exists('/proc/'. $p['pid'])) {
534                 $this->logecho("proc PID={$p['pid']} still here - trying to wait");
535                 pcntl_waitpid($p['pid'], $status, WNOHANG);
536             }
537
538             //clearstatcache();
539             //if (file_exists('/proc/'.$p['pid'])) {
540             //    $pool[] = $p;
541             //    continue;
542             //}
543             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
544             @unlink($p['out']);
545             @unlink($p['oute']);
546             // at this point we could pop onto the queue the 
547             $this->popQueueDomain($p['email']);
548             
549             //unlink($p['out']);
550         }
551         $this->logecho("POOL SIZE: ". count($pool) );
552         $this->pool = $pool;
553         if (count($pool) < $this->max_pool_size) {
554             return true;
555         }
556         return false;
557         
558     }
559     /**
560      * see if pool is already trying to deliver to this domain.?
561      * -- if so it get's pushed to the end of the queue.
562      *
563      */
564     function poolHasDomain($email)
565     {
566         $ret = 0;
567         $ea = explode('@',$email);
568         $dom = strtolower(array_pop($ea));
569         foreach($this->pool as $p) {
570             $ea = explode('@',$p['email']);
571             $mdom = strtolower(array_pop($ea));
572             if ($mdom == $dom) {
573                 $ret++;
574             }
575         }
576         return $ret;
577         
578     }
579     function popQueueDomain($email)
580     {
581         $ea = explode('@',$email);
582         $dom = strtolower(array_pop($ea));
583         if (empty($this->domain_queue[$dom])) {
584             return;
585         }
586         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
587         
588     }
589     
590     function pushQueueDomain($e, $email)
591     {
592         if ($this->domain_queue === false) {
593             $this->next_queue[] = $e;
594             return;
595         }
596         
597         $ea = explode('@',$email);
598         $dom = strtolower(array_pop($ea));
599         if (!isset($this->domain_queue[$dom])) {
600             $this->domain_queue[$dom] = array();
601         }
602         $this->domain_queue[$dom][] = $e;
603     }
604     function remainingDomainQueue()
605     {
606         $ret = array();
607         foreach($this->domain_queue as $dom => $ar) {
608             $ret = array_merge($ret, $ar);
609         }
610         $this->domain_queue = false;
611         return $ret;
612     }
613     function clearOld()
614      {
615           if ($this->server->isFirstServer()) {
616             
617             $p = DB_DataObject::factory($this->table);
618             $p->whereAdd("
619                 sent < '2000-01-01'
620                 and
621                 event_id = 0
622                 and
623                 act_start < NOW() - INTERVAL {$this->clear_interval}
624             ");
625            // $p->limit(1000);
626             if ($p->count()) {
627                 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
628                 $p = DB_DataObject::factory($this->table);
629                 $p->query("
630                     UPDATE
631                         {$this->table}
632                     SET
633                         sent = NOW(),
634                         msgid = '',
635                         event_id = {$ev->id}
636                     WHERE
637                         sent < '2000-01-01'
638                         and
639                         event_id = 0
640                         and
641                         act_start < NOW() - INTERVAL {$this->clear_interval}
642                     LIMIT
643                         1000
644                 ");
645                 
646             }
647         }
648      }
649     
650
651     function output()
652     {
653         $this->logecho("DONE");
654         exit;
655     }
656     function logecho($str)
657     {
658         echo date("Y-m-d H:i:s - ") . $str . "\n";
659     }
660 }