2018-10-22 10:49:20 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Checks
|
|
|
|
class TimedLogger
|
|
|
|
TimeoutError = Class.new(StandardError)
|
|
|
|
|
2018-10-25 04:49:59 -04:00
|
|
|
attr_reader :start_time, :header, :log, :timeout
|
2018-10-22 10:49:20 -04:00
|
|
|
|
2018-10-25 05:36:40 -04:00
|
|
|
def initialize(start_time: Time.now, log: [], header: "", timeout:)
|
2018-10-22 10:49:20 -04:00
|
|
|
@start_time = start_time
|
|
|
|
@timeout = timeout
|
2018-10-25 04:49:59 -04:00
|
|
|
@header = header
|
2018-10-22 10:49:20 -04:00
|
|
|
@log = log
|
|
|
|
end
|
|
|
|
|
2018-10-25 04:49:59 -04:00
|
|
|
# Adds trace of method being tracked with
|
2018-10-25 05:36:40 -04:00
|
|
|
# the correspondent time it took to run it.
|
|
|
|
# We make use of the start default argument
|
|
|
|
# on unit tests related to this method
|
2018-10-25 04:49:59 -04:00
|
|
|
#
|
2018-10-22 10:49:20 -04:00
|
|
|
def log_timed(log_message, start = Time.now)
|
|
|
|
check_timeout_reached
|
|
|
|
|
|
|
|
timed = true
|
|
|
|
|
|
|
|
yield
|
|
|
|
|
2018-10-25 04:49:59 -04:00
|
|
|
append_message(log_message + time_suffix_message(start: start))
|
2018-10-22 10:49:20 -04:00
|
|
|
rescue GRPC::DeadlineExceeded, TimeoutError
|
|
|
|
args = { cancelled: true }
|
|
|
|
args[:start] = start if timed
|
|
|
|
|
2020-12-10 07:09:43 -05:00
|
|
|
append_message(log_message + time_suffix_message(**args))
|
2018-10-22 10:49:20 -04:00
|
|
|
|
|
|
|
raise TimeoutError
|
|
|
|
end
|
|
|
|
|
|
|
|
def check_timeout_reached
|
|
|
|
return unless time_expired?
|
|
|
|
|
|
|
|
raise TimeoutError
|
|
|
|
end
|
|
|
|
|
|
|
|
def time_left
|
|
|
|
(start_time + timeout.seconds) - Time.now
|
|
|
|
end
|
|
|
|
|
2018-10-25 04:49:59 -04:00
|
|
|
def full_message
|
|
|
|
header + log.join("\n")
|
|
|
|
end
|
|
|
|
|
|
|
|
# We always want to append in-place on the log
|
|
|
|
def append_message(message)
|
|
|
|
log << message
|
|
|
|
end
|
|
|
|
|
2018-10-22 10:49:20 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def time_expired?
|
|
|
|
time_left <= 0
|
|
|
|
end
|
|
|
|
|
|
|
|
def time_suffix_message(cancelled: false, start: nil)
|
|
|
|
return " (#{elapsed_time(start)}ms)" unless cancelled
|
|
|
|
|
|
|
|
if start
|
|
|
|
" (cancelled after #{elapsed_time(start)}ms)"
|
|
|
|
else
|
|
|
|
" (cancelled)"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def elapsed_time(start)
|
|
|
|
to_ms(Time.now - start)
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_ms(elapsed)
|
|
|
|
(elapsed.to_f * 1000).round(2)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|