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