|
#--
|
|
# CyborgHood, a distributed system management software.
|
|
# Copyright (c) 2009-2010 Marc Dequènes (Duck) <Duck@DuckCorp.org>
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
#++
|
|
|
|
require 'yaml'
|
|
require 'cyborghood/cyborg/session'
|
|
|
|
# Note: Event machine core is mono-thread, so this code is not threadsafe.
|
|
# Only long tasks will be run in threads, which do not care about all this.
|
|
|
|
module CyborgHood
|
|
|
|
module BotProtocol
|
|
VERSION = "0.1"
|
|
CAPABILITIES = []
|
|
|
|
@@request_callback = proc{|result| process_request_result(result) }
|
|
|
|
# TODO:
|
|
# - check for request/reply couples (reply to wrong of non-existent request)
|
|
# - check for negociation wip/done
|
|
|
|
def initialize(conversation)
|
|
@conversation = conversation
|
|
|
|
@negociation_received = false
|
|
@negociation_sent = false
|
|
@negociation_ok = false
|
|
end
|
|
|
|
def negociation_ok?
|
|
@negociation_ok
|
|
end
|
|
|
|
def process_received_message(message)
|
|
method = "receive_" + message.action_code.downcase.tr(" ", "_")
|
|
if respond_to? method
|
|
send(method, message)
|
|
else
|
|
send_error_protocol "unknown action"
|
|
end
|
|
end
|
|
|
|
def process_request_result(result)
|
|
if result[:error]
|
|
send_error_action(result[:reply_message], result[:error])
|
|
else
|
|
send_reply_result(result[:reply_message], result[:action_result])
|
|
end
|
|
end
|
|
|
|
def receive_announce_helo(message)
|
|
unless message.conv_thread.id == 0
|
|
return send_quit_decline "bad negociation"
|
|
end
|
|
unless message.parameters[:bot_name] =~ Conversation::BOT_ID_PATTERN
|
|
return send_quit_decline "bad bot name"
|
|
end
|
|
unless message.parameters[:protocol_version] == VERSION
|
|
return send_quit_decline "protocol version does not match"
|
|
end
|
|
@negociation_received = true
|
|
@conversation.set_peer_info(message.parameters[:bot_name], message.parameters[:capabilities])
|
|
|
|
if @negociation_sent
|
|
send_announce_ok(message)
|
|
@negociation_ok = true
|
|
else
|
|
send_announce_helo(message)
|
|
@negociation_sent = true
|
|
end
|
|
end
|
|
|
|
def receive_announce_ok(message)
|
|
unless @negociation_sent and @negociation_received
|
|
send_quit_decline "bad negociation"
|
|
end
|
|
@negociation_ok = true
|
|
end
|
|
|
|
def receive_request_capabilities(message)
|
|
send_reply_result(message, @conversation.capabilities + CAPABILITIES)
|
|
end
|
|
|
|
def receive_request_call(message)
|
|
unless @conversation.bot.interface.is_node? message.parameters[:node]
|
|
return send_error_action(message, "bad node")
|
|
end
|
|
send_reply_ack(message)
|
|
@conversation.bot.schedule_task(@@request_callback) do
|
|
result = {
|
|
:reply_message => message
|
|
}
|
|
begin
|
|
result[:action_result] = @conversation.bot.interface.call(message.conv_thread.session,
|
|
message.parameters[:node],
|
|
message.parameters[:data])
|
|
rescue
|
|
result[:error] = $!
|
|
end
|
|
end
|
|
end
|
|
|
|
def receive_request_exists(message)
|
|
unless @conversation.bot.interface.is_node? message.parameters[:node]
|
|
return send_error_action(message, "bad node")
|
|
end
|
|
send_reply_ack(message)
|
|
@conversation.bot.schedule_task(@@request_callback) do
|
|
{
|
|
:reply_message => message,
|
|
:action_result => @conversation.bot.interface.has_node? message.parameters[:node]
|
|
}
|
|
end
|
|
end
|
|
|
|
def receive_request_describe(message)
|
|
# TODO: implement when ready in the interface
|
|
send_quit_decline(message, "not implemented")
|
|
end
|
|
|
|
def send_announce_helo(recv_message = nil)
|
|
action_code = "ANNOUNCE HELO"
|
|
message = (recv_message.nil? ? @conversation.thread('system').new_message(action_code) :
|
|
recv_message.create_reply(action_code))
|
|
message.send
|
|
end
|
|
|
|
def send_announce_ok(recv_message)
|
|
recv_message.create_reply("ANNOUNCE OK").send
|
|
end
|
|
|
|
def send_request_capabilities
|
|
@conversation.thread('system').new_message("REQUEST EXISTS", { :node => node }).send
|
|
end
|
|
|
|
def send_request_call(conv_thread, node)
|
|
conv_thread.new_message("REQUEST CALL", { :node => node }).send
|
|
end
|
|
|
|
def send_request_exists(conv_thread, node)
|
|
conv_thread.new_message("REQUEST EXISTS", { :node => node }).send
|
|
end
|
|
|
|
def send_request_describe(conv_thread, node)
|
|
conv_thread.new_message("REQUEST DESCRIBE", { :node => node }).send
|
|
end
|
|
|
|
def send_error_protocol(error, fatal = false)
|
|
@conversation.thread('system').new_message("ERROR PROTOCOL", { :error => error }).send
|
|
@conversation.set_error_status(fatal)
|
|
end
|
|
|
|
def send_error_action(recv_message, error)
|
|
recv_message.create_reply("ERROR ACTION", { :error => error }).send
|
|
end
|
|
|
|
def send_reply_ack(recv_message)
|
|
recv_message.create_reply("REPLY ACK").send
|
|
end
|
|
|
|
def send_reply_decline(recv_message, reason)
|
|
recv_message.create_reply("REPLY DECLINE", { :reason => reason }).send
|
|
end
|
|
|
|
def send_reply_result(recv_message, result)
|
|
recv_message.create_reply("REPLY ACK", { :result => result }).send
|
|
end
|
|
|
|
def send_quit_decline(reason)
|
|
@conversation.thread('system').new_message("QUIT LEAVING", { :reason => reason }).send
|
|
end
|
|
|
|
def send_quit_leaving
|
|
@conversation.thread('system').new_message("QUIT LEAVING").send
|
|
end
|
|
end
|
|
|
|
class ConversationThread
|
|
attr_reader :conversation, :name, :id, :session
|
|
|
|
def initialize(conversation, id, name)
|
|
@conversation = conversation
|
|
@name = name
|
|
@id = id
|
|
|
|
@session = Session.new
|
|
@next_action_id = 0
|
|
end
|
|
|
|
def new_message(action_code, parameters = nil, action_id = nil)
|
|
Message.new(self, action_code, parameters)
|
|
end
|
|
|
|
def next_action_id
|
|
id = @next_action_id
|
|
@next_action_id +=1
|
|
id
|
|
end
|
|
|
|
def close
|
|
@session.clear
|
|
# TODO: enforce destruction ???
|
|
end
|
|
end
|
|
|
|
class Message
|
|
private_class_method :new
|
|
|
|
attr_reader :conv_thread, :action_code, :action_parameters, :action_id
|
|
|
|
def initialize(conv_thread, action_code, action_parameters = nil, action_id = nil)
|
|
@conv_thread = conv_thread
|
|
@action_code = action_code
|
|
@action_parameters = action_parameters
|
|
@action_id = action_id
|
|
end
|
|
|
|
def new?
|
|
@action_id.nil?
|
|
end
|
|
|
|
def send
|
|
raise CyberError.new(:unrecoverable, "bot/conversation", "Not sending twice the same message") unless self.new?
|
|
@action_id = @conv_thread.next_action_id
|
|
@conv_thread.conversation.send_message(self)
|
|
end
|
|
|
|
def create_reply(action_code, parameters)
|
|
raise CyberError.new(:unrecoverable, "bot/conversation", "Cannot reply to a newly created message") if self.new?
|
|
new(self, action_code, parameters)
|
|
end
|
|
end
|
|
|
|
class Conversation < EventMachine::Protocols::LineAndTextProtocol
|
|
private_class_method :new
|
|
|
|
# don't rely on EventMachine's default, it may change one day
|
|
MaxLineLength = 16*1024
|
|
|
|
EOD = "\033[0J"
|
|
BOT_ID_PATTERN = "[a-zA-Z0-9]+"
|
|
ACTION_WORD_PATTERN = "[a-zA-Z0-9]+"
|
|
ACTION_PATTERN = "^(#{BOT_ID_PATTERN})(\d{4})-(\d{4})([+]?) (#{ACTION_WORD_PATTERN}( #{ACTION_WORD_PATTERN})*)$"
|
|
MAXIMUM_ERROR_COUNT = 3
|
|
MAXIMUM_LINES = 1024
|
|
|
|
attr_reader :bot
|
|
|
|
def initialize(bot)
|
|
@bot = bot
|
|
|
|
super
|
|
|
|
@config = Config.instance
|
|
|
|
@receive_error_count = 0
|
|
@split_data_mode = false
|
|
@split_data_message = nil
|
|
@split_data = []
|
|
|
|
# associated conversation threads
|
|
@conv_threads = {}
|
|
# thread 0 is reserved
|
|
@next_thread_id = 0
|
|
@system_thread = self.thread('system')
|
|
|
|
# post-negociation peer info
|
|
@peer_id = nil
|
|
@peer_capabilities = []
|
|
|
|
@protocol = BotProtocol.new(self)
|
|
end
|
|
|
|
def capabilities
|
|
[]
|
|
end
|
|
|
|
def post_init
|
|
logger.debug "New conversation with #{identifier}"
|
|
end
|
|
|
|
def receive_line(data)
|
|
return if data.empty?
|
|
|
|
clear_receive_info
|
|
|
|
if data == EOD
|
|
logger.debug "Received EOD [#{identifier}]"
|
|
exit_split_mode
|
|
else
|
|
if @split_data_mode
|
|
logger.debug "Received data (split mode) [#{identifier}]: #{data}"
|
|
|
|
if @split_data.size > MAXIMUM_LINES
|
|
reply_fatal_error "overflow"
|
|
else
|
|
@split_data << data
|
|
end
|
|
else
|
|
logger.debug "Received data [#{identifier}]: #{data}"
|
|
|
|
if data =~ Regexp.new(ACTION_PATTERN)
|
|
conv_thread_id = $1
|
|
action_id = $2
|
|
flags = $3 || ""
|
|
action_code = $4
|
|
|
|
conv_thread = self.thread_by_id(conv_thread_id)
|
|
message = conv_thread.new_message(action_code, nil, action_id)
|
|
|
|
if flags.index '+'
|
|
enter_split_mode(message)
|
|
else
|
|
receive_message(message)
|
|
end
|
|
else
|
|
reply_syntax_error "bad action format"
|
|
end
|
|
end
|
|
end
|
|
|
|
send_reply
|
|
|
|
check_errors
|
|
end
|
|
|
|
def receive_message(message)
|
|
logger.debug "Received message '#{action}' [#{identifier}]"
|
|
|
|
@protocol.process_received_message(message)
|
|
end
|
|
|
|
def receive_error(msg)
|
|
logger.error "Error [#{identifier}]: #{msg}"
|
|
@error_count += 1
|
|
end
|
|
|
|
def unbind
|
|
logger.debug "Conversation finished with #{identifier}"
|
|
@bot.register_communication @peer_id unless @peer_id.nil?
|
|
@conv_threads.each_values {|s| s.close }
|
|
end
|
|
|
|
def bye
|
|
send_quit_leaving
|
|
end
|
|
|
|
def set_peer_info(id, capabilities)
|
|
@peer_id = id
|
|
@peer_capabilities = capabilities || []
|
|
@bot.register_communication @peer_id, self
|
|
end
|
|
|
|
def set_error_status(fatal = false)
|
|
# fatal status is conservative, it cannot be canceled
|
|
@reveive_fatal_error = @reveive_fatal_error || fatal
|
|
@receive_error = true
|
|
end
|
|
|
|
def thread(name = 'default')
|
|
@conv_threads[name] || new_thread(name)
|
|
end
|
|
|
|
def thread_by_id(id)
|
|
name = @conv_threads_index[id]
|
|
name.nil? ? new_thread("noname/#{id}", id) : @conv_threads[name]
|
|
end
|
|
|
|
def send_message(message)
|
|
raise CyberError.new(:unrecoverable, "bot/conversation", "Cannot send message without action id") if message.action_id.nil?
|
|
|
|
send_line "#{@config.bot_id}-#{message.conv_thread.id}-#{message.action_id}" + (message.action_parameters.nil? : "" : "+") + " #{message.action_code}"
|
|
unless message.action_parameters.nil?
|
|
message.action_parameters.to_yaml.split.each {|l| send_line l }
|
|
send_line EOD
|
|
end
|
|
|
|
action_id
|
|
end
|
|
|
|
protected
|
|
|
|
def clear_receive_info
|
|
@receive_error = false
|
|
@receive_fatal_error = false
|
|
end
|
|
|
|
def send_line(msg)
|
|
logger.debug "Sending data [#{identifier}]: #{msg}"
|
|
send_data "#{msg}\n"
|
|
end
|
|
|
|
def check_errors
|
|
@error_count += 1 if @receive_error
|
|
|
|
msg_quit = nil
|
|
if @error_count >= MAXIMUM_ERROR_COUNT
|
|
msg_quit = "too much errors, terminating"
|
|
elsif @fatal_error
|
|
msg_quit = "previous fatal error"
|
|
end
|
|
|
|
unless msg_quit.nil?
|
|
send_quit_decline msg_quit
|
|
close_connection_after_writing
|
|
end
|
|
end
|
|
|
|
def new_thread(name, id = nil)
|
|
id ||= @next_thread_id
|
|
th = ConversationThread.new(self, id, name)
|
|
@next_thread_id = [@next_thread_id, id + 1].max
|
|
|
|
@conv_threads[th.name] = th
|
|
# allow searching by id too
|
|
@conv_threads_index[th.id] = name
|
|
th
|
|
end
|
|
|
|
def reply_syntax_error(msg = nil)
|
|
logger.error "Protocol error [#{identifier}]: syntax error (#{msg})"
|
|
|
|
msg = "syntax error" + (msg ? ": " + msg : "")
|
|
@protocol.send_error_protocol(msg)
|
|
end
|
|
|
|
def reply_fatal_error(msg = nil)
|
|
logger.error "Protocol error [#{identifier}]: fatal error (#{msg})"
|
|
|
|
msg = "fatal error" + (msg ? ": " + msg : "")
|
|
@protocol.send_error_protocol(msg, true)
|
|
end
|
|
|
|
def enter_split_mode(message)
|
|
if @split_data_mode
|
|
reply_fatal_error "already in split mode"
|
|
@split_data_mode = false
|
|
@split_data_message = nil
|
|
else
|
|
logger.debug "Protocol info [#{identifier}]: entered split mode for action '#{message.action_id}'"
|
|
@split_data_mode = true
|
|
@split_data_message = message
|
|
end
|
|
@split_data = []
|
|
end
|
|
|
|
def exit_split_mode
|
|
if @split_data_mode
|
|
logger.debug "Protocol info [#{identifier}]: quit split mode for action '#{@split_data_message.action_id}'"
|
|
|
|
parameters = YAML.parse(@split_data.join("\n"))
|
|
reply_syntax_error("bad parameters format") if parameters.nil?
|
|
|
|
message = @split_data_message.conv_thread.new_message(@split_data_message.action_code, parameters, @split_data_message.action_id)
|
|
receive_message(message)
|
|
else
|
|
reply_fatal_error "not in split mode"
|
|
end
|
|
@split_data_mode = false
|
|
@split_data_message = nil
|
|
@split_data = []
|
|
end
|
|
end
|
|
|
|
class ConversationUNIXSocket < Conversation
|
|
public_class_method :new
|
|
|
|
def identifier
|
|
"unix_socket/#{@signature}"
|
|
end
|
|
|
|
def capabilities
|
|
super + []
|
|
end
|
|
end
|
|
end
|