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