2015-08-26 01:42:46 +00: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?
|
2016-06-13 22:14:30 +00:00
|
|
|
builds.
|
2016-08-01 22:31:21 +00:00
|
|
|
# don't run projects which have not enabled shared runners and builds
|
|
|
|
joins(:project).where(projects: { shared_runners_enabled: true }).
|
|
|
|
joins('LEFT JOIN project_features ON ci_builds.gl_project_id = project_features.project_id').
|
2016-06-13 22:14:30 +00:00
|
|
|
|
|
|
|
# this returns builds that are ordered by number of running builds
|
|
|
|
# we prefer projects that don't use shared runners at all
|
|
|
|
joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.gl_project_id=project_builds.gl_project_id").
|
2016-08-01 22:31:21 +00:00
|
|
|
where('project_features.builds_access_level IS NULL or project_features.builds_access_level > 0').
|
2016-06-13 22:14:30 +00:00
|
|
|
order('COALESCE(project_builds.running_builds, 0) ASC', 'ci_builds.id ASC')
|
2015-08-26 01:42:46 +00:00
|
|
|
else
|
2016-06-13 19:52:41 +00:00
|
|
|
# do run projects which are only assigned to this runner (FIFO)
|
2016-08-01 22:31:21 +00:00
|
|
|
builds.where(project: current_runner.projects.with_builds_enabled).order('created_at ASC')
|
2015-08-26 01:42:46 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
build = builds.find do |build|
|
2016-06-08 07:19:49 +00:00
|
|
|
current_runner.can_pick?(build)
|
2015-08-26 01:42:46 +00:00
|
|
|
end
|
2015-09-28 12:44:07 +00:00
|
|
|
|
2015-08-26 01:42:46 +00:00
|
|
|
if build
|
|
|
|
# In case when 2 runners try to assign the same build, second runner will be declined
|
2016-10-20 07:33:44 +00:00
|
|
|
# with StateMachines::InvalidTransition or StaleObjectError when doing run! or save method.
|
|
|
|
build.runner_id = current_runner.id
|
|
|
|
build.run!
|
2015-08-26 01:42:46 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
build
|
|
|
|
|
2016-10-21 13:12:11 +00:00
|
|
|
rescue StateMachines::InvalidTransition, ActiveRecord::StaleObjectError
|
2015-08-26 01:42:46 +00:00
|
|
|
nil
|
|
|
|
end
|
2016-06-13 19:52:41 +00:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-06-13 22:14:30 +00:00
|
|
|
def running_builds_for_shared_runners
|
|
|
|
Ci::Build.running.where(runner: Ci::Runner.shared).
|
|
|
|
group(:gl_project_id).select(:gl_project_id, 'count(*) AS running_builds')
|
2016-06-13 19:52:41 +00:00
|
|
|
end
|
2015-08-26 01:42:46 +00:00
|
|
|
end
|
|
|
|
end
|