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