Notify.php
[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..',
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         'generate' => array(
60             'desc' => 'Generate notifications for a table, eg. cash_invoice',
61             'default' => '',
62             'short' => 'g',
63             'min' => 0,
64             'max' => 1,
65         ),
66          'limit' => array(
67             'desc' => 'Limit search for no. to send to ',
68             'default' => 1000,
69             'short' => 'L',
70             'min' => 0,
71             'max' => 999,
72         ),
73         'dryrun' => array(
74             'desc' => 'Dry run - do not send.',
75             'default' => 0,
76             'short' => 'D',
77             'min' => 0,
78             'max' => 0,
79         ),
80         'poolsize' => array(
81             'desc' => 'Pool size',
82             'default' => 10,
83             'short' => 'P',
84             'min' => 0,
85             'max' => 100,
86         ),
87     );
88     /**
89      * @var $nice_level Unix 'nice' level to stop it jamming server up.
90      */
91     var $nice_level = false;
92     /**
93      * @var $max_pool_size maximum runners to start at once.
94      */
95     var $max_pool_size = 10;
96     /**
97      * @var $max_to_domain maximum connections to make to a single domain
98      */
99     var $max_to_domain = 10;
100     
101     /**
102      * @var $maxruntime - maximum time a child is allowed to run - defaut 2 minutes
103      */
104     var $maxruntime = 120;
105     
106     var $table = 'core_notify';
107     var $target = 'Core/NotifySend';
108     var $evtype = ''; // any notification...
109                     // this script should only handle EMAIL notifications..
110     var $force = false;
111     function getAuth()
112     {
113         $ff = HTML_FlexyFramework::get();
114         if (!$ff->cli) {
115             die("access denied");
116         }
117         HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
118         return true;
119     }
120     
121     var $pool = array();
122     
123     function get($r,$opts)    
124     {
125         if ($opts['debug']) {
126             DB_DataObject::debugLevel($opts['debug']);
127             print_r($opts);
128         }
129         $this->opts = $opts;
130         if (!empty($opts['poolsize'])) {
131             $this->max_pool_size = $opts['poolsize'];
132         }
133         
134         if (empty($opts['limit'])) {
135             $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
136         }
137         //date_default_timezone_set('UTC');
138        // phpinfo();exit;
139         $showold = !empty($opts['old']);
140         if (!empty($opts['old'])) {
141             $opts['list'] = 1; // force listing..
142         }
143         
144         $this->force = empty($opts['force']) ? 0 : 1;
145      
146         if (!empty($opts['send-to'])) {
147             $this->send_to = $opts['send-to'];
148         }
149      
150         
151         $w = DB_DataObject::factory('core_notify_recur');
152         if (is_a($w, 'DB_DataObject')) {
153             $w->generateNotifications();
154         }
155         if (!empty($opts['generate'])) {
156             $w = DB_DataObject::factory($opts['generate']);
157             if (is_a($w, 'DB_DataObject')) {
158                 $w->generateNotifications();
159             }
160             exit;
161             
162             
163         }
164      
165         //DB_DataObject::debugLevel(1);
166         $w = DB_DataObject::factory($this->table);
167         
168         
169         if (!$showold) {
170             
171             // standard
172             
173             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
174             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
175             
176             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
177             if (!$this->force) {
178                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
179             }
180     
181             $w->orderBy('act_when ASC'); // oldest first.
182             
183             $this->logecho("QUEUE is {$w->count()}");
184             
185             $w->limit($opts['limit']); // we can run 1000 ...
186         } else {
187             $w->orderBy('act_when DESC'); // latest first
188             $w->limit($opts['limit']); // we can run 1000 ...
189         }
190         if (!empty($this->evtype)) {
191             $w->evtype = $this->evtype;
192         }
193         
194         $w->autoJoin();
195         
196         
197         $ar = $w->fetchAll();
198         
199         if (!empty($opts['list'])) {
200             if (empty($ar)) {
201                 die("Nothing in Queue\n");
202             }
203             foreach($ar as $w) {
204                 $o = $w->object();
205                 
206                 
207                 $this->logecho("$w->id : $w->person_id_email email    : ".
208                         $o->toEventString()."    ". $w->status()  );
209             }
210             exit;
211         }
212         
213         //echo "BATCH SIZE: ".  count($ar) . "\n";
214         $pushed = array();
215         $requeue = array();
216         while (true) {
217             
218             
219             $this->logecho("BATCH SIZE: ".  count($ar) );
220             
221             if (empty($ar)) {
222                 $this->logecho("COMPLETED MAIN QUEUE - running delated");
223                 
224                 if (empty($pushed)) {
225                     break;
226                 }
227                 $ar = $pushed;
228                 $pushed = false;
229                 continue;
230             }
231             
232             
233             $p = array_shift($ar);
234             if (!$this->poolfree()) {
235                 array_unshift($ar,$p); /// put it back on..
236                 sleep(3);
237                 continue;
238             }
239             if ($this->poolHasDomain($p->person_id_email) > $this->max_to_domain) {
240                 
241                 if ($pushed === false) {
242                     // we only try once to requeue..
243                     $requeue[] = $p;
244                     continue;
245                 }
246                 $pushed[] = $p;
247                 
248                 
249                 //sleep(3);
250                 continue;
251             }
252             
253             
254             $this->run($p->id,$p->person_id_email);
255             
256             
257             
258         }
259         
260         // we should have a time limit here...
261         while(count($this->pool)) {
262             $this->poolfree();
263              sleep(3);
264         }
265          
266         foreach($requeue as $p) {
267             $pp = clone($p);
268             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
269             $p->update($pp);
270             
271         }
272         
273         
274         $this->logecho("DONE");
275         exit;
276     }
277     
278     function run($id, $email, $cmdOpts="")
279     {
280         
281         static $renice = false;
282         if (!$renice) {
283             require_once 'System.php';
284             $renice = System::which('renice');
285         }
286         
287         // phpinfo();exit;
288         $tnx = tempnam(ini_get('session.save_path'),'stdout');
289         unlink($tnx);
290         $tn =  $tnx . '.stdout';
291         $descriptorspec = array(
292             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
293             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
294             2 => array("pipe", "w") // stderr is a file to write to
295          );
296         
297         static $php = false;
298         if (!$php) {
299             require_once 'System.php';
300             $php = System::which('php');
301         }
302         
303         $sn =  $_SERVER["SCRIPT_NAME"];
304         
305         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
306         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
307         if ($this->force) {
308             $app .= ' -f';
309         }
310         if (!empty($this->send_to)) {
311             $app .= ' --sent-to='.escapeshellarg($this->send_to);
312         }
313         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
314         
315        
316         $pipe = array();
317         $this->logecho("call proc_open $cmd");
318         
319         
320         if ($this->max_pool_size === 1) {
321             passthru($cmd);
322             return;
323         }
324         
325         
326         if (!empty($this->opts['dryrun'])) {
327             $this->logecho("DRY RUN");
328             return;
329         }
330         
331         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
332         $info =  proc_get_status($p);
333         
334         if ($this->nice_level !== false) { 
335             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
336             `$rcmd`;
337         } 
338         $this->pool[] = array(
339                 'proc' => $p,
340                 'pid' => $info['pid'],
341                 'out' => $tn,
342                 'cmd' => $cmd,
343                 'email' => $email,
344                 'pipes' => $pipes,
345                 'started' => time()
346             
347                 
348         );
349         $this->logecho("RUN ({$info['pid']}) $cmd ");
350     }
351     
352     function poolfree()
353     {
354         $pool = array();
355         clearstatcache();
356          
357         foreach($this->pool as $p) {
358              
359             //echo "CHECK PID: " . $p['pid'] . "\n";
360             $info =  proc_get_status($p['proc']);
361             //var_dump($info);
362             
363             // update if necessday.
364             if ($info['pid'] && $p['pid'] != $info['pid']) {
365                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
366                 $p['pid'] = $info['pid'];
367             }
368             
369             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
370             
371             if ($info['running']) {
372             
373                 //if (file_exists('/proc/'.$p['pid'])) {
374                 $runtime = time() - $p['started'];
375                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
376                 if ($runtime > $this->maxruntime) {
377                     
378                     proc_terminate($p['proc'], 9);
379                     //fclose($p['pipes'][1]);
380                     fclose($p['pipes'][0]);
381                     fclose($p['pipes'][2]);
382                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
383                     @unlink($p['out']);
384                     
385                     continue;
386                 }
387                 
388                 $pool[] = $p;
389                 continue;
390             }
391             fclose($p['pipes'][0]);
392             fclose($p['pipes'][2]);
393             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
394             //fclose($p['pipes'][1]);
395             
396             proc_close($p['proc']);
397             
398             
399             //clearstatcache();
400             //if (file_exists('/proc/'.$p['pid'])) {
401             //    $pool[] = $p;
402             //    continue;
403             //}
404             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
405             @unlink($p['out']);
406             //unlink($p['out']);
407         }
408         $this->logecho("POOL SIZE: ". count($pool) );
409         $this->pool = $pool;
410         if (count($pool) < $this->max_pool_size) {
411             return true;
412         }
413         return false;
414         
415     }
416     /**
417      * see if pool is already trying to deliver to this domain.?
418      * -- if so it get's pushed to the end of the queue.
419      *
420      */
421     function poolHasDomain($email)
422     {
423         $ret = 0;
424         $dom = strtolower(array_pop(explode('@',$email)));
425         foreach($this->pool as $p) {
426             $mdom = strtolower(array_pop(explode('@',$p['email'])));
427             if ($mdom == $dom) {
428                 $ret++;
429             }
430         }
431         return $ret;
432         
433     }
434
435     function output()
436     {
437         $this->logecho("DONE");
438         exit;
439     }
440     function logecho($str)
441     {
442         echo date("Y-m-d H:i:s - ") . $str . "\n";
443     }
444 }