2015-08-25 21:42:46 -04:00
|
|
|
module Ci
|
|
|
|
# This class responsible for assigning
|
|
|
|
# proper pending build to runner on runner API request
|
|
|
|
class RegisterBuildService
|
|
|
|
def execute(current_runner)
|
|
|
|
builds = Ci::Build.pending.unstarted
|
|
|
|
|
|
|
|
builds =
|
|
|
|
if current_runner.shared?
|
|
|
|
# don't run projects which have not enables shared runners
|
2015-12-04 06:55:23 -05:00
|
|
|
builds.joins(:project).where(projects: { builds_enabled: true, shared_runners_enabled: true })
|
2015-08-25 21:42:46 -04:00
|
|
|
else
|
|
|
|
# do run projects which are only assigned to this runner
|
2015-12-11 12:03:48 -05:00
|
|
|
builds.where(project: current_runner.projects.where(builds_enabled: true))
|
2015-08-25 21:42:46 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
builds = builds.order('created_at ASC')
|
|
|
|
|
|
|
|
build = builds.find do |build|
|
2015-10-12 15:12:31 -04:00
|
|
|
build.can_be_served?(current_runner)
|
2015-08-25 21:42:46 -04:00
|
|
|
end
|
2015-09-28 08:44:07 -04:00
|
|
|
|
2015-08-25 21:42:46 -04:00
|
|
|
if build
|
|
|
|
# In case when 2 runners try to assign the same build, second runner will be declined
|
2015-12-04 06:55:23 -05:00
|
|
|
# with StateMachines::InvalidTransition in run! method.
|
2015-08-25 21:42:46 -04:00
|
|
|
build.with_lock do
|
|
|
|
build.runner_id = current_runner.id
|
|
|
|
build.save!
|
|
|
|
build.run!
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
build
|
|
|
|
|
2015-12-04 06:55:23 -05:00
|
|
|
rescue StateMachines::InvalidTransition
|
2015-08-25 21:42:46 -04:00
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|