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