Class: Rexpro::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/rexpro/client.rb

Constant Summary collapse

DEFAULT_HOST =
'localhost'
DEFAULT_PORT =
8184

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rexpro/client.rb', line 12

def initialize(opts = {})
  opts = opts.dup
  @host = opts.delete(:host) || DEFAULT_HOST
  @port = opts.delete(:port) || DEFAULT_PORT

  @request_opts = {}
  [:graph_name, :graph_obj_name].each do |key|
    value = opts.delete(key)
    @request_opts[key] = value if value
  end

  @socket_opts = opts
  reconnect
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



10
11
12
# File 'lib/rexpro/client.rb', line 10

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



10
11
12
# File 'lib/rexpro/client.rb', line 10

def port
  @port
end

#socketObject (readonly)

Returns the value of attribute socket.



10
11
12
# File 'lib/rexpro/client.rb', line 10

def socket
  @socket
end

Instance Method Details

#execute(script, opts = {}) ⇒ Object



68
69
70
71
72
73
# File 'lib/rexpro/client.rb', line 68

def execute(script, opts = {})
  opts = @request_opts.merge(opts)
  opts[:script] = script
  msg = Rexpro::Message::ScriptRequest.new(opts)
  request(msg)
end

#new_session(opts = {}) ⇒ Object



61
62
63
64
65
66
# File 'lib/rexpro/client.rb', line 61

def new_session(opts = {})
  opts = @request_opts.merge(opts)
  req = Rexpro::Message::SessionRequest.new(opts)
  resp = request(req)
  Rexpro::Session.new(self, resp.session_uuid, resp.languages)
end

#reconnectObject



27
28
29
30
31
32
33
34
35
# File 'lib/rexpro/client.rb', line 27

def reconnect
  @socket.close if @socket && !@socket.closed?
  begin
    @socket = TCPTimeout::TCPSocket.new(@host, @port, @socket_opts)
    @socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
  rescue TCPTimeout::SocketTimeout => ex
    raise Rexpro::RexproException.new(ex)
  end
end

#request(req) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rexpro/client.rb', line 37

def request(req)
  req.write_to(@socket)

  Rexpro::Message.read_from(@socket).tap do |resp|
    if resp.is_a? Rexpro::Message::Error
      err_msg = resp.error_message
      err_msg << " [flag=#{resp.flag}]" if resp.flag
      raise Rexpro::RexproError.new(err_msg)
    end
    
    if resp.request_uuid.bytes.to_a != req.request_uuid.bytes.to_a
      @socket.close
      raise Rexpro::RexproException,
            "request uuid of response didn't match request"
    end
  end
rescue TCPTimeout::SocketTimeout => ex
  raise Rexpro::RexproException.new(ex)
rescue SystemCallError
  # Lets not leave an open connection in a potentially bad state
  @socket.close
  raise
end