Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[arvados.git] / services / api / lib / simulate_job_log.rb
1 module SimulateJobLog
2   def replay(filename, multiplier = 1, simulated_job_uuid = nil)
3     raise "Environment must be development or test" unless [ 'test', 'development' ].include? ENV['RAILS_ENV']
4
5     multiplier = multiplier.to_f
6     multiplier = 1.0 if multiplier <= 0
7
8     actual_start_time = Time.now
9     log_start_time = nil
10
11     act_as_system_user do
12       File.open(filename).each.with_index do |line, index|
13         cols = {}
14         cols[:timestamp], rest_of_line = line.split(' ', 2)
15         begin
16           cols[:timestamp] = Time.strptime( cols[:timestamp], "%Y-%m-%d_%H:%M:%S" )
17         rescue ArgumentError
18           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}) (.*)/
19             # Wed Nov 19 07:12:39 2014
20             cols[:timestamp] = Time.strptime( $1, "%a %b %d %H:%M:%S %Y" )
21             rest_of_line = $2
22           else
23               STDERR.puts "Ignoring log line because of unknown time format: #{line}"
24           end
25         end
26         cols[:job_uuid], cols[:pid], cols[:task], cols[:event_type], cols[:message] = rest_of_line.split(' ', 5)
27         # Override job uuid with a simulated one if specified
28         cols[:job_uuid] = simulated_job_uuid || cols[:job_uuid]
29         # determine when we want to simulate this log being created, based on the time multiplier
30         log_start_time = cols[:timestamp] if log_start_time.nil?
31         log_time = cols[:timestamp]
32         actual_elapsed_time = Time.now - actual_start_time
33         log_elapsed_time = log_time - log_start_time
34         modified_elapsed_time = log_elapsed_time / multiplier
35         pause_time = modified_elapsed_time - actual_elapsed_time
36         sleep pause_time if pause_time > 0
37         # output log entry for debugging and create it in the current environment's database
38         puts "#{index} #{cols.to_yaml}\n"
39         Log.new({
40           event_at:    Time.zone.local_to_utc(cols[:timestamp]),
41           object_uuid: cols[:job_uuid],
42           event_type:  cols[:event_type],
43           properties:  { 'text' => line }
44         }).save!
45       end
46     end
47
48   end
49 end