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