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