process_pipeline_service.rb 1.52 KB
Newer Older
1
2
3
4
5
6
7
module Ci
  class ProcessPipelineService < BaseService
    attr_reader :pipeline

    def execute(pipeline)
      @pipeline = pipeline

Kamil Trzcinski's avatar
Kamil Trzcinski committed
8
9
10
11
      new_builds =
        stage_indexes_of_created_builds.map do |index|
          process_stage(index)
        end
12

Kamil Trzcinski's avatar
Kamil Trzcinski committed
13
      @pipeline.update_status
14

Kamil Trzcinski's avatar
Kamil Trzcinski committed
15
      new_builds.flatten.any?
16
17
18
19
20
21
22
    end

    private

    def process_stage(index)
      current_status = status_for_prior_stages(index)

Kamil Trzcinski's avatar
Kamil Trzcinski committed
23
24
      if HasStatus::COMPLETED_STATUSES.include?(current_status)
        created_builds_in_stage(index).select do |build|
25
26
          Gitlab::OptimisticLocking.retry_lock(build) do |subject|
            process_build(subject, current_status)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
27
          end
28
        end
29
30
31
32
33
      end
    end

    def process_build(build, current_status)
      if valid_statuses_for_when(build.when).include?(current_status)
Stan Hu's avatar
Stan Hu committed
34
        build.enqueue
35
36
        true
      else
Stan Hu's avatar
Stan Hu committed
37
        build.skip
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
        false
      end
    end

    def valid_statuses_for_when(value)
      case value
      when 'on_success'
        %w[success]
      when 'on_failure'
        %w[failed]
      when 'always'
        %w[success failed]
      else
        []
      end
    end

    def status_for_prior_stages(index)
      pipeline.builds.where('stage_idx < ?', index).latest.status || 'success'
    end

    def stage_indexes_of_created_builds
      created_builds.order(:stage_idx).pluck('distinct stage_idx')
    end

    def created_builds_in_stage(index)
      created_builds.where(stage_idx: index)
    end

    def created_builds
      pipeline.builds.created
    end
  end
end