aboutsummaryrefslogtreecommitdiff
path: root/lib/main_loop.rb
blob: 93aaf9138bc28610953fbe266c64005f1807145a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
##
# Loops for getting new events from *sys/events*.
# This class is a singelton, because it should be
# the only looping thing.
class MainLoop
  include Singleton

#  class << self
#    attr_accessor :exception_tries
#  end
#
#  attr_accessor :ecs

  @exception_tries= 0

  def initialize
    Rails.logger.info "*** VIP merge and compute service started ***"
    @ecs= HttpEcs.instance
  end

  def start
    loop do
      evbody=JSON::parse((ev=read_event).body)
      if evbody.blank?
        #Rails.logger.info "MainLoop#start: "
        sleep(1)
      else
        if evbody[0]["ressource"].start_with?(APP_CONFIG["eventtypes"]["job"]["name"])
          Rails.logger.info "received \"#{APP_CONFIG["eventtypes"]["job"]["name"]}\" event type"
          JobEvent.new.process(evbody)
        elsif evbody[0]["ressource"].start_with?(APP_CONFIG["eventtypes"]["result"]["name"])
          Rails.logger.info "received \"#{APP_CONFIG["eventtypes"]["result"]["name"]}\" event type"
          process_result_event(evbody)
        else
          Rails.logger.info "Unknown event type"
        end
      end
    end
  rescue => e
    Rails.logger.error "MainLoop#start:Exception: #{e.class}: #{e.message}"
    Rails.logger.error Rails.backtrace_cleaner.clean(e.backtrace)
    #retry if MainLoop.try_ones_more?
  end

  private

  def self.try_ones_more?
    if MainLoop.exception_tries < 1
      sleep(2**MainLoop.exception_tries)
      MainLoop.exception_tries+= 1
      true
    else
      false
    end
  end

  def read_event
    @ecs.connection["sys/events/fifo"].post ""
  end

  def process_result_event(evbody)
    path= evbody[0]['ressource']
    result= @ecs.connection[path].delete
    Rails.logger.info "***** MainLoop#process_result_event: #{path} = #{result}"
    # remove exercise referenced through solution embedded in result
    path= URI(JSON::parse(result)["Result"]["Solution"]["exercise"]).path[1..-1]
    @ecs.connection[path].delete
  end

end