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