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