BigW Consortium Gitlab

stuck_ci_jobs_worker.rb 1.62 KB
Newer Older
1
class StuckCiJobsWorker
2
  include Sidekiq::Worker
3
  include CronjobQueue
4

Tomasz Maczukin committed
5
  EXCLUSIVE_LEASE_KEY = 'stuck_ci_builds_worker_lease'.freeze
Tomasz Maczukin committed
6

7 8 9
  BUILD_RUNNING_OUTDATED_TIMEOUT = 1.hour
  BUILD_PENDING_OUTDATED_TIMEOUT = 1.day
  BUILD_PENDING_STUCK_TIMEOUT = 1.hour
10 11

  def perform
12 13 14
    return unless try_obtain_lease

    Rails.logger.info "#{self.class}: Cleaning stuck builds"
15

Tomasz Maczukin committed
16 17
    drop :running, BUILD_RUNNING_OUTDATED_TIMEOUT
    drop :pending, BUILD_PENDING_OUTDATED_TIMEOUT
18
    drop_stuck :pending, BUILD_PENDING_STUCK_TIMEOUT
Tomasz Maczukin committed
19 20

    remove_lease
21 22 23 24
  end

  private

25
  def try_obtain_lease
Tomasz Maczukin committed
26
    @uuid = Gitlab::ExclusiveLease.new(EXCLUSIVE_LEASE_KEY, timeout: 30.minutes).try_obtain
27 28
  end

Tomasz Maczukin committed
29 30 31 32
  def remove_lease
    Gitlab::ExclusiveLease.cancel(EXCLUSIVE_LEASE_KEY, @uuid)
  end

33 34 35 36 37 38 39 40 41 42
  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
43
    end
44 45 46 47
  end

  def search(status, timeout)
    builds = Ci::Build.where(status: status).where('ci_builds.updated_at < ?', timeout.ago)
48
    builds.joins(:project).merge(Project.without_deleted).includes(:tags, :runner, project: :namespace).find_each(batch_size: 50).each do |build|
49 50 51
      yield(build)
    end
  end
52

53
  def drop_build(type, build, status, timeout)
54
    Rails.logger.info "#{self.class}: Dropping #{type} build #{build.id} for runner #{build.runner_id} (status: #{status}, timeout: #{timeout})"
55 56 57
    Gitlab::OptimisticLocking.retry_lock(build, 3) do |b|
      b.drop
    end
58 59
  end
end