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