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.. (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         '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 parseArgs(&$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         
138         if (!empty($opts['old'])) {
139             $opts['list'] = 1; // force listing..
140         }
141         
142         $this->force = empty($opts['force']) ? 0 : 1;
143      
144         if (!empty($opts['send-to'])) {
145             $this->send_to = $opts['send-to'];
146         }
147     }
148     
149     
150     function get($r,$opts)    
151     {
152         $this->parseArgs($opts); 
153          
154         //date_default_timezone_set('UTC');
155        // phpinfo();exit;
156         
157      
158         
159         $w = DB_DataObject::factory('core_notify_recur');
160         if (is_a($w, 'DB_DataObject')) {
161             $w->generateNotifications();
162         }
163         if (!empty($opts['generate'])) {
164             $w = DB_DataObject::factory($opts['generate']);
165             if (is_a($w, 'DB_DataObject')) {
166                 $w->generateNotifications();
167             }
168             exit;
169             
170             
171         }
172      
173         //DB_DataObject::debugLevel(1);
174         $w = DB_DataObject::factory($this->table);
175         
176         if (!empty($opts['old'])) {
177             // show old and new...
178             
179             $w->orderBy('act_when DESC'); // latest first
180             $w->limit($opts['limit']); // we can run 
181             
182         } else {   
183             // standard
184             
185             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
186             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
187             
188             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
189             if (!$this->force) {
190                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
191             }
192     
193             $w->orderBy('act_when ASC'); // oldest first.
194             
195             $this->logecho("QUEUE is {$w->count()} only runing " . ((int) $opts['limit']));
196             
197             $w->limit($opts['limit']); // we can run 1000 ...
198         }
199         
200         if (!empty($this->evtype)) {
201             $w->evtype = $this->evtype;
202         }
203         
204         $w->autoJoin();
205         
206         
207         $ar = array(); // $w->fetchAll();
208         
209         if (!empty($opts['list'])) {
210             if (empty($ar)) {
211                 die("Nothing in Queue\n");
212             }
213             foreach($ar as $w) {
214                 $o = $w->object();
215                 
216                 
217                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
218                         $o->toEventString()."    ". $w->status()  );
219             }
220             exit;
221         }
222         
223         //echo "BATCH SIZE: ".  count($ar) . "\n";
224         $pushed = array();
225         $requeue = array();
226         while (true) {
227             if ($w->fetch()) {
228                 $ar[] = clone($w);
229             }
230             
231             $this->logecho("BATCH SIZE: ".  count($ar) );
232             
233             if (empty($ar)) {
234                 $this->logecho("COMPLETED MAIN QUEUE - running delated");
235                 
236                 if (empty($pushed)) {
237                     break;
238                 }
239                 $ar = $pushed;
240                 $pushed = false;
241                 continue;
242             }
243             
244             
245             $p = array_shift($ar);
246             if (!$this->poolfree()) {
247                 array_unshift($ar,$p); /// put it back on..
248                 sleep(3);
249                 continue;
250             }
251             if ($this->poolHasDomain($p->person()->email) > $this->max_to_domain) {
252                 
253                 if ($pushed === false) {
254                     // we only try once to requeue..
255                     $requeue[] = $p;
256                     continue;
257                 }
258                 $pushed[] = $p;
259                 
260                 
261                 //sleep(3);
262                 continue;
263             }
264             
265             
266             $this->run($p->id,$p->person()->email);
267             
268             
269             
270         }
271         
272         // we should have a time limit here...
273         while(count($this->pool)) {
274             $this->poolfree();
275              sleep(3);
276         }
277          
278         foreach($requeue as $p) {
279             $pp = clone($p);
280             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
281             $p->update($pp);
282             
283         }
284         
285         
286         $this->logecho("DONE");
287         exit;
288     }
289     
290     function run($id, $email, $cmdOpts="")
291     {
292         
293         static $renice = false;
294         if (!$renice) {
295             require_once 'System.php';
296             $renice = System::which('renice');
297         }
298         
299         // phpinfo();exit;
300         $tnx = tempnam(ini_get('session.save_path'),'stdout');
301         unlink($tnx);
302         $tn =  $tnx . '.stdout';
303         $descriptorspec = array(
304             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
305             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
306             2 => array("pipe", "w") // stderr is a file to write to
307          );
308         
309         static $php = false;
310         if (!$php) {
311             require_once 'System.php';
312             $php = System::which('php');
313         }
314         
315         $sn =  $_SERVER["SCRIPT_NAME"];
316         
317         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
318         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
319         if ($this->force) {
320             $app .= ' -f';
321         }
322         if (!empty($this->send_to)) {
323             $app .= ' --sent-to='.escapeshellarg($this->send_to);
324         }
325         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
326         
327        
328         $pipe = array();
329         $this->logecho("call proc_open $cmd");
330         
331         
332         if ($this->max_pool_size === 1) {
333             passthru($cmd);
334             return;
335         }
336         
337         
338         if (!empty($this->opts['dryrun'])) {
339             $this->logecho("DRY RUN");
340             return;
341         }
342         
343         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
344         $info =  proc_get_status($p);
345         
346         if ($this->nice_level !== false) { 
347             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
348             `$rcmd`;
349         } 
350         $this->pool[] = array(
351                 'proc' => $p,
352                 'pid' => $info['pid'],
353                 'out' => $tn,
354                 'cmd' => $cmd,
355                 'email' => $email,
356                 'pipes' => $pipes,
357                 'notify_id' => $id,
358                 'started' => time()
359             
360                 
361         );
362         $this->logecho("RUN ({$info['pid']}) $cmd ");
363     }
364     
365     function poolfree()
366     {
367         $pool = array();
368         clearstatcache();
369          
370         foreach($this->pool as $p) {
371              
372             //echo "CHECK PID: " . $p['pid'] . "\n";
373             $info =  proc_get_status($p['proc']);
374             //var_dump($info);
375             
376             // update if necessday.
377             if ($info['pid'] && $p['pid'] != $info['pid']) {
378                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
379                 $p['pid'] = $info['pid'];
380             }
381             
382             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
383             
384             if ($info['running']) {
385             
386                 //if (file_exists('/proc/'.$p['pid'])) {
387                 $runtime = time() - $p['started'];
388                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
389                 if ($runtime > $this->maxruntime) {
390                     
391                     proc_terminate($p['proc'], 9);
392                     //fclose($p['pipes'][1]);
393                     fclose($p['pipes'][0]);
394                     fclose($p['pipes'][2]);
395                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
396                     @unlink($p['out']);
397                     
398                     $w = DB_DataObject::factory($this->table);
399                     $w->get($p['notify_id']);
400                     $ww = clone($w);
401                     $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
402                     $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30  MINUTES'));
403                     $w->update($ww);
404                     
405                     
406                     continue;
407                 }
408                 
409                 $pool[] = $p;
410                 continue;
411             }
412             fclose($p['pipes'][0]);
413             fclose($p['pipes'][2]);
414             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
415             //fclose($p['pipes'][1]);
416             
417             proc_close($p['proc']);
418             
419             
420             //clearstatcache();
421             //if (file_exists('/proc/'.$p['pid'])) {
422             //    $pool[] = $p;
423             //    continue;
424             //}
425             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
426             @unlink($p['out']);
427             //unlink($p['out']);
428         }
429         $this->logecho("POOL SIZE: ". count($pool) );
430         $this->pool = $pool;
431         if (count($pool) < $this->max_pool_size) {
432             return true;
433         }
434         return false;
435         
436     }
437     /**
438      * see if pool is already trying to deliver to this domain.?
439      * -- if so it get's pushed to the end of the queue.
440      *
441      */
442     function poolHasDomain($email)
443     {
444         $ret = 0;
445         $dom = strtolower(array_pop(explode('@',$email)));
446         foreach($this->pool as $p) {
447             $mdom = strtolower(array_pop(explode('@',$p['email'])));
448             if ($mdom == $dom) {
449                 $ret++;
450             }
451         }
452         return $ret;
453         
454     }
455
456     function output()
457     {
458         $this->logecho("DONE");
459         exit;
460     }
461     function logecho($str)
462     {
463         echo date("Y-m-d H:i:s - ") . $str . "\n";
464     }
465 }