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 = "Runs the notification queue (usually from cron)
20                         Normally used to sends out emails to anyone in the notification list.
21     
22                         /etc/cron.d/pman-core-notify
23                         * *  * * *     www-data     /usr/bin/php /home/gitlive/web.mtrack/admin.php  Core/Notify > /dev/null
24     
25 ";
26     
27     static $cli_opts = array(
28         'debug' => array(
29             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
30             'default' => 0,
31             'short' => 'v',
32             'min' => 1,
33             'max' => 1,
34             
35         ),
36         'list' => array(
37             'desc' => 'List message to send, do not send them..',
38             'default' => 0,
39             'short' => 'l',
40             'min' => 0,
41             'max' => 0,
42             
43         ),
44         'old' => array(
45             'desc' => 'Show old messages..',
46             'default' => 0,
47             'short' => 'o',
48             'min' => 0,
49             'max' => 0,
50             
51         ),
52         'force' => array(
53             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
54             'default' => 0,
55             'short' => 'f',
56             'min' => 0,
57             'max' => 0,
58         ),
59         'generate' => array(
60             'desc' => 'Generate notifications for a table, eg. cash_invoice',
61             'default' => '',
62             'short' => 'g',
63             'min' => 0,
64             'max' => 1,
65         ),
66          'limit' => array(
67             'desc' => 'Limit search for no. to send to ',
68             'default' => 50,
69             'short' => 'L',
70             'min' => 0,
71             'max' => 999,
72         ),
73         'dryrun' => array(
74             'desc' => 'Dry run - do not send.',
75             'default' => 0,
76             'short' => 'D',
77             'min' => 0,
78             'max' => 0,
79         ),
80     );
81     
82     var $max_pool_size = 10;
83     
84     var $table = 'core_notify';
85     var $target = 'Core/NotifySend';
86     var $evtype = ''; // any notification...
87                     // this script should only handle EMAIL notifications..
88     var $force = false;
89     function getAuth()
90     {
91         $ff = HTML_FlexyFramework::get();
92         if (!$ff->cli) {
93             die("access denied");
94         }
95         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
96         return true;
97         
98     }
99     
100     var $pool = array();
101     
102     function get($r,$opts)    
103     {
104         if ($opts['debug']) {
105             DB_DataObject::debugLevel($opts['debug']);
106             print_r($opts);
107         }
108         
109         
110         //date_default_timezone_set('UTC');
111        // phpinfo();exit;
112         $showold = !empty($opts['old']);
113         if (!empty($opts['old'])) {
114             $opts['list'] = 1; // force listing..
115         }
116         
117         $this->force = empty($opts['force']) ? 0 : 1;
118      
119         if (!empty($opts['send-to'])) {
120             $this->send_to = $opts['send-to'];
121         }
122      
123         
124         $w = DB_DataObject::factory('core_notify_recur');
125         if (is_a($w, 'DB_DataObject')) {
126             $w->generateNotifications();
127         }
128         if (!empty($opts['generate'])) {
129             $w = DB_DataObject::factory($opts['generate']);
130             if (is_a($w, 'DB_DataObject')) {
131                 $w->generateNotifications();
132             }
133             exit;
134             
135             
136         }
137      
138         //DB_DataObject::debugLevel(1);
139         $w = DB_DataObject::factory($this->table);
140         
141         if (!$showold) {
142             
143             // standard
144             
145             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
146             $w->whereAdd("sent < '1970-01-01'"); // eg.. sent is not valid..
147             
148             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
149             if (!$this->force) {
150                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
151             }
152     
153             $w->orderBy('act_when ASC'); // oldest first.
154             $w->limit(1000); // we can run 1000 ...
155         } else {
156             $w->orderBy('act_when DESC'); // latest first
157             $w->limit($opts['limit']); // we can run 1000 ...
158         }
159         if (!empty($this->evtype)) {
160             $w->evtype = $this->evtype;
161         }
162         
163         $w->autoJoin();
164         
165         
166         $ar = $w->fetchAll();
167         
168         if (!empty($opts['list'])) {
169             if (empty($ar)) {
170                 die("Nothing in Queue\n");
171             }
172             foreach($ar as $w) {
173                 $o = $w->object();
174                 
175                 
176                 echo "$w->id : $w->person_id_email email    : ".
177                         $o->toEventString()."    ". $w->status() . "\n";
178             }
179             exit;
180         }
181         
182         
183         $pushed = array();
184         while (true) {
185             if (empty($ar)) {
186                 break;
187             }
188             
189             
190             $p = array_shift($ar);
191             if (!$this->poolfree()) {
192                 array_unshift($ar,$p); /// put it back on..
193                 sleep(1);
194                 continue;
195             }
196             if ($this->poolHasDomain($p->person_id_email)) {
197                 if (in_array($p->person_id_email, $pushed)) {
198                     // it's been pushed to the end, and nothing has
199                     // been pushed since.s
200                     // give up, let the next run sort it out.
201                     break;
202                 }
203                 
204                 $ar[] = $p; // push it on the end..
205                 
206                 $pushed[] = $p->person_id_email;
207                 
208                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
209                 //sleep(3);
210                 continue;
211             }
212             
213             
214             $this->run($p->id,$p->person_id_email);
215             
216             
217             
218             $pushed = array();
219             
220         }
221         
222         // we should have a time limit here...
223         while(count($this->pool)) {
224             $this->poolfree();
225              sleep(1);
226         }
227         
228         die("DONE\n");
229     }
230     
231     function run($id, $email, $cmdOpts="")
232     {
233        // phpinfo();exit;
234         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
235         $descriptorspec = array(
236             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
237             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
238             2 => array("pipe", "w") // stderr is a file to write to
239          );
240         $php = $_SERVER["_"];
241         $sn =  $_SERVER["SCRIPT_NAME"];
242         
243         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
244         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
245         if ($this->force) {
246             $app .= ' -f';
247         }
248         if (!empty($this->send_to)) {
249             $app .= ' --sent-to='.escapeshellarg($this->send_to);
250         }
251         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
252         
253        
254         $pipe = array();
255         echo "call proc_open $cmd\n";
256         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
257         $info =  proc_get_status($p);
258         $this->pool[] = array(
259                 'proc' => $p,
260                 'pid' => $info['pid'],
261                 'out' => $tn,
262                 'cmd' => $cmd,
263                 'email' => $email,
264                 'pipes' => $pipes,
265                 'started' => time()
266             
267                 
268         );
269         echo "RUN ({$info['pid']}) $cmd  \n";
270     }
271     
272     function poolfree()
273     {
274         $pool = array();
275         clearstatcache();
276         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
277         
278         foreach($this->pool as $p) {
279              
280             //echo "CHECK PID: " . $p['pid'] . "\n";
281             $info =  proc_get_status($p['proc']);
282             //var_dump($info);
283             
284             // update if necessday.
285             if ($info['pid']) {
286                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
287                 $p['pid'] = $info['pid'];
288             }
289             
290             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
291             
292             if ($info['running']) {
293             
294                 //if (file_exists('/proc/'.$p['pid'])) {
295                 $runtime = time() - $p['started'];
296                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
297                 if ($runtime > $maxruntime) {
298                     
299                     proc_terminate($p['proc'], 9);
300                     //fclose($p['pipes'][1]);
301                     fclose($p['pipes'][0]);
302                     fclose($p['pipes'][2]);
303                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
304                     @unlink($p['out']);
305                     
306                     continue;
307                 }
308                 
309                 $pool[] = $p;
310                 continue;
311             }
312             fclose($p['pipes'][0]);
313             fclose($p['pipes'][2]);
314             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
315             //fclose($p['pipes'][1]);
316             
317             proc_close($p['proc']);
318             
319             
320             //clearstatcache();
321             //if (file_exists('/proc/'.$p['pid'])) {
322             //    $pool[] = $p;
323             //    continue;
324             //}
325             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
326             @unlink($p['out']);
327             //unlink($p['out']);
328         }
329         echo "POOL SIZE: ". count($pool) ."\n";
330         $this->pool = $pool;
331         if (count($pool) < $this->max_pool_size) {
332             return true;
333         }
334         return false;
335         
336     }
337     /**
338      * see if pool is already trying to deliver to this domain.?
339      * -- if so it get's pushed to the end of the queue.
340      *
341      */
342     function poolHasDomain($email)
343     {
344         $dom = strtolower(array_pop(explode('@',$email)));
345         foreach($this->pool as $p) {
346             $mdom = strtolower(array_pop(explode('@',$p['email'])));
347             if ($mdom == $dom) {
348                 return true;
349             }
350         }
351         return false;
352         
353     }
354
355     function output()
356     {
357         die("Done\n");
358     }
359 }