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