File: udp.rb

package info (click to toggle)
ruby-riemann-client 0.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 148 kB
  • sloc: ruby: 730; makefile: 2
file content (78 lines) | stat: -rw-r--r-- 1,706 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
module Riemann
  class Client
    class UDP < Client
      MAX_SIZE = 16384

      attr_accessor :host, :port, :socket, :max_size

      def initialize(opts = {})
        @host = opts[:host] || HOST
        @port = opts[:port] || PORT
        @max_size = opts[:max_size] || MAX_SIZE
        @locket = Mutex.new
      end

      def connect
        @socket = UDPSocket.new
      end

      def close
        @locket.synchronize do
          @socket.close
        end
      end

      def connected?
        !!@socket && @socket.closed?
      end

      # Read a message from a stream
      def read_message(s)
        raise Unsupported
      end

      def send_recv(*a)
        raise Unsupported
      end

      def send_maybe_recv(message)
        with_connection do |s|
          x = message.encode ''
          unless x.length < @max_size
            raise TooBig
          end

          s.send(x, 0, @host, @port)
          nil
        end
      end

      # Yields a connection in the block.
      def with_connection
        tries = 0
        
        @locket.synchronize do
          begin
            tries += 1
              yield(@socket || connect)
          rescue IOError => e
            raise if tries > 3
            connect and retry
          rescue Errno::EPIPE => e
            raise if tries > 3
            connect and retry
          rescue Errno::ECONNREFUSED => e
            raise if tries > 3
            connect and retry
          rescue Errno::ECONNRESET => e
            raise if tries > 3
            connect and retry
          rescue InvalidResponse => e
            raise if tries > 3
            connect and retry
          end
        end
      end
    end
  end
end