fix terminate
[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             $w->orderBy('act_when ASC'); // oldest first.
230             $total = min($w->count(), $opts['limit']);
231             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
232             
233             $w->limit($opts['limit']); // we can run 1000 ...
234         }
235         
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                     $ev = $this->addEvent('NOTIFY', $p, 'BLACKLISTED  FROM our DB');
299                     $this->server->updateNotifyToNextServer($w,  strtotime('NOW +  5 MINUTES'),true);
300                    // $this->errorHandler( $ev->remarks);
301                 }
302                 
303                 continue;
304             }
305              
306             
307             if ($this->poolHasDomain($email) > $this->max_to_domain) {
308                 
309                 // push it to a 'domain specific queue'
310                 $this->logecho("REQUEING - maxed out that domain - {$email}");
311                 $this->pushQueueDomain($p, $email);
312                    
313                 //sleep(3);
314                 continue;
315             }
316             
317             
318             $this->run($p->id,$email);
319             
320             
321             
322         }
323         $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
324         if (!empty($this->next_queue)) {
325              
326             foreach($this->next_queue as $p) {
327                 if (false === $this->server->updateNotifyToNextServer($p)) {
328                     $p->updateState("????");
329                 }
330             }
331         }
332         
333         
334         $this->logecho("QUEUE COMPLETE - waiting for pool to end");
335         // we should have a time limit here...
336         while(count($this->pool)) {
337             $this->poolfree();
338             sleep(3);
339         }
340          
341         
342         
343         
344         $this->logecho("DONE");
345         exit;
346     }
347     
348     
349    
350     
351     // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
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      
390     
391     function run($id, $email='', $cmdOpts="")
392     {
393         
394         static $renice = false;
395         if (!$renice) {
396             require_once 'System.php';
397             $renice = System::which('renice');
398         }
399         
400         // phpinfo();exit;
401         
402         
403         $tn =  $this->tempName('stdout', true);
404         $tne =  $this->tempName('stderr', 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("file", $tne, 'w'),   // stderr is a file to write to
409           //  2 => array("pipe", "w") // stderr is a file to write to
410          );
411         
412         static $php = false;
413         if (!$php) {
414             require_once 'System.php';
415             $php = System::which('php');
416         }
417         
418         $sn =  $_SERVER["SCRIPT_NAME"];
419         
420         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
421         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
422         if ($this->force) {
423             $app .= ' -f';
424         }
425         if (!empty($this->send_to)) {
426             $app .= ' --sent-to='.escapeshellarg($this->send_to);
427         }
428         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
429         
430        
431         $pipe = array();
432         //$this->logecho("call proc_open $cmd");
433         
434         
435         if ($this->max_pool_size === 1) {
436             $this->logecho("call passthru [{$email}] $cmd");
437             passthru($cmd);
438             return;
439         }
440         
441         
442         if (!empty($this->opts['dryrun'])) {
443             $this->logecho("DRY RUN");
444             return;
445         }
446         
447         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
448         $info =  proc_get_status($p);
449         
450         if ($this->nice_level !== false) { 
451             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
452             `$rcmd`;
453         } 
454         $this->pool[] = array(
455                 'proc' => $p,
456                 'pid' => $info['pid'],
457                 'out' => $tn,
458                 'oute' => $tne,
459                 'cmd' => $cmd,
460                 'email' => $email,
461                 'pipes' => $pipes,
462                 'notify_id' => $id,
463                 'started' => time()
464             
465                 
466         );
467         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
468     }
469     
470     function poolfree()
471     {
472         $pool = array();
473         clearstatcache();
474          
475         foreach($this->pool as $p) {
476              
477             //echo "CHECK PID: " . $p['pid'] . "\n";
478             
479             
480             $info =  proc_get_status($p['proc']);
481             //var_dump($info);
482             
483             // update if necessday.
484             if ($info['pid'] && $p['pid'] != $info['pid']) {
485                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
486                 $p['pid'] = $info['pid'];
487             }
488             
489             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
490             
491             if ($info['running']) {
492             
493                 //if (file_exists('/proc/'.$p['pid'])) {
494                 $runtime = time() - $p['started'];
495                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
496                 if ($runtime > $this->maxruntime) {
497                     
498                     proc_terminate($p['proc'], 9);
499                     //fclose($p['pipes'][1]);
500                     fclose($p['pipes'][0]);
501                     
502                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
503                     @unlink($p['out']);
504                     @unlink($p['oute']);
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             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
524             //fclose($p['pipes'][1]);
525             
526             proc_close($p['proc']);
527             proc_terminate($p['proc'], 9);
528             sleep(1);
529             clearstatcache();
530             if (file_exists('/proc/'. $p['pid'])) {
531                 $this->logecho("proc PID={$p['pid']} still here - trying to wait");
532                 pcntl_waitpid($p['pid'], $status, WNOHANG);
533             }
534
535             //clearstatcache();
536             //if (file_exists('/proc/'.$p['pid'])) {
537             //    $pool[] = $p;
538             //    continue;
539             //}
540             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
541             @unlink($p['out']);
542             @unlink($p['oute']);
543             // at this point we could pop onto the queue the 
544             $this->popQueueDomain($p['email']);
545             
546             //unlink($p['out']);
547         }
548         $this->logecho("POOL SIZE: ". count($pool) );
549         $this->pool = $pool;
550         if (count($pool) < $this->max_pool_size) {
551             return true;
552         }
553         return false;
554         
555     }
556     /**
557      * see if pool is already trying to deliver to this domain.?
558      * -- if so it get's pushed to the end of the queue.
559      *
560      */
561     function poolHasDomain($email)
562     {
563         $ret = 0;
564         $ea = explode('@',$email);
565         $dom = strtolower(array_pop($ea));
566         foreach($this->pool as $p) {
567             $ea = explode('@',$p['email']);
568             $mdom = strtolower(array_pop($ea));
569             if ($mdom == $dom) {
570                 $ret++;
571             }
572         }
573         return $ret;
574         
575     }
576     function popQueueDomain($email)
577     {
578         $ea = explode('@',$email);
579         $dom = strtolower(array_pop($ea));
580         if (empty($this->domain_queue[$dom])) {
581             return;
582         }
583         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
584         
585     }
586     
587     function pushQueueDomain($e, $email)
588     {
589         if ($this->domain_queue === false) {
590             $this->next_queue[] = $e;
591             return;
592         }
593         
594         $ea = explode('@',$email);
595         $dom = strtolower(array_pop($ea));
596         if (!isset($this->domain_queue[$dom])) {
597             $this->domain_queue[$dom] = array();
598         }
599         $this->domain_queue[$dom][] = $e;
600     }
601     function remainingDomainQueue()
602     {
603         $ret = array();
604         foreach($this->domain_queue as $dom => $ar) {
605             $ret = array_merge($ret, $ar);
606         }
607         $this->domain_queue = false;
608         return $ret;
609     }
610     function clearOld()
611      {
612           if ($this->server->isFirstServer()) {
613             $p = DB_DataObject::factory($this->table);
614             $p->whereAdd("
615                 sent < '2000-01-01'
616                 and
617                 event_id = 0
618                 and
619                 act_start < NOW() - INTERVAL {$this->clear_interval}
620             ");
621            // $p->limit(1000);
622             if ($p->count()) {
623                 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
624                 $p = DB_DataObject::factory($this->table);
625                 $p->query("
626                     UPDATE
627                         {$this->table}
628                     SET
629                         sent = NOW(),
630                         msgid = '',
631                         event_id = {$ev->id}
632                     WHERE
633                         sent < '2000-01-01'
634                         and
635                         event_id = 0
636                         and
637                         act_start < NOW() - INTERVAL {$this->clear_interval}
638                     LIMIT
639                         1000
640                 ");
641                 
642             }
643         }
644      }
645     
646
647     function output()
648     {
649         $this->logecho("DONE");
650         exit;
651     }
652     function logecho($str)
653     {
654         echo date("Y-m-d H:i:s - ") . $str . "\n";
655     }
656 }