Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Tag: | Revision:
#--
# CyborgHood, a distributed system management software.
# Copyright (c) 2009-2011 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/>.
#++


module CyborgHood
module TaskAspect
def task(name, options = {}, &block)
the_bot = self.is_a?(Cyborg) ? self : self.bot
DSL::Task.new(the_bot, name, options, &block)
end

def schedule_task(callback = nil, &task)
EventMachine.defer(task, callback)
end
end

module DSL
class TaskBase
attr_reader :bot, :name, :errors, :results, :preferred_locales, :locale, :user, :store

include I18nTranslation

# mutex used for all class variables in this paragraph
@@tasks_info_mutex = Mutex.new
@@task_wip = 0
@@registered_resources = {}

@@stop_all_tasks = false

def self.idle?
@@tasks_info_mutex.synchronize do
@@task_wip == 0
end
end

def self.stop_all
@@stop_all_tasks = true

# call defuse callback out of the sync block
# (which may need to synchronize later to the
# same mutex in usual conditions)
resources_to_free = true
while not resources_to_free.nil?
@@tasks_info_mutex.synchronize do
resources_to_free = @@registered_resources.shift
end
resources_to_free[1].call unless resources_to_free.nil?
end
end

# the name MUST be unique
def initialize(bot, name, options = {}, &block)
@bot = bot
@name = name

@@tasks_info_mutex.synchronize do
@@task_wip += 1
end

@errors = {}.freeze
@results = {}.freeze

@notification_name = "task/#{@name}"
@preferred_locales = nil
@locale = nil
@user = nil

@store = OpenStruct.new

_setup

step = {:options => options, :cb => block}
step_code = get_step_code(step)
_start_dsl(step_code)
end

def set_preferred_locales(prefs)
_add_subtask("setting/preferred_locales") do |subtask|
logger.debug "Task '#{@name}': setting preferred locales to: #{prefs}"
@preferred_locales = prefs

subtask.finish
end
end

# temporary setting until Guard is created
def set_user(user)
_add_subtask("setting/user") do |subtask|
logger.debug "Task '#{@name}': setting user to: #{user}"
@user = user

subtask.finish
end
end

# may return a Hash of results
def schedule(&job)
_add_subtask("job/#{job.hash}") do |subtask|
logger.debug "Task '#{@name}': Scheduling job"
cb = Proc.new do
subtask.finish
end
job_wrapper = Proc.new do
job.call subtask
end
@bot.schedule_task(cb, job_wrapper)
end
end

def send_notification(name, data)
name = @notification_name if name == :task

_add_subtask("notification/#{name}/out") do |subtask|
logger.debug "Task '#{@name}': Sending notification to '#{name}'"
chan = @bot.get_channel(name)
chan << data
subtask.finish
end
end

def wait_notification(name, criterias = {}, timeout = nil, &cb)
name = @notification_name if name == :task

subtask_name = "notification/#{name}/#{criterias.hash}/in"
_add_subtask(subtask_name) do |subtask|
logger.debug "Task '#{@name}': subtask '#{subtask.name}': waiting notification on '#{name}'"
subcription_id = nil
subcription_id_mutex = Mutex.new

# callback to end notification and subtask
# (used when shooting the task)
defuse_notification_cb = Proc.new do
logger.debug "Task '#{@name}': defusing subtask '#{subtask.name}'"

subcription_id_mutex.synchronize do
@bot.get_channel(name).unsubscribe(subcription_id) unless subcription_id.nil?
subcription_id = nil
end

subtask.finish unless subtask.finished?

# we already own the mutex here
@@registered_resources.delete(subtask_name)
end
# register notification in the task
@@tasks_info_mutex.synchronize do
@@registered_resources[subtask_name] = defuse_notification_cb
end

subcription_id = @bot.get_channel(name).subscribe do |msg|
if _notification_criterias_match(msg, criterias)
cb.call(subtask, msg)

if subtask.finished?
subcription_id_mutex.synchronize do
@bot.get_channel(name).unsubscribe(subcription_id) unless subcription_id.nil?
subcription_id = nil
end

# unregister the notification
@@tasks_info_mutex.synchronize do
@@registered_resources.delete(subtask_name)
end
end
end
end

if timeout
EventMachine.add_timer(timeout) do
subcription_id_mutex.synchronize do
@bot.get_channel(name).unsubscribe(subcription_id) unless subcription_id.nil?
subcription_id = nil
end

# unregister the notification
@@tasks_info_mutex.synchronize do
@@registered_resources.delete(subtask_name)
end

subtask.finish
end
end
end
end

def wait_timer(timeout, repeat = false, &cb)
subtask_name = "timer/#{timeout}/#{cb.hash}"
_add_subtask(subtask_name) do |subtask|
timer_signature = nil
timer_signature_mutex = Mutex.new

# callback to end timer and subtask
# (used when shooting the task)
defuse_timer_cb = Proc.new do
logger.debug "Task '#{@name}': defusing subtask '#{subtask.name}'"

timer_signature_mutex.synchronize do
EventMachine.cancel_timer(timer_signature) unless timer_signature.nil?
timer_signature = nil
end

subtask.finish unless subtask.finished?

# we already own the mutex here
@@registered_resources.delete(subtask_name)
end
# register timer in the task
@@tasks_info_mutex.synchronize do
@@registered_resources[subtask_name] = defuse_timer_cb
end

timer_cb = Proc.new do
if repeat
cb.call(subtask)
timer_signature_mutex.synchronize do
if subtask.finished? and not timer_signature.nil?
EventMachine.cancel_timer(timer_signature)
timer_signature = nil
end
end
else
cb.call(subtask)

# unregister the timer
@@tasks_info_mutex.synchronize do
@@registered_resources.delete(subtask_name)
end

subtask.finish unless subtask.finished?
end
end

if repeat
timer_signature = EventMachine.add_periodic_timer(timeout, timer_cb)
else
timer_signature = EventMachine.add_timer(timeout, timer_cb)
end
end
end

# the name MUST be unique
def task(name, &block)
_add_subtask("task/#{name}") do |subtask|
self.class.new(@bot, name, &block)
subtask.finish
end
end

def meet(task_list, meetpoint, retry_time = 2)
task_list = [task_list] unless task_list.is_a? Array
task_list = Set.new(task_list)

notification_name = "meeting_point/#{meetpoint}"
notifications_received = Set.new
meet_ok = false

wait_notification(notification_name, {:topic => "MEET"}) do |subtask, msg|
notifications_received << msg[:from] if task_list.include?(msg[:from])
if task_list == notifications_received
meet_ok = true
subtask.finish
end
end
wait_timer(retry_time, true) do |subtask|
# in this order: send a last message before leaving
# (so we are sure the peer received a reply to its message)
send_notification notification_name, {:topic => "MEET", :from => @name}

subtask.finish if meet_ok or @@stop_all_tasks
end
end

# error when adding subtasks, as we cannot check callbacks
# only applies to subsequently added tasks (wanted behavior)
def cancel_on_start_error
@cancel_on_start_error = true
end

def on_error(options = {}, &cb)
@error_step = {:options => options, :cb => cb}
end

def on_success(options = {}, &cb)
@success_step = {:options => options, :cb => cb}
end

def stop_bot(condition)
_add_subtask('stop') do |subtask|
@bot.stop(condition)

subtask.finish
end
end

protected

class Subtask
attr_reader :name
attr_accessor :results, :errors

def initialize(task, name, &block)
@task = task
@name = name
@block = block

@finished = false
@results = {}
@errors = []
end

def do_it
@block.call self
rescue
msg = "Task '#{@task.name}': error: " + $!.to_s
logger.error msg
@errors << CyberError.new(:unrecoverable, "botnet/client/dsl", msg)
logger.debug $!.backtrace.join("\n")
finish
end

def finish
if @finished
raise CyberError.new(:unrecoverable, "botnet/client/dsl", "Task '#{@task.name}': subtask '#{@name}' should have ended, but it lied")
end
@finished = true
logger.debug "Task '#{@task.name}': subtask '#{@name}' finished"
@task.__send__(:_check_finished)
end

def finished?
@finished
end
end

def _add_subtask(name, cb = nil, &block)
subtask = Subtask.new(self, name, &block)
@subtasks << subtask
subtask.do_it if @dsl_runing
end

def _subtasks_finished?
subtasks_running = []
@subtasks.each do |subtask|
subtasks_running << subtask.name unless subtask.finished?
end

logger.debug "Task '#{@name}': the following subtasks are still running: " +
subtasks_running.join(', ') unless subtasks_running.empty?

subtasks_running.empty?
end

def get_step_code(step)
return if step.nil?

cb = step[:cb]
return cb unless cb.nil?

file = step[:options][:file]
if file.nil?
logger.error "Task '#{@name}': error in DSL: neither block nor file provided for next step definition"
return
end

begin
step_code = File.read(File.join(self.base_lpath, file + ".rb"))
rescue
logger.error "Task '#{@name}': error in DSL: cannot open step definition file: " + $!.message
return
end

return step_code
end

def _check_finished
return unless _subtasks_finished?

# avoid race: no subtask will be run in this task now
@dsl_runing = false

logger.debug "Task '#{@name}': step finished"

if @@stop_all_tasks
_finished

# running no more steps will end the task
return
end

# compute step result
@errors = {}
@results = {}
@subtasks.each do |subtask|
@errors[subtask.name] = subtask.errors unless subtask.errors.empty?
@results.merge!(subtask.results)
end
@errors.freeze
@result.freeze

# next step
step = @errors.empty? ? @success_step : @error_step
step_code = get_step_code(step)
if step_code
logger.debug "Task '#{@name}': step result: " + (@errors.empty? ? "success" : "error")
_start_dsl(step_code)
else
_finished
end
end

def _notification_criterias_match(msg, criterias)
criterias.each_pair do |key, expected_val|
val = msg[key]
if expected_val.is_a? Regexp
return false if val !~ expected_val
else
return false if val != expected_val
end
end
true
end

def _setup
logger.debug "Task '#{@name}': created"
end

def base_lpath
File.join(Config::LIB_DIR, 'cyborghood-' + @bot.model.downcase, 'tasks')
end

def _start_dsl(step_code)
@dsl_runing = false
@subtasks = []
@cancel_on_start_error = false
@error_step = nil
@success_step = nil

begin
if step_code.is_a? String
instance_eval step_code
else
instance_eval &step_code
end
rescue
logger.error "Task '#{@name}': error in DSL: " + $!.to_s
logger.debug $!.backtrace.join("\n")
return
end

logger.debug "Task '#{@name}': begining step"

if @subtasks.empty?
_check_finished
else
@dsl_runing = true
@subtasks.each do |subtask|
# skip broken or canceled subtasks
next if subtask.finished?
subtask.do_it
end
end

true
end

def _finished
@@tasks_info_mutex.synchronize do
@@task_wip -= 1
logger.debug "Task '#{@name}': finished (#{@@task_wip} tasks remaining)"
end
end

# needed for mixin
# TODO: find a cleaner solution
def tasks_info_mutex
@@tasks_info_mutex
end

# needed for mixin
# TODO: find a cleaner solution
def registered_resources
@@registered_resources
end
end

# this empty class is used as a trick to be able to inject features
# as module.prepend does not exist yet
class Task < TaskBase
end
end
end
(2-2/2)