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