summaryrefslogtreecommitdiff
path: root/app/services/ci/pipelines/add_job_service.rb
blob: 1a5c8d0dccf68aa1c4324b3a6100a376856c106d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

module Ci
  module Pipelines
    class AddJobService
      include ::Gitlab::ExclusiveLeaseHelpers

      attr_reader :pipeline

      def initialize(pipeline)
        @pipeline = pipeline

        raise ArgumentError, "Pipeline must be persisted for this service to be used" unless pipeline.persisted?
      end

      def execute!(job, &block)
        assign_pipeline_attributes(job)

        in_lock("ci:pipelines:#{pipeline.id}:add-job", ttl: LOCK_TIMEOUT, sleep_sec: LOCK_SLEEP, retries: LOCK_RETRIES) do
          Ci::Pipeline.transaction do
            # This is used to reduce the deadlocks when partitioning `ci_builds`
            # since inserting into this table requires locks on all foreign keys
            # and we need to lock all the tables in a specific order for the
            # migration to succeed.
            Ci::Pipeline.connection.execute('LOCK "ci_pipelines", "ci_stages" IN ROW SHARE MODE;')

            yield(job)

            job.update_older_statuses_retried!
          end
        end

        ServiceResponse.success(payload: { job: job })
      rescue StandardError => e
        ServiceResponse.error(message: e.message, payload: { job: job })
      end

      private

      LOCK_TIMEOUT = 1.minute
      LOCK_SLEEP = 0.5.seconds
      LOCK_RETRIES = 20

      def assign_pipeline_attributes(job)
        job.pipeline = pipeline
        job.project = pipeline.project
        job.ref = pipeline.ref
        job.partition_id = pipeline.partition_id

        # update metadata since it might have been lazily initialised before this call
        # metadata is present on `Ci::Processable`
        if job.respond_to?(:metadata) && job.metadata
          job.metadata.project = pipeline.project
          job.metadata.partition_id = pipeline.partition_id
        end
      end
    end
  end
end