DataObjects/Core_notify_server.php
[Pman.Core] / Notify.php
index a35770a..850a9df 100644 (file)
@@ -56,13 +56,11 @@ class Pman_Core_Notify extends Pman
             'min' => 0,
             'max' => 0,
         ),
-        'generate' => array(
-            'desc' => 'Generate notifications for a table, eg. cash_invoice',
-            'default' => '',
-            'short' => 'g',
-            'min' => 0,
-            'max' => 1,
+       /* removed - use GenerateNotifcations.php hooked classes
+         'generate' =>  'Generate notifications for a table, eg. cash_invoice',
+            
         ),
+        */
          'limit' => array(
             'desc' => 'Limit search for no. to send to ',
             'default' => 1000,
@@ -99,14 +97,37 @@ class Pman_Core_Notify extends Pman
     var $max_to_domain = 10;
     
     /**
-     * @var $maxruntime - maximum time a child is allowed to run - defaut 2 minutes
+     * @var $maxruntime - maximum seconds a child is allowed to run - defaut 2 minutes
      */
     var $maxruntime = 120;
     
+    /**
+    * @var {Boolean} log_events - default true if events should be logged.
+    */
+    var $log_events = true;
+    /**
+    * @var {Number} try_again_minutes how long after failing to try again default = 30 if max runtime fails
+    */
+    var $try_again_minutes = 30;
+    
+    /**
+     * @var {String} table - the table that the class will query for notification events
+     */
     var $table = 'core_notify';
+    /**
+     * @var {String} target - the application that will run for each Row in the table (eg. Pman/Core/NotifySend)
+     */
     var $target = 'Core/NotifySend';
+    
+    
+    
     var $evtype = ''; // any notification...
                     // this script should only handle EMAIL notifications..
+    
+    var $server_id;
+    
+    
+    var $opts; 
     var $force = false;
     function getAuth()
     {
@@ -114,7 +135,7 @@ class Pman_Core_Notify extends Pman
         if (!$ff->cli) {
             die("access denied");
         }
-        HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
+        HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
         return true;
     }
     
@@ -146,34 +167,41 @@ class Pman_Core_Notify extends Pman
         }
     }
     
-    
-    function get($r,$opts)    
+    var $queue = array();
+    var $domain_queue = array(); // false to use nextquee
+    var $next_queue = array();
+
+   
+    function get($r,$opts=array())    
     {
         $this->parseArgs($opts); 
          
         //date_default_timezone_set('UTC');
-       // phpinfo();exit;
         
-     
         
-        $w = DB_DataObject::factory('core_notify_recur');
-        if (is_a($w, 'DB_DataObject')) {
-            $w->generateNotifications();
-        }
-        if (!empty($opts['generate'])) {
-            $w = DB_DataObject::factory($opts['generate']);
-            if (is_a($w, 'DB_DataObject')) {
-                $w->generateNotifications();
-            }
-            exit;
-            
-            
-        }
-     
+        $this->generateNotifications();
+        
+        $this->assignQueues();
+        
         //DB_DataObject::debugLevel(1);
         $w = DB_DataObject::factory($this->table);
         $total = 0;
         
+        
+        
+        $ff = HTML_FlexyFramework::get();
+        if (!empty($ff->Core_Notify['servers'])) {
+            if (!isset($ff->Core_Notify['servers'][gethostname()])) {
+                $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
+            }
+            $w->server_id = array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
+        }
+        if (!empty($this->evtype)) {
+            $w->evtype = $this->evtype;
+        }
+        
+        
+        
         if (!empty($opts['old'])) {
             // show old and new...
             
@@ -198,14 +226,19 @@ class Pman_Core_Notify extends Pman
             $w->limit($opts['limit']); // we can run 1000 ...
         }
         
-        if (!empty($this->evtype)) {
-            $w->evtype = $this->evtype;
-        }
         
+        
+    
+        
+         
         $w->autoJoin();
-        $w->find();
+        $total = $w->find();
+        
+        if (empty($total)) {
+            $this->logecho("Nothing In Queue - DONE");
+            exit;
+        }
         
-        $ar = array(); // $w->fetchAll();
         
         if (!empty($opts['list'])) {
             
@@ -221,74 +254,227 @@ class Pman_Core_Notify extends Pman
         }
         
         //echo "BATCH SIZE: ".  count($ar) . "\n";
-        $pushed = array();
-        $requeue = array();
+       
+        
         while (true) {
-            if ($w->fetch()) {
-                $ar[] = clone($w);
+            // only add if we don't have any queued up..
+            if (empty($this->queue) && $w->fetch()) {
+                $this->queue[] = clone($w);
                 $total--;
             }
+          
+            $this->logecho("BATCH SIZE: Queue=".  count($this->queue) . " TOTAL = " . $total  );
             
-            $this->logecho("BATCH SIZE: ".  (count($ar) + $total) );
-            
-            if (empty($ar)) {
-                $this->logecho("COMPLETED MAIN QUEUE - running delated");
-                
-                if (empty($pushed)) {
-                    break;
+            if (empty($this->queue)) {
+                $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
+                if ($this->domain_queue !== false) {
+                    $this->queue  = $this->remainingDomainQueue();
+                     
+                    continue;
                 }
-                $ar = $pushed;
-                $pushed = false;
-                continue;
+                break; // nothing more in queue.. and no remaining one
             }
             
             
-            $p = array_shift($ar);
+            $p = array_shift($this->queue);
             if (!$this->poolfree()) {
-                array_unshift($ar,$p); /// put it back on..
+                array_unshift($this->queue,$p); /// put it back on..
                 sleep(3);
                 continue;
             }
-            if ($this->poolHasDomain($p->person()->email) > $this->max_to_domain) {
-                
-                if ($pushed === false) {
-                    // we only try once to requeue..
-                    $requeue[] = $p;
-                    continue;
-                }
-                $pushed[] = $p;
+            // not sure what happesn if person email and to_email is empty!!?
+            $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
+            
+            $black = $this->isBlacklisted($email);
+            if ($black !== false) {
+                $this->logecho("DOMAIN blacklisted - {$email} - moving to another pool");
+                $this->updateServer($p, $black);
+                continue;
+            }
+             
+            
+            if ($this->poolHasDomain($email) > $this->max_to_domain) {
                 
+                // push it to a 'domain specific queue'
+                $this->logecho("REQUEING - maxed out that domain - {$email}");
+                $this->pushQueueDomain($p, $email);
+                  
                 
                 //sleep(3);
                 continue;
             }
             
             
-            $this->run($p->id,$p->person()->email);
+            $this->run($p->id,$email);
             
             
             
         }
+         $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
+        if (!empty($this->next_queue)) {
+             
+            foreach($this->next_queue as $p) {
+                $this->updateServer($p);
+            }
+        }
+        
         
+        $this->logecho("QUEUE COMPLETE - waiting for pool to end");
         // we should have a time limit here...
         while(count($this->pool)) {
             $this->poolfree();
-             sleep(3);
+            sleep(3);
         }
          
-        foreach($requeue as $p) {
-            $pp = clone($p);
-            $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
-            $p->update($pp);
-            
-        }
+        
         
         
         $this->logecho("DONE");
         exit;
     }
     
-    function run($id, $email, $cmdOpts="")
+    
+    function isBlacklisted($email)
+    {
+        // return current server id..
+        $ff = HTML_FlexyFramework::get();
+        //$this->logecho("CHECK BLACKLISTED - {$email}");
+        if (empty($ff->Core_Notify['servers'])) {
+            return false;
+        }
+      
+        if (!isset($ff->Core_Notify['servers'][gethostname()]['blacklisted'])) {
+            return false;
+        }
+       
+        // get the domain..
+        $ea = explode('@',$email);
+        $dom = strtolower(array_pop($ea));
+        
+        //$this->logecho("CHECK BLACKLISTED DOM - {$dom}");
+        if (!in_array($dom, $ff->Core_Notify['servers'][gethostname()]['blacklisted'] )) {
+            return false;
+        }
+        //$this->logecho("RETURN BLACKLISTED TRUE");
+        return array_search(gethostname(),array_keys($ff->Core_Notify['servers']));
+    }
+    
+    // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
+    function updateServer($ww, $exclude = -1)
+    {
+        $w = DB_DataObject::factory($ww->tableName());
+        $w->get($ww->id);
+        
+        $ff = HTML_FlexyFramework::get();
+        static $num = 0;
+        if (empty($ff->Core_Notify['servers'])) {
+            return;
+        }
+        $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
+        if ($exclude == $num ) {
+            $num = ($num+1) % count(array_keys($ff->Core_Notify['servers']));
+        }
+        // next server..
+        $pp = clone($w);
+        $w->server_id = $num;
+                    
+        $w->act_when = $w->sqlValue('NOW() + INTERVAL 1 MINUTE');
+        $w->update($pp);
+        
+         
+    }
+  
+    
+    function generateNotifications()
+    {
+        // this should check each module for 'GenerateNotifications.php' class..
+        //and run it if found..
+        $ff = HTML_FlexyFramework::get();
+       
+        $disabled = explode(',', $ff->disable);
+
+        $modules = array_reverse($this->modulesList());
+        
+        // move 'project' one to the end...
+        
+        foreach ($modules as $module){
+            if(in_array($module, $disabled)){
+                continue;
+            }
+            $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
+            if(!file_exists($file)){
+                continue;
+            }
+            
+            require_once $file;
+            $class = "Pman_{$module}_GenerateNotifications";
+            $x = new $class;
+            if(!method_exists($x, 'generate')){
+                continue;
+            };
+            //echo "$module\n";
+            $x->generate($this);
+        }
+                
+    
+    }
+    
+    function assignQueues()
+    {
+        $ff = HTML_FlexyFramework::get();
+        
+        if (empty($ff->Core_Notify['servers'])) {
+            return;
+        }
+        
+        if (!isset($ff->Core_Notify['servers'][gethostname()])) {
+            $this->jerr("Core_Notify['servers']['" . gethostname() ."'] is not set");
+        }
+        // only run this on the main server...
+        if (array_search(gethostname(),array_keys($ff->Core_Notify['servers'])) > 0) {
+            return;
+        }
+        
+        $num_servers = count(array_keys($ff->Core_Notify['servers']));
+        $p = DB_DataObject::factory($this->table);
+        $p->whereAdd("
+                sent < '2000-01-01'
+                and
+                event_id = 0
+                and
+                act_start < NOW() +  INTERVAL 3 HOUR 
+                and
+                server_id < 0"
+            
+        );
+        if ($p->count() < 1) {
+            return;
+        }
+         $p = DB_DataObject::factory($this->table);
+        // 6 seconds on this machne...
+        $p->query("
+            UPDATE
+                {$this->table}
+            SET
+                server_id = ((@row_number := CASE WHEN @row_number IS NULL THEN 0 ELSE @row_number END  +1) % {$num_servers})
+            WHERE
+                sent < '2000-01-01'
+                and
+                event_id = 0
+                and
+                act_start < NOW() +  INTERVAL 3 HOUR 
+                and
+                server_id < 0
+            ORDER BY
+                id ASC
+            LIMIT
+                10000
+        ");
+
+        
+    }
+    
+    function run($id, $email='', $cmdOpts="")
     {
         
         static $renice = false;
@@ -298,9 +484,9 @@ class Pman_Core_Notify extends Pman
         }
         
         // phpinfo();exit;
-        $tnx = tempnam(ini_get('session.save_path'),'stdout');
-        unlink($tnx);
-        $tn =  $tnx . '.stdout';
+        
+        
+        $tn =  $this->tempName('stdout', true);
         $descriptorspec = array(
             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
@@ -327,10 +513,11 @@ class Pman_Core_Notify extends Pman
         
        
         $pipe = array();
-        $this->logecho("call proc_open $cmd");
+        //$this->logecho("call proc_open $cmd");
         
         
         if ($this->max_pool_size === 1) {
+            $this->logecho("call passthru [{$email}] $cmd");
             passthru($cmd);
             return;
         }
@@ -360,7 +547,7 @@ class Pman_Core_Notify extends Pman
             
                 
         );
-        $this->logecho("RUN ({$info['pid']}) $cmd ");
+        $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
     }
     
     function poolfree()
@@ -393,17 +580,19 @@ class Pman_Core_Notify extends Pman
                     //fclose($p['pipes'][1]);
                     fclose($p['pipes'][0]);
                     fclose($p['pipes'][2]);
-                    $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
+                    $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']));
                     @unlink($p['out']);
                     
+                    // schedule again
                     $w = DB_DataObject::factory($this->table);
                     $w->get($p['notify_id']);
                     $ww = clone($w);
-                    $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
-                    $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30  MINUTES'));
+                    if ($this->log_events) {
+                        $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
+                    }
+                    $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
                     $w->update($ww);
                     
-                    
                     continue;
                 }
                 
@@ -423,8 +612,11 @@ class Pman_Core_Notify extends Pman
             //    $pool[] = $p;
             //    continue;
             //}
-            $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
+            $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
             @unlink($p['out']);
+            // at this point we could pop onto the queue the 
+            $this->popQueueDomain($p['email']);
+            
             //unlink($p['out']);
         }
         $this->logecho("POOL SIZE: ". count($pool) );
@@ -443,9 +635,11 @@ class Pman_Core_Notify extends Pman
     function poolHasDomain($email)
     {
         $ret = 0;
-        $dom = strtolower(array_pop(explode('@',$email)));
+        $ea = explode('@',$email);
+        $dom = strtolower(array_pop($ea));
         foreach($this->pool as $p) {
-            $mdom = strtolower(array_pop(explode('@',$p['email'])));
+            $ea = explode('@',$p['email']);
+            $mdom = strtolower(array_pop($ea));
             if ($mdom == $dom) {
                 $ret++;
             }
@@ -453,6 +647,42 @@ class Pman_Core_Notify extends Pman
         return $ret;
         
     }
+    function popQueueDomain($email)
+    {
+        $ea = explode('@',$email);
+        $dom = strtolower(array_pop($ea));
+        if (empty($this->domain_queue[$dom])) {
+            return;
+        }
+        array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
+        
+    }
+    
+    function pushQueueDomain($e, $email)
+    {
+        if ($this->domain_queue === false) {
+            $this->next_queue[] = $e;
+            return;
+        }
+        
+        $ea = explode('@',$email);
+        $dom = strtolower(array_pop($ea));
+        if (!isset($this->domain_queue[$dom])) {
+            $this->domain_queue[$dom] = array();
+        }
+        $this->domain_queue[$dom][] = $e;
+    }
+    function remainingDomainQueue()
+    {
+        $ret = array();
+        foreach($this->domain_queue as $dom => $ar) {
+            $ret = array_merge($ret, $ar);
+        }
+        $this->domain_queue = false;
+        return $ret;
+    }
+    
+    
 
     function output()
     {
@@ -463,4 +693,4 @@ class Pman_Core_Notify extends Pman
     {
         echo date("Y-m-d H:i:s - ") . $str . "\n";
     }
-}
\ No newline at end of file
+}