Class: RightScale::CommandIO

Inherits:
Object
  • Object
show all
Includes:
RightSupport::Ruby::EasySingleton
Defined in:
lib/right_agent/command/command_io.rb

Overview

Class which allows listening for data and sending data on sockets This allows other processes running on the same machine to send commands to the agent without having to go through RabbitMQ.

Defined Under Namespace

Modules: ServerInputHandler

Instance Method Summary collapse

Instance Method Details

#listen(socket_port, &block) ⇒ Object

Open command socket and wait for input on it This can only be called again after ‘stop_listening’ was called

Parameters

socket_port(Integer)

Socket port on which to listen

Block

The given block should take two arguments:

* First argument will be given the commands sent through the socket
  Commands should be serialized using RightScale::CommandSerializer.
* Second argument contains the connection that should be given back to
  +reply+ to send reply

Return

true

Always return true

Raise

(ArgumentError)

If block is missing

(Exceptions::Application)

If listen has already been called and stop hasn’t since

(Exceptions::Application)

If port is already bound

Raises:

  • (ArgumentError)


82
83
84
85
86
87
88
89
90
91
# File 'lib/right_agent/command/command_io.rb', line 82

def listen(socket_port, &block)
  raise ArgumentError, 'Missing listener block' unless block_given?
  raise Exceptions::Application, 'Already listening' if listening
  begin
    @conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
  rescue Exception => e
    raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
  end
  true
end

#listeningObject

Is listener currently waiting for input?

Return

true

If ‘listen’ was last called

false

Otherwise



58
59
60
# File 'lib/right_agent/command/command_io.rb', line 58

def listening
  !@conn.nil?
end

#reply(conn, data, close_after_writing = true) ⇒ Object

Write given data to socket, must be listening

Parameters

conn(EM::Connection)

Connection used to send data

data(String)

Data that should be written

close_after_writing(TrueClass|FalseClass)

Whether TCP connection with client should be closed after reply is sent

Return

true

Always return true



118
119
120
121
122
# File 'lib/right_agent/command/command_io.rb', line 118

def reply(conn, data, close_after_writing=true)
  conn.send_data(CommandSerializer.dump(data))
  conn.close_connection_after_writing if close_after_writing
  true
end

#stop_listeningObject

Stop listening for commands Do nothing if already stopped

Return

true

If command listener was listening

false

Otherwise



99
100
101
102
103
104
105
106
# File 'lib/right_agent/command/command_io.rb', line 99

def stop_listening
  res = !@conn.nil?
  if res
    EM.stop_server(@conn)
    @conn = nil
  end
  res
end