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