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