module Eco module API class Session class Batch class JobsGroups < API::Common::Session::BaseSession DELAY_BETWEEN_GROUPS = 2 class << self def counter(seconds) puts "\n" while seconds + 1 > 0 do print " Waiting #{seconds}\r" $stdout.flush seconds -= 1 sleep 1 end print "#{" " * 40}" $stdout.flush puts "" end end include Enumerable def initialize(e) super(e) reset end def reset @order = [] @groups = {} @callbacks = {} end def length count end def empty? count == 0 end def each(&block) return to_enum(:each) unless block items.each(&block) end def items @groups.values end def [](name) @groups[name] end def exists?(name) @groups.key?(name) end # Creates a new group of `Batch::Jobs` named `name`. # @yield [group, group_status] callback after launching the batch job request against the server. # @yieldparam group [Eco::API::Session::Batch::Jobs] the group of jobs we have launched against the server. # @yieldparam group_status [Hash] the status of the launched batch jobs. # @return [Eco::API::Session::Batch::Jobs] the group of jobs. def new(name, order: :last, &block) fatal "Can't create job group named '#{name}' because it already exists." if exists?(name) Batch::Jobs.new(enviro, name: name).tap do |group| @groups[name] = group if order == :last @order.push(group) else @order.unshift(group) end @callbacks[group] = block if block_given? end end def pending? any? {|group| group.pending?} end # Launches every `Batch::Jobs` group in the current `Batch::JobGroups` # @note # - if there was post-launch callback for a `Batch::Jobs` groups, it calls it. # @return [Hash>] def launch(simulate: false) @order.each_with_index do |group, idx| if group.pending? status[group] = group_status = group.launch(simulate: simulate) callback = @callbacks[group] callback.call(group, group_status) if callback self.class.counter(delay_between_groups) if !simulate && idx < @order.length - 1 end end launch(simulate: simulate) if pending? return status end def find_jobs(type:) each_with_object([]) do |group, jbs| jbs.concat(group.find_jobs(type: type)) end end def status if block_given? status.each do |group, group_status| yield(group, group_status) end self else @groups_status ||= {} end end def errors? any? {|group| group.errors?} end def summary [].tap do |msg| map {|group| msg << group.summary} end.join("\n") end private def delay_between_groups config.delay_between_job_groups || DELAY_BETWEEN_GROUPS end end end end end end