gitlab-org--gitlab-foss/app/workers/stuck_ci_jobs_worker.rb

60 lines
1.6 KiB
Ruby
Raw Normal View History

class StuckCiJobsWorker
2015-10-21 05:29:47 -04:00
include Sidekiq::Worker
include CronjobQueue
2015-10-21 05:29:47 -04:00
2017-03-01 07:56:54 -05:00
EXCLUSIVE_LEASE_KEY = 'stuck_ci_builds_worker_lease'.freeze
2017-02-08 21:29:38 -05:00
BUILD_RUNNING_OUTDATED_TIMEOUT = 1.hour
BUILD_PENDING_OUTDATED_TIMEOUT = 1.day
BUILD_PENDING_STUCK_TIMEOUT = 1.hour
2015-10-21 05:29:47 -04:00
def perform
return unless try_obtain_lease
Rails.logger.info "#{self.class}: Cleaning stuck builds"
2015-10-21 05:29:47 -04:00
2017-02-08 21:29:38 -05:00
drop :running, BUILD_RUNNING_OUTDATED_TIMEOUT
drop :pending, BUILD_PENDING_OUTDATED_TIMEOUT
drop_stuck :pending, BUILD_PENDING_STUCK_TIMEOUT
2017-02-08 21:29:38 -05:00
remove_lease
end
private
def try_obtain_lease
2017-03-01 07:56:54 -05:00
@uuid = Gitlab::ExclusiveLease.new(EXCLUSIVE_LEASE_KEY, timeout: 30.minutes).try_obtain
end
2017-02-08 21:29:38 -05:00
def remove_lease
Gitlab::ExclusiveLease.cancel(EXCLUSIVE_LEASE_KEY, @uuid)
end
def drop(status, timeout)
search(status, timeout) do |build|
drop_build :outdated, build, status, timeout
end
end
def drop_stuck(status, timeout)
search(status, timeout) do |build|
return unless build.stuck?
drop_build :stuck, build, status, timeout
2015-10-21 05:29:47 -04:00
end
end
def search(status, timeout)
builds = Ci::Build.where(status: status).where('ci_builds.updated_at < ?', timeout.ago)
2017-06-15 08:06:49 -04:00
builds.joins(:project).merge(Project.without_deleted).includes(:tags, :runner, project: :namespace).find_each(batch_size: 50).each do |build|
yield(build)
end
end
def drop_build(type, build, status, timeout)
Rails.logger.info "#{self.class}: Dropping #{type} build #{build.id} for runner #{build.runner_id} (status: #{status}, timeout: #{timeout})"
Gitlab::OptimisticLocking.retry_lock(build, 3) do |b|
2017-08-31 09:03:41 -04:00
b.drop(:stuck_or_timeout_failure)
end
2015-10-21 05:29:47 -04:00
end
end