Class: Nerve::ServiceCheck::TcpServiceCheck

Inherits:
BaseServiceCheck show all
Includes:
Socket::Constants
Defined in:
lib/nerve/service_watcher/tcp.rb

Instance Method Summary collapse

Methods inherited from BaseServiceCheck

#catch_errors, #up?

Methods included from Logging

configure_logger_for, #log, logger_for

Methods included from Utils

#safe_run

Constructor Details

#initialize(opts = {}) ⇒ TcpServiceCheck

Returns a new instance of TcpServiceCheck.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
# File 'lib/nerve/service_watcher/tcp.rb', line 9

def initialize(opts={})
  super

  raise ArgumentError, "missing required argument 'port' in tcp check" unless opts['port']

  @port = opts['port']
  @host = opts['host'] || '127.0.0.1'

  @address = Socket.sockaddr_in(@port, @host)
end

Instance Method Details

#checkObject



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
# File 'lib/nerve/service_watcher/tcp.rb', line 20

def check
  log.debug "nerve: running TCP health check #{@name}"

  # create a TCP socket
  socket = Socket.new(AF_INET, SOCK_STREAM, 0)

  begin
    # open a non-blocking connection
    socket.connect_nonblock(@address)
  rescue Errno::EINPROGRESS
    # opening a non-blocking socket will usually raise
    # this exception. it's just connect returning immediately,
    # so it's not really an exception, but ruby makes it into
    # one. if we got here, we are now free to wait until the timeout
    # expires for the socket to be writeable
    IO.select(nil, [socket], nil, @timeout)

    # we should be connected now; allow any other exception through
    begin
      socket.connect_nonblock(@address)
    rescue Errno::EISCONN
      return true
    end
  else
    # we managed to connect REALLY REALLY FAST
    log.debug "nerve: connected to non-blocking socket without an exception"
    return true
  ensure
    socket.close
  end
end