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