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