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' OR sent IS NULL"); // 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 = $p->sqlValue('NOW + INTERVAL 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         
290         static $php = false;
291         if (!$php) {
292             require_once 'System.php';
293             $php = System::which('php');
294         }
295         
296         $sn =  $_SERVER["SCRIPT_NAME"];
297         
298         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
299         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
300         if ($this->force) {
301             $app .= ' -f';
302         }
303         if (!empty($this->send_to)) {
304             $app .= ' --sent-to='.escapeshellarg($this->send_to);
305         }
306         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
307         
308        
309         $pipe = array();
310         echo "call proc_open $cmd\n";
311         
312         
313         if ($this->max_pool_size === 1) {
314             passthru($cmd);
315             return;
316         }
317         
318         
319         if (!empty($this->opts['dryrun'])) {
320             echo "DRY RUN\n";
321             return;
322         }
323         
324         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
325         $info =  proc_get_status($p);
326         
327         if ($this->nice_level !== false) { 
328             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
329             `$rcmd`;
330         } 
331         $this->pool[] = array(
332                 'proc' => $p,
333                 'pid' => $info['pid'],
334                 'out' => $tn,
335                 'cmd' => $cmd,
336                 'email' => $email,
337                 'pipes' => $pipes,
338                 'started' => time()
339             
340                 
341         );
342         echo "RUN ({$info['pid']}) $cmd  \n";
343     }
344     
345     function poolfree()
346     {
347         $pool = array();
348         clearstatcache();
349         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
350         
351         foreach($this->pool as $p) {
352              
353             //echo "CHECK PID: " . $p['pid'] . "\n";
354             $info =  proc_get_status($p['proc']);
355             //var_dump($info);
356             
357             // update if necessday.
358             if ($info['pid'] && $p['pid'] != $info['pid']) {
359                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
360                 $p['pid'] = $info['pid'];
361             }
362             
363             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
364             
365             if ($info['running']) {
366             
367                 //if (file_exists('/proc/'.$p['pid'])) {
368                 $runtime = time() - $p['started'];
369                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
370                 if ($runtime > $maxruntime) {
371                     
372                     proc_terminate($p['proc'], 9);
373                     //fclose($p['pipes'][1]);
374                     fclose($p['pipes'][0]);
375                     fclose($p['pipes'][2]);
376                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
377                     @unlink($p['out']);
378                     
379                     continue;
380                 }
381                 
382                 $pool[] = $p;
383                 continue;
384             }
385             fclose($p['pipes'][0]);
386             fclose($p['pipes'][2]);
387             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
388             //fclose($p['pipes'][1]);
389             
390             proc_close($p['proc']);
391             
392             
393             //clearstatcache();
394             //if (file_exists('/proc/'.$p['pid'])) {
395             //    $pool[] = $p;
396             //    continue;
397             //}
398             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
399             @unlink($p['out']);
400             //unlink($p['out']);
401         }
402         echo "POOL SIZE: ". count($pool) ."\n";
403         $this->pool = $pool;
404         if (count($pool) < $this->max_pool_size) {
405             return true;
406         }
407         return false;
408         
409     }
410     /**
411      * see if pool is already trying to deliver to this domain.?
412      * -- if so it get's pushed to the end of the queue.
413      *
414      */
415     function poolHasDomain($email)
416     {
417         $ret = 0;
418         $dom = strtolower(array_pop(explode('@',$email)));
419         foreach($this->pool as $p) {
420             $mdom = strtolower(array_pop(explode('@',$p['email'])));
421             if ($mdom == $dom) {
422                 $ret++;
423             }
424         }
425         return $ret;
426         
427     }
428
429     function output()
430     {
431         die("Done\n");
432     }
433 }