8784: Fix test for latest firefox.
[arvados.git] / services / api / lib / simulate_job_log.rb
1 require 'current_api_client'
2
3 module SimulateJobLog
4   include CurrentApiClient
5   def replay(filename, multiplier = 1, simulated_job_uuid = nil)
6     raise "Environment must be development or test" unless [ 'test', 'development' ].include? ENV['RAILS_ENV']
7
8     multiplier = multiplier.to_f
9     multiplier = 1.0 if multiplier <= 0
10
11     actual_start_time = Time.now
12     log_start_time = nil
13
14     if simulated_job_uuid and (job = Job.where(uuid: simulated_job_uuid).first)
15       job_owner_uuid = job.owner_uuid
16     else
17       job_owner_uuid = system_user_uuid
18     end
19
20     act_as_system_user do
21       File.open(filename).each.with_index do |line, index|
22         cols = {}
23         cols[:timestamp], rest_of_line = line.split(' ', 2)
24         begin
25           cols[:timestamp] = Time.strptime( cols[:timestamp], "%Y-%m-%d_%H:%M:%S" )
26         rescue ArgumentError
27           if line =~ /^((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d\d:\d\d:\d\d \d{4}) (.*)/
28             # Wed Nov 19 07:12:39 2014
29             cols[:timestamp] = Time.strptime( $1, "%a %b %d %H:%M:%S %Y" )
30             rest_of_line = $2
31           else
32               STDERR.puts "Ignoring log line because of unknown time format: #{line}"
33           end
34         end
35         cols[:job_uuid], cols[:pid], cols[:task], cols[:event_type], cols[:message] = rest_of_line.split(' ', 5)
36         # Override job uuid with a simulated one if specified
37         cols[:job_uuid] = simulated_job_uuid || cols[:job_uuid]
38         # determine when we want to simulate this log being created, based on the time multiplier
39         log_start_time = cols[:timestamp] if log_start_time.nil?
40         log_time = cols[:timestamp]
41         actual_elapsed_time = Time.now - actual_start_time
42         log_elapsed_time = log_time - log_start_time
43         modified_elapsed_time = log_elapsed_time / multiplier
44         pause_time = modified_elapsed_time - actual_elapsed_time
45         sleep pause_time if pause_time > 0
46
47         Log.new({
48           owner_uuid:  job_owner_uuid,
49           event_at:    Time.zone.local_to_utc(cols[:timestamp]),
50           object_uuid: cols[:job_uuid],
51           event_type:  cols[:event_type],
52           properties:  { 'text' => line }
53         }).save!
54       end
55     end
56
57   end
58 end