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' => 50,
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 $max_pool_size = 10;
90     
91     var $table = 'core_notify';
92     var $target = 'Core/NotifySend';
93     var $evtype = ''; // any notification...
94                     // this script should only handle EMAIL notifications..
95     var $force = false;
96     function getAuth()
97     {
98         $ff = HTML_FlexyFramework::get();
99         if (!$ff->cli) {
100             die("access denied");
101         }
102         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
103         return true;
104         
105     }
106     
107     var $pool = array();
108     
109     function get($r,$opts)    
110     {
111         if ($opts['debug']) {
112             DB_DataObject::debugLevel($opts['debug']);
113             print_r($opts);
114         }
115         $this->opts = $opts;
116         $this->max_pool_size = $opts['poolsize'];
117         
118         //date_default_timezone_set('UTC');
119        // phpinfo();exit;
120         $showold = !empty($opts['old']);
121         if (!empty($opts['old'])) {
122             $opts['list'] = 1; // force listing..
123         }
124         
125         $this->force = empty($opts['force']) ? 0 : 1;
126      
127         if (!empty($opts['send-to'])) {
128             $this->send_to = $opts['send-to'];
129         }
130      
131         
132         $w = DB_DataObject::factory('core_notify_recur');
133         if (is_a($w, 'DB_DataObject')) {
134             $w->generateNotifications();
135         }
136         if (!empty($opts['generate'])) {
137             $w = DB_DataObject::factory($opts['generate']);
138             if (is_a($w, 'DB_DataObject')) {
139                 $w->generateNotifications();
140             }
141             exit;
142             
143             
144         }
145      
146         //DB_DataObject::debugLevel(1);
147         $w = DB_DataObject::factory($this->table);
148         
149         if (!$showold) {
150             
151             // standard
152             
153             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
154             $w->whereAdd("sent < '1970-01-01'"); // eg.. sent is not valid..
155             
156             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
157             if (!$this->force) {
158                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
159             }
160     
161             $w->orderBy('act_when ASC'); // oldest first.
162             $w->limit($opts['limit']); // we can run 1000 ...
163         } else {
164             $w->orderBy('act_when DESC'); // latest first
165             $w->limit($opts['limit']); // we can run 1000 ...
166         }
167         if (!empty($this->evtype)) {
168             $w->evtype = $this->evtype;
169         }
170         
171         $w->autoJoin();
172         
173         
174         $ar = $w->fetchAll();
175         
176         if (!empty($opts['list'])) {
177             if (empty($ar)) {
178                 die("Nothing in Queue\n");
179             }
180             foreach($ar as $w) {
181                 $o = $w->object();
182                 
183                 
184                 echo "$w->id : $w->person_id_email email    : ".
185                         $o->toEventString()."    ". $w->status() . "\n";
186             }
187             exit;
188         }
189         
190         
191         $pushed = array();
192         while (true) {
193             if (empty($ar)) {
194                 break;
195             }
196             
197             
198             $p = array_shift($ar);
199             if (!$this->poolfree()) {
200                 array_unshift($ar,$p); /// put it back on..
201                 sleep(1);
202                 continue;
203             }
204             if ($this->poolHasDomain($p->person_id_email)) {
205                 if (in_array($p->person_id_email, $pushed)) {
206                     // it's been pushed to the end, and nothing has
207                     // been pushed since.s
208                     // give up, let the next run sort it out.
209                     break;
210                 }
211                 
212                 $ar[] = $p; // push it on the end..
213                 
214                 $pushed[] = $p->person_id_email;
215                 
216                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
217                 //sleep(3);
218                 continue;
219             }
220             
221             
222             $this->run($p->id,$p->person_id_email);
223             
224             
225             
226             $pushed = array();
227             
228         }
229         
230         // we should have a time limit here...
231         while(count($this->pool)) {
232             $this->poolfree();
233              sleep(1);
234         }
235         
236         die("DONE\n");
237     }
238     
239     function run($id, $email, $cmdOpts="")
240     {
241        // phpinfo();exit;
242         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
243         $descriptorspec = array(
244             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
245             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
246             2 => array("pipe", "w") // stderr is a file to write to
247          );
248         $php = $_SERVER["_"];
249         $sn =  $_SERVER["SCRIPT_NAME"];
250         
251         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
252         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
253         if ($this->force) {
254             $app .= ' -f';
255         }
256         if (!empty($this->send_to)) {
257             $app .= ' --sent-to='.escapeshellarg($this->send_to);
258         }
259         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
260         
261        
262         $pipe = array();
263         echo "call proc_open $cmd\n";
264         
265         
266         if (!empty($this->opts['dryrun'])) {
267             echo "DRY RUN\n";
268             return;
269         }
270         
271         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
272         $info =  proc_get_status($p);
273         $this->pool[] = array(
274                 'proc' => $p,
275                 'pid' => $info['pid'],
276                 'out' => $tn,
277                 'cmd' => $cmd,
278                 'email' => $email,
279                 'pipes' => $pipes,
280                 'started' => time()
281             
282                 
283         );
284         echo "RUN ({$info['pid']}) $cmd  \n";
285     }
286     
287     function poolfree()
288     {
289         $pool = array();
290         clearstatcache();
291         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
292         
293         foreach($this->pool as $p) {
294              
295             //echo "CHECK PID: " . $p['pid'] . "\n";
296             $info =  proc_get_status($p['proc']);
297             //var_dump($info);
298             
299             // update if necessday.
300             if ($info['pid']) {
301                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
302                 $p['pid'] = $info['pid'];
303             }
304             
305             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
306             
307             if ($info['running']) {
308             
309                 //if (file_exists('/proc/'.$p['pid'])) {
310                 $runtime = time() - $p['started'];
311                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
312                 if ($runtime > $maxruntime) {
313                     
314                     proc_terminate($p['proc'], 9);
315                     //fclose($p['pipes'][1]);
316                     fclose($p['pipes'][0]);
317                     fclose($p['pipes'][2]);
318                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
319                     @unlink($p['out']);
320                     
321                     continue;
322                 }
323                 
324                 $pool[] = $p;
325                 continue;
326             }
327             fclose($p['pipes'][0]);
328             fclose($p['pipes'][2]);
329             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
330             //fclose($p['pipes'][1]);
331             
332             proc_close($p['proc']);
333             
334             
335             //clearstatcache();
336             //if (file_exists('/proc/'.$p['pid'])) {
337             //    $pool[] = $p;
338             //    continue;
339             //}
340             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
341             @unlink($p['out']);
342             //unlink($p['out']);
343         }
344         echo "POOL SIZE: ". count($pool) ."\n";
345         $this->pool = $pool;
346         if (count($pool) < $this->max_pool_size) {
347             return true;
348         }
349         return false;
350         
351     }
352     /**
353      * see if pool is already trying to deliver to this domain.?
354      * -- if so it get's pushed to the end of the queue.
355      *
356      */
357     function poolHasDomain($email)
358     {
359         $dom = strtolower(array_pop(explode('@',$email)));
360         foreach($this->pool as $p) {
361             $mdom = strtolower(array_pop(explode('@',$p['email'])));
362             if ($mdom == $dom) {
363                 return true;
364             }
365         }
366         return false;
367         
368     }
369
370     function output()
371     {
372         die("Done\n");
373     }
374 }