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