]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/ircbot.rb
better failure to connect behaviour
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
index c30d0e6d3bdf33095060af0f09adcd12f89c8205..2443ec95d7ae0865423a2b4a4117245c55cb77ea 100644 (file)
@@ -51,9 +51,6 @@ class IrcBot
   # bot's Language data
   attr_reader :lang
 
-  # bot's configured addressing prefixes
-  attr_reader :addressing_prefixes
-
   # channel info for channels the bot is in
   attr_reader :channels
 
@@ -112,6 +109,10 @@ class IrcBot
       :default => 4, :validate => Proc.new{|v| v >= 0},
       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines, with non-burst limits of 512 bytes/2 seconds",
       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
+    BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
+      :default => 10, :validate => Proc.new{|v| v >= 0},
+      :on_change => Proc.new {|bot, v| bot.start_server_pings},
+      :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
 
     @argv = params[:argv]
 
@@ -120,7 +121,8 @@ class IrcBot
       exit 2
     end
     
-    botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass
+    #botclass = "#{Etc.getpwnam(Etc.getlogin).dir}/.rbot" unless botclass
+    botclass = "#{ENV['HOME']}/.rbot" unless botclass
     @botclass = botclass.gsub(/\/$/, "")
 
     unless FileTest.directory? botclass
@@ -134,6 +136,9 @@ class IrcBot
     
     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
 
+    @ping_timer = nil
+    @pong_timer = nil
+    @last_ping = nil
     @startup_time = Time.new
     @config = BotConfig.new(self)
 # TODO background self after botconfig has a chance to run wizard
@@ -142,7 +147,6 @@ class IrcBot
     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
     @channels = Hash.new
     @logs = Hash.new
-    
     @httputil = Utils::HttpUtil.new(self)
     @lang = Language::Language.new(@config['core.language'])
     @keywords = Keywords.new(self)
@@ -153,7 +157,7 @@ class IrcBot
 
     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
     @nick = @config['irc.nick']
-    
+
     @client = IrcClient.new
     @client[:privmsg] = proc { |data|
       message = PrivMessage.new(self, data[:source], data[:target], data[:message])
@@ -179,6 +183,9 @@ class IrcBot
       # (jump the queue for pongs)
       @socket.puts "PONG #{data[:pingid]}"
     }
+    @client[:pong] = proc {|data|
+      @last_ping = nil
+    }
     @client[:nick] = proc {|data|
       sourcenick = data[:sourcenick]
       nick = data[:nick]
@@ -300,9 +307,13 @@ class IrcBot
 
   # connect the bot to IRC
   def connect
-    trap("SIGTERM") { quit }
-    trap("SIGHUP") { quit }
-    trap("SIGINT") { quit }
+    begin
+      trap("SIGTERM") { quit }
+      trap("SIGHUP") { quit }
+      trap("SIGINT") { quit }
+    rescue
+      debug "failed to trap signals, probably running on windows?"
+    end
     begin
       @socket.connect
       rescue => e
@@ -310,32 +321,38 @@ class IrcBot
     end
     @socket.puts "PASS " + @config['server.password'] if @config['server.password']
     @socket.puts "NICK #{@nick}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
+    start_server_pings
   end
 
   # begin event handling loop
   def mainloop
     while true
+      begin
       connect
       @timer.start
       
-      begin
         while true
           if @socket.select
             break unless reply = @socket.gets
             @client.process reply
           end
         end
-      rescue TimeoutError, SocketError => e
+      # I despair of this. Some of my users get "connection reset by peer"
+      # exceptions that ARENT SocketError's. How am I supposed to handle
+      # that?
+      #rescue TimeoutError, SocketError => e
+      rescue Exception => e
         puts "network exception: connection closed: #{e}"
         puts e.backtrace.join("\n")
-        @socket.close # now we reconnect
-      rescue => e # TODO be selective, only grab Network errors
+        @socket.shutdown # now we reconnect
+      rescue => e
         puts "unexpected exception: connection closed: #{e.inspect}"
         puts e.backtrace.join("\n")
         exit 2
       end
       
       puts "disconnected"
+      @last_ping = nil
       @channels.clear
       @socket.clearq
       
@@ -546,6 +563,40 @@ class IrcBot
     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
   end
 
+  # we'll ping the server every 30 seconds or so, and expect a response
+  # before the next one come around..
+  def start_server_pings
+    @last_ping = nil
+    # stop existing timers if running
+    unless @ping_timer.nil?
+      @timer.remove @ping_timer
+      @ping_timer = nil
+    end
+    unless @pong_timer.nil?
+      @timer.remove @pong_timer
+      @pong_timer = nil
+    end
+    return unless @config['server.ping_timeout'] > 0
+    # we want to respond to a hung server within 30 secs or so
+    @ping_timer = @timer.add(30) {
+      @last_ping = Time.now
+      @socket.puts "PING :rbot"
+    }
+    @pong_timer = @timer.add(10) {
+      unless @last_ping.nil?
+        diff = Time.now - @last_ping
+        unless diff < @config['server.ping_timeout']
+          debug "no PONG from server for #{diff} seconds, reconnecting"
+          begin
+            @socket.shutdown
+          rescue
+            debug "couldn't shutdown connection (already shutdown?)"
+          end
+          @last_ping = nil
+        end
+      end
+    }
+  end
 
   private
 
@@ -794,7 +845,6 @@ class IrcBot
       break if m.privmsg(message)
     }
   end
-
 end
 
 end