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