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