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