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