more server check
[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         $descriptorspec = array(
405             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
406             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
407             2 => array("pipe", "w") // stderr is a file to write to
408          );
409         
410         static $php = false;
411         if (!$php) {
412             require_once 'System.php';
413             $php = System::which('php');
414         }
415         
416         $sn =  $_SERVER["SCRIPT_NAME"];
417         
418         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
419         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
420         if ($this->force) {
421             $app .= ' -f';
422         }
423         if (!empty($this->send_to)) {
424             $app .= ' --sent-to='.escapeshellarg($this->send_to);
425         }
426         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
427         
428        
429         $pipe = array();
430         //$this->logecho("call proc_open $cmd");
431         
432         
433         if ($this->max_pool_size === 1) {
434             $this->logecho("call passthru [{$email}] $cmd");
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 [{$email}] ({$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['email']} " . $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['email']} " .  $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         $this->domain_queue = false;
596         return $ret;
597     }
598     function clearOld()
599      {
600           if ($this->server->isFirstServer()) {
601             $p = DB_DataObject::factory($this->table);
602             $p->whereAdd("
603                 sent < '2000-01-01'
604                 and
605                 event_id = 0
606                 and
607                 act_start < NOW() - INTERVAL {$this->clear_interval}
608             ");
609            // $p->limit(1000);
610             if ($p->count()) {
611                 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
612                 $p = DB_DataObject::factory($this->table);
613                 $p->query("
614                     UPDATE
615                         {$this->table}
616                     SET
617                         sent = NOW(),
618                         msgid = '',
619                         event_id = {$ev->id}
620                     WHERE
621                         sent < '2000-01-01'
622                         and
623                         event_id = 0
624                         and
625                         act_start < NOW() - INTERVAL {$this->clear_interval}
626                     LIMIT
627                         1000
628                 ");
629                 
630             }
631         }
632      }
633     
634
635     function output()
636     {
637         $this->logecho("DONE");
638         exit;
639     }
640     function logecho($str)
641     {
642         echo date("Y-m-d H:i:s - ") . $str . "\n";
643     }
644 }