fix the count
[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         
196         if (!empty($opts['old'])) {
197             // show old and new...
198             
199             $w->orderBy('act_when DESC'); // latest first
200             $w->limit($opts['limit']); // we can run 
201             $total = min($w->count(), $opts['limit']);
202         } else {   
203             // standard
204             
205             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
206             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
207             
208             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
209             if (!$this->force) {
210                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
211             }
212     
213             $w->orderBy('act_when ASC'); // oldest first.
214             $total = min($w->count(), $opts['limit']);
215             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
216             
217             $w->limit($opts['limit']); // we can run 1000 ...
218         }
219         
220         if (!empty($this->evtype)) {
221             $w->evtype = $this->evtype;
222         }
223         
224         
225     
226         
227          
228         $w->autoJoin();
229         $w->find();
230         
231         
232         
233         if (!empty($opts['list'])) {
234             
235             
236             while ($w->fetch()) { 
237                 $o = $w->object();
238                 
239                 
240                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
241                         $o->toEventString()."    ". $w->status()  );
242             }
243             exit;
244         }
245         
246         //echo "BATCH SIZE: ".  count($ar) . "\n";
247        
248         
249         while (true) {
250             // only add if we don't have any queued up..
251             if (empty($this->queue) && $w->fetch()) {
252                 $this->queue[] = clone($w);
253                 $total--;
254             }
255             
256             $this->logecho("BATCH SIZE: Queue=".  count($this->queue) . " TOTAL = " . $total  );
257             
258             if (empty($this->queue)) {
259                 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
260                 if ($this->domain_queue !== false) {
261                     $this->queue  = $this->remainingDomainQueue();
262                      
263                     continue;
264                 }
265                 break; // nothing more in queue.. and no remaining one
266             }
267             
268             
269             $p = array_shift($this->queue);
270             if (!$this->poolfree()) {
271                 array_unshift($this->queue,$p); /// put it back on..
272                 sleep(3);
273                 continue;
274             }
275             $email = $p->person() ? $p->person()->email : $p->to_email;
276             
277             if ($this->poolHasDomain($email) > $this->max_to_domain) {
278                 
279                 // push it to a 'domain specific queue'
280                 $this->logecho("REQUEING - maxed out that domain - {$email}");
281                 $this->pushQueueDomain($p, $email);
282                   
283                 
284                 //sleep(3);
285                 continue;
286             }
287             
288             
289             $this->run($p->id,$email);
290             
291             
292             
293         }
294          $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
295         if (!empty($this->next_queue)) {
296              
297             foreach($this->next_queue as $p) {
298                 $pp = clone($p);
299                 $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
300                 $this->updateServer($p);
301                 $p->update($pp);
302                 
303             }
304         }
305         
306         
307         $this->logecho("QUEUE COMPLETE - waiting for pool to end");
308         // we should have a time limit here...
309         while(count($this->pool)) {
310             $this->poolfree();
311             sleep(3);
312         }
313          
314         
315         
316         
317         $this->logecho("DONE");
318         exit;
319     }
320     
321     // this sequentially distributes requeued emails.. - to other servers.
322     function updateServer($w)
323     {
324         $ff = HTML_FlexyFramework::get();
325         static $num = 0;
326         if (empty($ff->Core_Notify['servers'])) {
327             return;
328         }
329         $num++;
330         // next server..
331         $w->server_id = $num % count(array_keys($ff->Core_Notify['servers']));
332          
333     }
334   
335     
336     function generateNotifications()
337     {
338         // this should check each module for 'GenerateNotifications.php' class..
339         //and run it if found..
340         $ff = HTML_FlexyFramework::get();
341        
342         $disabled = explode(',', $ff->disable);
343
344         $modules = array_reverse($this->modulesList());
345         
346         // move 'project' one to the end...
347         
348         foreach ($modules as $module){
349             if(in_array($module, $disabled)){
350                 continue;
351             }
352             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
353             if(!file_exists($file)){
354                 continue;
355             }
356             
357             require_once $file;
358             $class = "Pman_{$module}_GenerateNotifications";
359             $x = new $class;
360             if(!method_exists($x, 'generate')){
361                 continue;
362             };
363             //echo "$module\n";
364             $x->generate($this);
365         }
366                 
367     
368     }
369     
370     function assignQueues()
371     {
372         $ff = HTML_FlexyFramework::get();
373         
374         if (empty($ff->Core_Notify['servers'])) {
375             return;
376         }
377         
378         $num_servers = count(array_keys($ff->Core_Notify['servers']));
379         $p = DB_DataObject::factory($this->table);
380         // 6 seconds on this machne...
381         $p->query("
382             UPDATE
383                 {$this->table}
384             SET
385                 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
386             WHERE
387                 sent < '2000-01-01'
388                 and
389                 event_id = 0
390                 and
391                 act_start < NOW()
392                 and
393                 server_id < 0
394             ORDER BY
395                 id ASC
396             LIMIT
397                 20000
398         ");
399
400         
401     }
402     
403     function run($id, $email='', $cmdOpts="")
404     {
405         
406         static $renice = false;
407         if (!$renice) {
408             require_once 'System.php';
409             $renice = System::which('renice');
410         }
411         
412         // phpinfo();exit;
413         
414         
415         $tn =  $this->tempName('stdout', true);
416         $descriptorspec = array(
417             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
418             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
419             2 => array("pipe", "w") // stderr is a file to write to
420          );
421         
422         static $php = false;
423         if (!$php) {
424             require_once 'System.php';
425             $php = System::which('php');
426         }
427         
428         $sn =  $_SERVER["SCRIPT_NAME"];
429         
430         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
431         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
432         if ($this->force) {
433             $app .= ' -f';
434         }
435         if (!empty($this->send_to)) {
436             $app .= ' --sent-to='.escapeshellarg($this->send_to);
437         }
438         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
439         
440        
441         $pipe = array();
442         //$this->logecho("call proc_open $cmd");
443         
444         
445         if ($this->max_pool_size === 1) {
446             this->logecho("call passthru [{$email}] $cmd");
447             passthru($cmd);
448             return;
449         }
450         
451         
452         if (!empty($this->opts['dryrun'])) {
453             $this->logecho("DRY RUN");
454             return;
455         }
456         
457         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
458         $info =  proc_get_status($p);
459         
460         if ($this->nice_level !== false) { 
461             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
462             `$rcmd`;
463         } 
464         $this->pool[] = array(
465                 'proc' => $p,
466                 'pid' => $info['pid'],
467                 'out' => $tn,
468                 'cmd' => $cmd,
469                 'email' => $email,
470                 'pipes' => $pipes,
471                 'notify_id' => $id,
472                 'started' => time()
473             
474                 
475         );
476         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
477     }
478     
479     function poolfree()
480     {
481         $pool = array();
482         clearstatcache();
483          
484         foreach($this->pool as $p) {
485              
486             //echo "CHECK PID: " . $p['pid'] . "\n";
487             $info =  proc_get_status($p['proc']);
488             //var_dump($info);
489             
490             // update if necessday.
491             if ($info['pid'] && $p['pid'] != $info['pid']) {
492                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
493                 $p['pid'] = $info['pid'];
494             }
495             
496             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
497             
498             if ($info['running']) {
499             
500                 //if (file_exists('/proc/'.$p['pid'])) {
501                 $runtime = time() - $p['started'];
502                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
503                 if ($runtime > $this->maxruntime) {
504                     
505                     proc_terminate($p['proc'], 9);
506                     //fclose($p['pipes'][1]);
507                     fclose($p['pipes'][0]);
508                     fclose($p['pipes'][2]);
509                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
510                     @unlink($p['out']);
511                     
512                     // schedule again
513                     $w = DB_DataObject::factory($this->table);
514                     $w->get($p['notify_id']);
515                     $ww = clone($w);
516                     if ($this->log_events) {
517                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
518                     }
519                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
520                     $w->update($ww);
521                     
522                     continue;
523                 }
524                 
525                 $pool[] = $p;
526                 continue;
527             }
528             fclose($p['pipes'][0]);
529             fclose($p['pipes'][2]);
530             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
531             //fclose($p['pipes'][1]);
532             
533             proc_close($p['proc']);
534             
535             
536             //clearstatcache();
537             //if (file_exists('/proc/'.$p['pid'])) {
538             //    $pool[] = $p;
539             //    continue;
540             //}
541             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
542             @unlink($p['out']);
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     
611     
612
613     function output()
614     {
615         $this->logecho("DONE");
616         exit;
617     }
618     function logecho($str)
619     {
620         echo date("Y-m-d H:i:s - ") . $str . "\n";
621     }
622 }