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