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