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