Class: CheckTaskr::SocketAction

Inherits:
JobsAction show all
Includes:
Socket::Constants
Defined in:
lib/check-taskr/task/sockets.rb

Instance Attribute Summary collapse

Attributes inherited from JobsAction

#name

Instance Method Summary collapse

Methods inherited from JobsAction

setup

Constructor Details

#initialize(options) ⇒ SocketAction

Returns a new instance of SocketAction.



29
30
31
32
33
34
35
# File 'lib/check-taskr/task/sockets.rb', line 29

def initialize(options)
  @name = options[:name]
  @ip = options[:ip]
  @port = options[:port]
  @error_code = options[:error_code] || @@default_error_code
  @error_msg = options[:error_msg] || @@default_error_msg
end

Instance Attribute Details

#error_codeObject

Returns the value of attribute error_code.



25
26
27
# File 'lib/check-taskr/task/sockets.rb', line 25

def error_code
  @error_code
end

#error_msgObject

Returns the value of attribute error_msg.



25
26
27
# File 'lib/check-taskr/task/sockets.rb', line 25

def error_msg
  @error_msg
end

#ipObject

Returns the value of attribute ip.



25
26
27
# File 'lib/check-taskr/task/sockets.rb', line 25

def ip
  @ip
end

#portObject

Returns the value of attribute port.



25
26
27
# File 'lib/check-taskr/task/sockets.rb', line 25

def port
  @port
end

Instance Method Details

#executeObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/check-taskr/task/sockets.rb', line 37

def execute
  log = Log4r::Logger['default']
  log.debug "action: ip=#{@ip}, port=#{@port}, name=#{@name}"
  hash = { :stat => 0, :ip => @ip, :msg => "OK", :timestamp => Time.now.to_i, :error_id => @error_code }
  begin
    timeout(5) do
      socket = Socket.new(AF_INET, SOCK_STREAM, 0) #生成新的套接字
      sockaddr = Socket.pack_sockaddr_in(@port, @ip)
      socket.connect(sockaddr)
      log.debug "Port:#{@ip}:#{@port} is Opend!\n"
      socket.close
    end
  rescue Timeout::Error
    hash = {:error_id => @error_code, :stat => 2, :ip => @ip, :msg => "网络访问超时", :timestamp => Time.now.to_i }
    log.error hash.to_json
  rescue Exception => e
    hash = {:error_id => @error_code, :stat => 1, :ip => @ip, :msg => @error_msg || e.to_s, :timestamp => Time.now.to_i }
    log.error hash.to_json
  end
  return hash
end