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