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         
165         if (!$showold) {
166             
167             // standard
168             
169             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
170             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
171             
172             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
173             if (!$this->force) {
174                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
175             }
176     
177             $w->orderBy('act_when ASC'); // oldest first.
178             
179             $this->Log("QUEUE is {$w->count()}");
180             
181             $w->limit($opts['limit']); // we can run 1000 ...
182         } else {
183             $w->orderBy('act_when DESC'); // latest first
184             $w->limit($opts['limit']); // we can run 1000 ...
185         }
186         if (!empty($this->evtype)) {
187             $w->evtype = $this->evtype;
188         }
189         
190         $w->autoJoin();
191         
192         
193         $ar = $w->fetchAll();
194         
195         if (!empty($opts['list'])) {
196             if (empty($ar)) {
197                 die("Nothing in Queue\n");
198             }
199             foreach($ar as $w) {
200                 $o = $w->object();
201                 
202                 
203                 $this->logecho("$w->id : $w->person_id_email email    : ".
204                         $o->toEventString()."    ". $w->status()  );
205             }
206             exit;
207         }
208         
209         //echo "BATCH SIZE: ".  count($ar) . "\n";
210         $pushed = array();
211         $requeue = array();
212         while (true) {
213             
214             
215             $this->logecho("BATCH SIZE: ".  count($ar) );
216             
217             if (empty($ar)) {
218                 $this->logecho("COMPLETED MAIN QUEUE - running delated");
219                 
220                 if (empty($pushed)) {
221                     break;
222                 }
223                 $ar = $pushed;
224                 $pushed = false;
225                 continue;
226             }
227             
228             
229             $p = array_shift($ar);
230             if (!$this->poolfree()) {
231                 array_unshift($ar,$p); /// put it back on..
232                 sleep(3);
233                 continue;
234             }
235             if ($this->poolHasDomain($p->person_id_email) > $this->max_to_domain) {
236                 
237                 if ($pushed === false) {
238                     // we only try once to requeue..
239                     $requeue[] = $p;
240                     continue;
241                 }
242                 $pushed[] = $p;
243                 
244                 
245                 //sleep(3);
246                 continue;
247             }
248             
249             
250             $this->run($p->id,$p->person_id_email);
251             
252             
253             
254         }
255         
256         // we should have a time limit here...
257         while(count($this->pool)) {
258             $this->poolfree();
259              sleep(3);
260         }
261          
262         foreach($requeue as $p) {
263             $pp = clone($p);
264             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
265             $p->update($pp);
266             
267         }
268         
269         
270         
271         die("DONE\n");
272     }
273     
274     function run($id, $email, $cmdOpts="")
275     {
276         
277         static $renice = false;
278         if (!$renice) {
279             require_once 'System.php';
280             $renice = System::which('renice');
281         }
282         
283         // phpinfo();exit;
284         $tnx = tempnam(ini_get('session.save_path'),'stdout');
285         unlink($tnx);
286         $tn =  $tnx . '.stdout';
287         $descriptorspec = array(
288             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
289             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
290             2 => array("pipe", "w") // stderr is a file to write to
291          );
292         
293         static $php = false;
294         if (!$php) {
295             require_once 'System.php';
296             $php = System::which('php');
297         }
298         
299         $sn =  $_SERVER["SCRIPT_NAME"];
300         
301         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
302         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
303         if ($this->force) {
304             $app .= ' -f';
305         }
306         if (!empty($this->send_to)) {
307             $app .= ' --sent-to='.escapeshellarg($this->send_to);
308         }
309         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
310         
311        
312         $pipe = array();
313         $this->logecho("call proc_open $cmd");
314         
315         
316         if ($this->max_pool_size === 1) {
317             passthru($cmd);
318             return;
319         }
320         
321         
322         if (!empty($this->opts['dryrun'])) {
323             $this->logecho("DRY RUN");
324             return;
325         }
326         
327         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
328         $info =  proc_get_status($p);
329         
330         if ($this->nice_level !== false) { 
331             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
332             `$rcmd`;
333         } 
334         $this->pool[] = array(
335                 'proc' => $p,
336                 'pid' => $info['pid'],
337                 'out' => $tn,
338                 'cmd' => $cmd,
339                 'email' => $email,
340                 'pipes' => $pipes,
341                 'started' => time()
342             
343                 
344         );
345         $this->logecho("RUN ({$info['pid']}) $cmd ");
346     }
347     
348     function poolfree()
349     {
350         $pool = array();
351         clearstatcache();
352         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
353         
354         foreach($this->pool as $p) {
355              
356             //echo "CHECK PID: " . $p['pid'] . "\n";
357             $info =  proc_get_status($p['proc']);
358             //var_dump($info);
359             
360             // update if necessday.
361             if ($info['pid'] && $p['pid'] != $info['pid']) {
362                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
363                 $p['pid'] = $info['pid'];
364             }
365             
366             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
367             
368             if ($info['running']) {
369             
370                 //if (file_exists('/proc/'.$p['pid'])) {
371                 $runtime = time() - $p['started'];
372                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
373                 if ($runtime > $maxruntime) {
374                     
375                     proc_terminate($p['proc'], 9);
376                     //fclose($p['pipes'][1]);
377                     fclose($p['pipes'][0]);
378                     fclose($p['pipes'][2]);
379                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
380                     @unlink($p['out']);
381                     
382                     continue;
383                 }
384                 
385                 $pool[] = $p;
386                 continue;
387             }
388             fclose($p['pipes'][0]);
389             fclose($p['pipes'][2]);
390             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
391             //fclose($p['pipes'][1]);
392             
393             proc_close($p['proc']);
394             
395             
396             //clearstatcache();
397             //if (file_exists('/proc/'.$p['pid'])) {
398             //    $pool[] = $p;
399             //    continue;
400             //}
401             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
402             @unlink($p['out']);
403             //unlink($p['out']);
404         }
405         $this->logecho("POOL SIZE: ". count($pool) );
406         $this->pool = $pool;
407         if (count($pool) < $this->max_pool_size) {
408             return true;
409         }
410         return false;
411         
412     }
413     /**
414      * see if pool is already trying to deliver to this domain.?
415      * -- if so it get's pushed to the end of the queue.
416      *
417      */
418     function poolHasDomain($email)
419     {
420         $ret = 0;
421         $dom = strtolower(array_pop(explode('@',$email)));
422         foreach($this->pool as $p) {
423             $mdom = strtolower(array_pop(explode('@',$p['email'])));
424             if ($mdom == $dom) {
425                 $ret++;
426             }
427         }
428         return $ret;
429         
430     }
431
432     function output()
433     {
434         die("Done\n");
435     }
436     function logecho($str)
437     {
438         echo date("Y-m-d H:i:s - $str\n");
439     }
440 }