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