www.webdeveloper.com
Results 1 to 11 of 11

Thread: Drunken compairison?

  1. #1
    Join Date
    Jul 2007
    Posts
    357

    Drunken compairison?

    I have a script that connect to server. I need to be able to reconnect on a disconnect. The first reconnect part of my script works on the initial connect.. But if the connection is broken during the run, doesn't try to reconnect at all. Saying that 0 is greater than 120.

    PHP Code:
    <?php
    // Run "forever"
    set_time_limit(0);

    /**
     * Database setup, connection and db selection
     */
    include('dbInclude.php');

    /**
     * Error logging
     */
    include('classes/ErrorLogger.class.php');
    $err = new ErrorLogger('/var/www/html/agent/errors.log');

    /**
     * Configuration of reconnection stuff
     */
    $reconnect  1// Reconnect?
    $maxRetries 120// Max reconnect retries
    $retryWait  1000000// Wait before reconnection try in milliseconds
    $tries      0;

    // Open the socket to the Asterisk Manager
    $socket   = @fsockopen('127.0.0.1','5038'$errno$errstr);

    // Connection failed
    if(!$socket)
     {
      
    // Try again?
      
    if($reconnect === 1)
       {
        
    $tries  0;
        
    $socket 0;

        do
         {
          
    // have we hit the max # of retries?
          
    if($tries >= $maxRetries)
           {
            
    $err->logError('manager.php''fsocketopen''Could not connect after '.intval($tries).' retries');
            die(
    'Could not connect to the manager');
           }

          
    $socket   fsockopen('127.0.0.1','5038'$errno$errstr);

          ++
    $tries;
          
    usleep($retryWait);
         }while(!
    $socket);
       }
      else
       {
        
    $err->logError('manager.php''fsocketopen''Could not connect - No retries');
        die(
    'Could not connect to the manager');
       }
     }

    // Login to the manager and turn events on
    fputs($socket"Action: Login\r\n");
    fputs($socket"UserName: admin\r\n");
    fputs($socket"Secret: xxxx\r\n\r\n");
    fputs($socket"Events: on\r\n");

    // Initialize an empty buffer - prevent a warning
    $buffer   "";

    // Array to track the calls
    $calls     = array();

    stream_set_blocking($socketTRUE);

    // Loop the the CLI output
    do
     {
      
    // Double check our stream
      
    if(feof($socket))
       {
        
    // Try again?
        
    if($reconnect === 1)
         {
          
    $tries  0;
          
    $socket 0;

          do
           {
            
    // have we hit the max # of retries?
            
    if($tries >= $maxRetries)
             {
              
    $err->logError('manager.php''fsocketopen''Could not reconnect after '.$tries.' retries');
              die(
    'Could not reconnect to the manager');
             }

            
    $socket   = @fsockopen('127.0.0.1','5038'$errno$errstr);

            ++
    $tries;
            
    usleep($retryWait);
           }while(!
    $socket);

          
    // Login back in.
          
    fputs($socket"Action: Login\r\n");
          
    fputs($socket"UserName: admin\r\n");
          
    fputs($socket"Secret: xxxx\r\n\r\n");
          
    fputs($socket"Events: on\r\n");
         }
        else
         {
          
    $err->logError('manager.php''fsocketopen''Stream disconnected - No retries');
          die(
    'Stream to manager disconnected');
         }
       }
     }

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,387
    Do you know which comparison is failing? Where does it say that "0 is greater than 120"?
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Jul 2007
    Posts
    357
    It's the second one:
    PHP Code:
      // Double check our stream
      
    if(feof($socket))
       {
        
    // Try again?
        
    if($reconnect === 1)
         {
          
    $tries  0;
          
    $socket 0;

          do
           {
            
    // have we hit the max # of retries?
            
    if($tries >= $maxRetries)
             {
              
    $err->logError('manager.php''fsocketopen''Could not reconnect after '.$tries.' retries');
              die(
    'Could not reconnect to the manager');
             } 

  4. #4
    Join Date
    Jul 2007
    Posts
    357
    This quickly done version works fine..
    PHP Code:
    <?php
    // Run "forever"
    set_time_limit(0);

    /**
    * Configuration of reconnection stuff
    */
    $reconnect  1// Reconnect?
    $maxRetries 5// Max reconnect retries
    $retryWait  1000000// Wait before reconnection try in milliseconds
    $tries      0;
    $timeout    5;

    // Open the socket to the Asterisk Manager
    $socket   = @fsockopen('127.0.0.1','6667'$errno$errstr$timeout);

    // Connection failed
    if(!$socket)
     {
      
    // Try again?
      
    if($reconnect === 1)
       {
        
    $tries  0;
        
    $socket 0;

        do
         {
          
    // have we hit the max # of retries?
          
    if($tries >= $maxRetries)
           {
            
            die(
    'Could not connect to the manager after retrying');
           }

          
    $socket   = @fsockopen('127.0.0.1''6667'$errno$errstr$timeout);

          ++
    $tries;
          
    usleep($retryWait);
         }while(!
    $socket);
       }
      else
       {
        die(
    'Could not connect to the manager');
       }
    }

    echo 
    'Connected.',"\r\n";

    // Initialize an empty buffer - prevent a warning
    $buffer   "";

    stream_set_blocking($socketTRUE);

    // Loop the the CLI output
    do
     {
      
    // Double check our stream
      
    if(feof($socket))
       {
        echo 
    'Disconnected...',"\r\n";
        
    // Try again?
        
    if($reconnect === 1)
         {
          
    $tries  0;
          
    $socket 0;

          do
           {
            
    // have we hit the max # of retries?
            
    if($tries >= $maxRetries)
             {
              die(
    'Could not reconnect to the manager after '.$tries.' tries.');
             }

            
    $socket   = @fsockopen('127.0.0.1','6667'$errno$errstr$timeout);

            ++
    $tries;
            
    usleep($retryWait);
           }while(!
    $socket);
          echo 
    'Reconnected...',"\r\n";
         }
        else
         {
          die(
    'Stream to manager disconnected');
         }
       }
     echo 
    fgets($socket);
    }while(
    1);
    Basically the only difference is that I added a short lived time out. I wouldn't think that would cause an issue thou...

    I'll find out if it worked or not tomorrow morning.
    Last edited by ellisgl; 09-18-2008 at 02:41 PM.

  5. #5
    Join Date
    Jul 2007
    Posts
    357
    Hmmph..
    Ok - I have $maxRetries set for 120 - but the script dies after 2 retries... What the..... Weird.
    Last edited by ellisgl; 09-19-2008 at 11:17 AM.

  6. #6
    Join Date
    Aug 2006
    Location
    Michigan
    Posts
    1,046
    What error is logged when the script dies? in the do loop or the else statement?

  7. #7
    Join Date
    Jul 2007
    Posts
    357
    My error handler shows this in the log:
    20080919 07:00:45
    manager.php
    fsocketopen
    Could not reconnect after 2 retries
    --------------------

  8. #8
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,387
    You might want to add a error_reporting(E_ALL); to the start of the script to make sure your error log is catching all errors/notices, at least for now. Maybe the script is timing out, maxing out on memory, or some other non-obvious thing?
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  9. #9
    Join Date
    Jan 2003
    Location
    VA
    Posts
    419
    Quote Originally Posted by ellisgl
    I have a script that connect to server. I need to be able to reconnect on a disconnect. The first reconnect part of my script works on the initial connect.. But if the connection is broken during the run, doesn't try to reconnect at all. Saying that 0 is greater than 120.

    PHP Code:
    <?php
    // Run "forever"
    set_time_limit(0);

    /**
     * Database setup, connection and db selection
     */
    include('dbInclude.php');

    /**
     * Error logging
     */
    include('classes/ErrorLogger.class.php');
    $err = new ErrorLogger('/var/www/html/agent/errors.log');

    /**
     * Configuration of reconnection stuff
     */
    $reconnect  1// Reconnect?
    $maxRetries 120// Max reconnect retries
    $retryWait  1000000// Wait before reconnection try in milliseconds
    $tries      0;

    // Open the socket to the Asterisk Manager
    $socket   = @fsockopen('127.0.0.1','5038'$errno$errstr);

    // Connection failed
    if(!$socket)
     {
      
    // Try again?
      
    if($reconnect === 1)
       {
        
    $tries  0;
        
    $socket 0;

        do
         {
          
    // have we hit the max # of retries?
          
    if($tries >= $maxRetries)
           {
            
    $err->logError('manager.php''fsocketopen''Could not connect after '.intval($tries).' retries');
            die(
    'Could not connect to the manager');
           }

          
    $socket   fsockopen('127.0.0.1','5038'$errno$errstr);

          ++
    $tries;
          
    usleep($retryWait);
         }while(!
    $socket);
       }
      else
       {
        
    $err->logError('manager.php''fsocketopen''Could not connect - No retries');
        die(
    'Could not connect to the manager');
       }
     }

    // Login to the manager and turn events on
    fputs($socket"Action: Login\r\n");
    fputs($socket"UserName: admin\r\n");
    fputs($socket"Secret: xxxx\r\n\r\n");
    fputs($socket"Events: on\r\n");

    // Initialize an empty buffer - prevent a warning
    $buffer   "";

    // Array to track the calls
    $calls     = array();

    stream_set_blocking($socketTRUE);

    // Loop the the CLI output
    do
     {
      
    // Double check our stream
      
    if(feof($socket))
       {
        
    // Try again?
        
    if($reconnect === 1)
         {
          
    $tries  0;
          
    $socket 0;

          do
           {
            
    // have we hit the max # of retries?
            
    if($tries >= $maxRetries)
             {
              
    $err->logError('manager.php''fsocketopen''Could not reconnect after '.$tries.' retries');
              die(
    'Could not reconnect to the manager');
             }

            
    $socket   = @fsockopen('127.0.0.1','5038'$errno$errstr);

            ++
    $tries;
            
    usleep($retryWait);
           }while(!
    $socket);

          
    // Login back in.
          
    fputs($socket"Action: Login\r\n");
          
    fputs($socket"UserName: admin\r\n");
          
    fputs($socket"Secret: xxxx\r\n\r\n");
          
    fputs($socket"Events: on\r\n");
         }
        else
         {
          
    $err->logError('manager.php''fsocketopen''Stream disconnected - No retries');
          die(
    'Stream to manager disconnected');
         }
       }
     }
    Im not really sure, but maybe something like this will work.. I see your redeclaring $server several times. Maybe if you just use someting like this:
    PHP Code:
    // Connection failed
    if(!$socket = @fsockopen('127.0.0.1','5038'$errno$errstr)){
        
    // Try again?
        
    if($reconnect === 1){
            
    $tries  0;
            do {
                
    // have we hit the max # of retries?
                
    if($tries >= $maxRetries){
                    
    $err->logError('manager.php''fsocketopen''Could not connect after '.intval($tries).' retries');
                    die(
    'Could not connect to the manager');
                }    
            ++
    $tries;
            
    usleep($retryWait);
            }
            while(!
    $socket fsockopen('127.0.0.1','5038'$errno$errstr));
        }

    Going to be honest though, I havent a clue. just maybe a suggestion. its something I would try in my trial-and-error process.
    Cornflakes mmmm yummy

  10. #10
    Join Date
    Jul 2007
    Posts
    357
    During my test on the code last night, I would stop the server that it was connected to.. Then start it back up and it worked. But this morning, the script died with the message basically stating 2 is greater than 120. I'm thinking that when ever that server get's restarted, there's something that could killing that process, but I don't see how it would end up triggering the errors. I did a couple more changes this afternoon, some of my error handling was jacked up.. I'll find out again in the morning.

  11. #11
    Join Date
    Jul 2007
    Posts
    357
    Ok - after fixing my error logging calls, I ended up with another story for why the script was dying. My MySQL wrapper wasn't reselecting the DB after reconnect. Doh.. Of course we'll see tomorrow if it's all good.

    Here's the wrapper I've made...
    PHP Code:
    <?php
    class DBWrapper
     
    {
      private 
    $host       0// DB host address or url
      
    private $user       0// DB user name
      
    private $pass       0// DB password
      
    private $link       0// DB Link - Keeps the sessions seperated
      
    private $db         0// DB DB
      
    private $sql        0// MySQL query  string
      
    private $res        0// Results from query
      
    private $reconnect  0// Reconnect?
      
    private $maxRetries 0// Max reconnect retries
      
    private $retryWait  0// Wait before reconnection try in milliseconds
      
    private $error      0// Error messages

      
    public function __construct($config)
       {
        
    // Configure the private properties from an array
        
    foreach($config as $key=>$val)
         {
          
    $this->{$key} = $val;
         }

        
    // Connect to the DB
        
    $this->Connect(1);
       }

      
    // Connect to the DB
      
    private function Connect($init 0)
       {
        
    $this->link = @mysql_connect($this->host$this->user$this->pass1);

        
    // Could not connect
        
    if(!$this->link)
         {
          
    // Try to reconnect
          
    if($this->reconnect)
           {
            
    $this->link  0;
            
    $tries       0;

            do
             {
              
    // have we hit the max # of retries?
              
    if($this->maxRetries <= $tries)
               {
                if(
    $init === 1)
                 {
                  
    $this->error 'Could not connect to: '.$this->host;
                 }
                else
                 {
                  
    $this->error 'Could not reconnect to: '.$this->host;
                 }
                return 
    0;
               }

              
    $this->link = @mysql_connect($tihs->host$this->user$this->pass1);

              ++
    $tries;

              
    usleep($retryWait);

             }while(!
    $this->$link);
           }
          else
           {
            
    $this->error 'Could not connect to: '.$this->host;
            return 
    0;
           }
         }

        
    // Make sure the DB is selected
        
    $this->SelectDB();

        return 
    1;
       }

      
    // Select the DB
      
    private function SelectDB()
       {
        if(!
    mysql_select_db($this->db$this->link))
         {
          
    $this->error 'Could not select the DB: '.$this->db;
          return 
    0;
         }
        return 
    1;
       }

      public function 
    Query($sql)
       {
        
    // Store query sting
        
    $this->sql $sql;

        
    // Query the DB
        
    $this->res mysql_query($sql$this->link);

        
    // Error
        
    if(!$this->res)
         {
          
    // Disconnected?
          
    switch(mysql_errno($this->link))
           {
            
    // Disconnected error code
            
    case 2001:
            case 
    2002:
            case 
    2003:
            case 
    2004:
            case 
    2005:
            case 
    2006:
            case 
    2011:
            case 
    2012:
            case 
    2013:
             
    // Reconnect?
             
    if($this->reconnect === 1)
              {
               if(!
    $this->Connect())
                {
                 
    $this->error $this->error.'<br />Query was ::: '.$sql;
                 return 
    0;
                }
              }
             else
              {
               
    $this->error $sql.' ::: '.mysql_error($this->link);
               return 
    0;
              }
            break;

            default:
             
    $this->error $sql.' ::: '.mysql_error($this->link);
             return 
    0;
           }
         }
        else
         {
          return 
    $this->res;
         }

        
    // Reconnected - requery
        
    $this->res mysql_query($sql$this->link);
        return 
    $this->res;
       }

      public function 
    QueryAssoc($qry)
       {
        
    $this->Query($qry);
        return 
    mysql_fetch_assoc($this->res);
       }

      public function 
    Assoc()
       {
        return 
    mysql_fetch_assoc($this->res);
       }

      public function 
    Rows()
       {
        return 
    mysql_num_rows($this->res);
       }

      public function 
    ID()
       {
        return 
    mysql_insert_id($this->link);
       }

      public function 
    GetError()
       {
        return 
    $this->error;
       }
     }
    And my error logger.
    PHP Code:
    <?php
    class ErrorLogger
     
    {
      private 
    $logFile 0// Path and file name of the error log

      
    public function __construct($logFile)
       {
        
    $this->logFile $logFile;
       }

      public function 
    logError($fileName$type$error)
       {
        
    $fp   fopen($this->logFile'a');

        if(!
    $fp)
         {
          die(
    'Could not open or create: '.$this->logFile);
         }

        
    $data date('Ymd H:i:s')."\n".
                
    $fileName."\n".
                
    $type."\n".
                
    $error."\n".
                
    '--------------------'."\n\n";
                
        
    fwrite($fp$data);
       }
     }
    Last edited by ellisgl; 09-20-2008 at 12:26 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles