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