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