fix up cli
[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     
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             $w->whereAdd('act_when > sent'); // eg.. sent is not valid..
127             
128             if (!$this->force) {
129                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
130             }
131     
132             $w->orderBy('act_when ASC'); // oldest first.
133             $w->limit(1000); // we can run 1000 ...
134         } else {
135             $w->orderBy('act_when DESC'); // latest first
136             $w->limit(50); // we can run 1000 ...
137         }
138         if (!empty($this->evtype)) {
139             $w->evtype = $this->evtype;
140         }
141         
142         $w->autoJoin();
143         
144         
145         $ar = $w->fetchAll();
146         
147         if (!empty($opts['list'])) {
148             if (empty($ar)) {
149                 die("Nothing in Queue\n");
150             }
151             foreach($ar as $w) {
152                 $o = $w->object();
153                 
154                 
155                 echo "$w->id : $w->person_id_email email    : ".
156                         $o->toEventString()."    ". $w->status() . "\n";
157             }
158             exit;
159         }
160         
161         
162         $pushed = array();
163         while (true) {
164             if (empty($ar)) {
165                 break;
166             }
167             
168             
169             $p = array_shift($ar);
170             if (!$this->poolfree()) {
171                 array_unshift($ar,$p); /// put it back on..
172                 sleep(3);
173                 continue;
174             }
175             if ($this->poolHasDomain($p->person_id_email)) {
176                 if (in_array($p->person_id_email, $pushed)) {
177                     // it's been pushed to the end, and nothing has
178                     // been pushed since.
179                     // give up, let the next run sort it out.
180                     break;
181                 }
182                 
183                 $ar[] = $p; // push it on the end..
184                 
185                 $pushed[] = $p->person_id_email;
186                 
187                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
188                 sleep(3);
189                 continue;
190             }
191             
192             
193             $this->run($p->id,$p->person_id_email);
194             $pushed = array();
195             
196         }
197         
198         // we should have a time limit here...
199         while(count($this->pool)) {
200             $this->poolfree();
201             sleep(3);
202         }
203         
204         die("DONE\n");
205     }
206     
207     function run($id, $email, $cmdOpts="")
208     {
209        // phpinfo();exit;
210         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
211         $descriptorspec = array(
212             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
213             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
214             2 => array("pipe", "w") // stderr is a file to write to
215          );
216         $php = $_SERVER["_"];
217         $sn =  $_SERVER["SCRIPT_NAME"];
218         
219         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
220         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
221         if ($this->force) {
222             $app .= ' -f';
223         }
224         if (!empty($this->send_to)) {
225             $app .= ' --sent-to='.escapeshellarg($this->send_to);
226         }
227         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
228         
229        
230         $pipe = array();
231         echo "call proc_open $cmd\n";
232         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
233         $info =  proc_get_status($p);
234         $this->pool[] = array(
235                 'proc' => $p,
236                 'pid' => $info['pid'],
237                 'out' => $tn,
238                 'cmd' => $cmd,
239                 'email' => $email,
240                 'pipes' => $pipes,
241                 'started' => time()
242             
243                 
244         );
245         echo "RUN ({$info['pid']}) $cmd  \n";
246     }
247     
248     function poolfree()
249     {
250         $pool = array();
251         clearstatcache();
252         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
253         
254         foreach($this->pool as $p) {
255              
256             //echo "CHECK PID: " . $p['pid'] . "\n";
257             $info =  proc_get_status($p['proc']);
258             //var_dump($info);
259             
260             // update if necessday.
261             if ($info['pid']) {
262                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
263                 $p['pid'] = $info['pid'];
264             }
265             
266             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
267             
268             if ($info['running']) {
269             
270                 //if (file_exists('/proc/'.$p['pid'])) {
271                 $runtime = time() - $p['started'];
272                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
273                 if ($runtime > $maxruntime) {
274                     
275                     proc_terminate($p['proc'], 9);
276                     //fclose($p['pipes'][1]);
277                     fclose($p['pipes'][0]);
278                     fclose($p['pipes'][2]);
279                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
280                     @unlink($p['out']);
281                     
282                     continue;
283                 }
284                 
285                 $pool[] = $p;
286                 continue;
287             }
288             fclose($p['pipes'][0]);
289             fclose($p['pipes'][2]);
290             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
291             //fclose($p['pipes'][1]);
292             
293             proc_close($p['proc']);
294             
295             
296             //clearstatcache();
297             //if (file_exists('/proc/'.$p['pid'])) {
298             //    $pool[] = $p;
299             //    continue;
300             //}
301             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
302             @unlink($p['out']);
303             //unlink($p['out']);
304         }
305         echo "POOL SIZE: ". count($pool) ."\n";
306         $this->pool = $pool;
307         if (count($pool) < 10) {
308             return true;
309         }
310         return false;
311         
312     }
313     /**
314      * see if pool is already trying to deliver to this domain.?
315      * -- if so it get's pushed to the end of the queue.
316      *
317      */
318     function poolHasDomain($email)
319     {
320         $dom = strtolower(array_pop(explode('@',$email)));
321         foreach($this->pool as $p) {
322             $mdom = strtolower(array_pop(explode('@',$p['email'])));
323             if ($mdom == $dom) {
324                 return true;
325             }
326         }
327         return false;
328         
329     }
330
331     function output()
332     {
333         die("Done\n");
334     }
335 }