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