reduce number of update queries
[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         $p->whereAdd("
383                 sent < '2000-01-01'
384                 and
385                 event_id = 0
386                 and
387                 act_start < NOW() +  INTERVAL 3 HOUR 
388                 and
389                 server_id < 0"
390             
391         );
392         if ($p->count() < 1) {
393             return;
394         }
395         
396         // 6 seconds on this machne...
397         $p->query("
398             UPDATE
399                 {$this->table}
400             SET
401                 server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
402             WHERE
403                 sent < '2000-01-01'
404                 and
405                 event_id = 0
406                 and
407                 act_start < NOW() +  INTERVAL 3 HOUR 
408                 and
409                 server_id < 0
410             ORDER BY
411                 id ASC
412             LIMIT
413                 10000
414         ");
415
416         
417     }
418     
419     function run($id, $email='', $cmdOpts="")
420     {
421         
422         static $renice = false;
423         if (!$renice) {
424             require_once 'System.php';
425             $renice = System::which('renice');
426         }
427         
428         // phpinfo();exit;
429         
430         
431         $tn =  $this->tempName('stdout', true);
432         $descriptorspec = array(
433             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
434             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
435             2 => array("pipe", "w") // stderr is a file to write to
436          );
437         
438         static $php = false;
439         if (!$php) {
440             require_once 'System.php';
441             $php = System::which('php');
442         }
443         
444         $sn =  $_SERVER["SCRIPT_NAME"];
445         
446         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
447         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
448         if ($this->force) {
449             $app .= ' -f';
450         }
451         if (!empty($this->send_to)) {
452             $app .= ' --sent-to='.escapeshellarg($this->send_to);
453         }
454         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
455         
456        
457         $pipe = array();
458         //$this->logecho("call proc_open $cmd");
459         
460         
461         if ($this->max_pool_size === 1) {
462             $this->logecho("call passthru [{$email}] $cmd");
463             passthru($cmd);
464             return;
465         }
466         
467         
468         if (!empty($this->opts['dryrun'])) {
469             $this->logecho("DRY RUN");
470             return;
471         }
472         
473         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
474         $info =  proc_get_status($p);
475         
476         if ($this->nice_level !== false) { 
477             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
478             `$rcmd`;
479         } 
480         $this->pool[] = array(
481                 'proc' => $p,
482                 'pid' => $info['pid'],
483                 'out' => $tn,
484                 'cmd' => $cmd,
485                 'email' => $email,
486                 'pipes' => $pipes,
487                 'notify_id' => $id,
488                 'started' => time()
489             
490                 
491         );
492         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
493     }
494     
495     function poolfree()
496     {
497         $pool = array();
498         clearstatcache();
499          
500         foreach($this->pool as $p) {
501              
502             //echo "CHECK PID: " . $p['pid'] . "\n";
503             $info =  proc_get_status($p['proc']);
504             //var_dump($info);
505             
506             // update if necessday.
507             if ($info['pid'] && $p['pid'] != $info['pid']) {
508                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
509                 $p['pid'] = $info['pid'];
510             }
511             
512             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
513             
514             if ($info['running']) {
515             
516                 //if (file_exists('/proc/'.$p['pid'])) {
517                 $runtime = time() - $p['started'];
518                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
519                 if ($runtime > $this->maxruntime) {
520                     
521                     proc_terminate($p['proc'], 9);
522                     //fclose($p['pipes'][1]);
523                     fclose($p['pipes'][0]);
524                     fclose($p['pipes'][2]);
525                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
526                     @unlink($p['out']);
527                     
528                     // schedule again
529                     $w = DB_DataObject::factory($this->table);
530                     $w->get($p['notify_id']);
531                     $ww = clone($w);
532                     if ($this->log_events) {
533                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
534                     }
535                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
536                     $w->update($ww);
537                     
538                     continue;
539                 }
540                 
541                 $pool[] = $p;
542                 continue;
543             }
544             fclose($p['pipes'][0]);
545             fclose($p['pipes'][2]);
546             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
547             //fclose($p['pipes'][1]);
548             
549             proc_close($p['proc']);
550             
551             
552             //clearstatcache();
553             //if (file_exists('/proc/'.$p['pid'])) {
554             //    $pool[] = $p;
555             //    continue;
556             //}
557             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
558             @unlink($p['out']);
559             // at this point we could pop onto the queue the 
560             $this->popQueueDomain($p['email']);
561             
562             //unlink($p['out']);
563         }
564         $this->logecho("POOL SIZE: ". count($pool) );
565         $this->pool = $pool;
566         if (count($pool) < $this->max_pool_size) {
567             return true;
568         }
569         return false;
570         
571     }
572     /**
573      * see if pool is already trying to deliver to this domain.?
574      * -- if so it get's pushed to the end of the queue.
575      *
576      */
577     function poolHasDomain($email)
578     {
579         $ret = 0;
580         $ea = explode('@',$email);
581         $dom = strtolower(array_pop($ea));
582         foreach($this->pool as $p) {
583             $ea = explode('@',$p['email']);
584             $mdom = strtolower(array_pop($ea));
585             if ($mdom == $dom) {
586                 $ret++;
587             }
588         }
589         return $ret;
590         
591     }
592     function popQueueDomain($email)
593     {
594         $ea = explode('@',$email);
595         $dom = strtolower(array_pop($ea));
596         if (empty($this->domain_queue[$dom])) {
597             return;
598         }
599         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
600         
601     }
602     
603     function pushQueueDomain($e, $email)
604     {
605         if ($this->domain_queue === false) {
606             $this->next_queue[] = $e;
607             return;
608         }
609         
610         $ea = explode('@',$email);
611         $dom = strtolower(array_pop($ea));
612         if (!isset($this->domain_queue[$dom])) {
613             $this->domain_queue[$dom] = array();
614         }
615         $this->domain_queue[$dom][] = $e;
616     }
617     function remainingDomainQueue()
618     {
619         $ret = array();
620         foreach($this->domain_queue as $dom => $ar) {
621             $ret = array_merge($ret, $ar);
622         }
623         $this->domain_queue = false;
624         return $ret;
625     }
626     
627     
628
629     function output()
630     {
631         $this->logecho("DONE");
632         exit;
633     }
634     function logecho($str)
635     {
636         echo date("Y-m-d H:i:s - ") . $str . "\n";
637     }
638 }