build.rb 29.5 KB
Newer Older
1 2
# frozen_string_literal: true

D
Douwe Maan 已提交
3
module Ci
4
  class Build < Ci::Processable
5
    include Ci::Metadatable
6
    include Ci::Contextable
7
    include Ci::PipelineDelegator
8
    include TokenAuthenticatable
9
    include AfterCommitQueue
10
    include ObjectStorage::BackgroundMove
R
Rémy Coutable 已提交
11
    include Presentable
S
Shinya Maeda 已提交
12
    include Importable
13
    include Ci::HasRef
14
    include IgnorableColumns
15

16 17
    BuildArchivedError = Class.new(StandardError)

18
    ignore_columns :artifacts_file, :artifacts_file_store, :artifacts_metadata, :artifacts_metadata_store, :artifacts_size, :commands, remove_after: '2019-12-15', remove_with: '12.7'
19

20
    belongs_to :project, inverse_of: :builds
21 22
    belongs_to :runner
    belongs_to :trigger_request
23
    belongs_to :erased_by, class_name: 'User'
24
    belongs_to :resource_group, class_name: 'Ci::ResourceGroup', inverse_of: :builds
25
    belongs_to :pipeline, class_name: 'Ci::Pipeline', foreign_key: :commit_id
D
Douwe Maan 已提交
26

27
    RUNNER_FEATURES = {
28 29
      upload_multiple_artifacts: -> (build) { build.publishes_artifacts_reports? },
      refspecs: -> (build) { build.merge_request_ref? }
30 31
    }.freeze

32 33 34 35
    DEFAULT_RETRIES = {
      scheduler_failure: 2
    }.freeze

S
Shinya Maeda 已提交
36
    has_one :deployment, as: :deployable, class_name: 'Deployment'
37
    has_one :resource, class_name: 'Ci::Resource', inverse_of: :build
38
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
39
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
40

41
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
M
Matija Čupić 已提交
42
    has_many :job_variables, class_name: 'Ci::JobVariable', foreign_key: :job_id
43
    has_many :sourced_pipelines, class_name: 'Ci::Sources::Pipeline', foreign_key: :source_job_id
S
Shinya Maeda 已提交
44 45 46 47

    Ci::JobArtifact.file_types.each do |key, value|
      has_one :"job_artifacts_#{key}", -> { where(file_type: value) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
    end
48

F
Francisco Javier López 已提交
49 50
    has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build

51
    accepts_nested_attributes_for :runner_session, update_only: true
M
Matija Čupić 已提交
52
    accepts_nested_attributes_for :job_variables
F
Francisco Javier López 已提交
53 54 55

    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
56
    delegate :gitlab_deploy_token, to: :project
57
    delegate :trigger_short_token, to: :trigger_request, allow_nil: true
T
Tomasz Maczukin 已提交
58

59
    ##
60 61
    # Since Gitlab 11.5, deployments records started being created right after
    # `ci_builds` creation. We can look up a relevant `environment` through
62
    # `deployment` relation today.
63
    # (See more https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/22380)
64
    #
65 66
    # Since Gitlab 12.9, we started persisting the expanded environment name to
    # avoid repeated variables expansion in `action: stop` builds as well.
67
    def persisted_environment
68 69 70
      return unless has_environment?

      strong_memoize(:persisted_environment) do
71 72
        deployment&.environment ||
          Environment.find_by(name: expanded_environment_name, project: project)
73
      end
74 75
    end

76 77
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
78

D
Douwe Maan 已提交
79 80
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
81
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
82
    validates :ref, presence: true
D
Douwe Maan 已提交
83

84 85 86 87 88
    scope :not_interruptible, -> do
      joins(:metadata).where('ci_builds_metadata.id NOT IN (?)',
        Ci::BuildMetadata.scoped_build.with_interruptible.select(:id))
    end

D
Douwe Maan 已提交
89
    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
90
    scope :ignore_failures, ->() { where(allow_failure: false) }
91
    scope :with_artifacts_archive, ->() do
92
      where('EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
93
    end
94

95 96 97 98
    scope :with_existing_job_artifacts, ->(query) do
      where('EXISTS (?)', ::Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').merge(query))
    end

99
    scope :with_archived_trace, ->() do
100
      with_existing_job_artifacts(Ci::JobArtifact.trace)
101 102
    end

103 104 105 106
    scope :without_archived_trace, ->() do
      where('NOT EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').trace)
    end

M
Matija Čupić 已提交
107 108
    scope :with_reports, ->(reports_scope) do
      with_existing_job_artifacts(reports_scope)
109
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
110 111
    end

112
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }
113
    scope :eager_load_job_artifacts_archive, -> { includes(:job_artifacts_archive) }
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128
    scope :eager_load_everything, -> do
      includes(
        [
          { pipeline: [:project, :user] },
          :job_artifacts_archive,
          :metadata,
          :trigger_request,
          :project,
          :user,
          :tags
        ]
      )
    end

129 130 131 132 133
    scope :with_exposed_artifacts, -> do
      joins(:metadata).merge(Ci::BuildMetadata.with_exposed_artifacts)
        .includes(:metadata, :job_artifacts_metadata)
    end

134 135
    scope :with_artifacts_not_expired, ->() { with_artifacts_archive.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
    scope :with_expired_artifacts, ->() { with_artifacts_archive.where('artifacts_expire_at < ?', Time.now) }
136
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
137 138
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
139
    scope :ref_protected, -> { where(protected: true) }
140
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
141 142
    scope :with_stale_live_trace, -> { with_live_trace.finished_before(12.hours.ago) }
    scope :finished_before, -> (date) { finished.where('finished_at < ?', date) }
143

144 145 146 147 148 149
    scope :with_secure_reports_from_options, -> (job_type) { where('options like :job_type', job_type: "%:artifacts:%:reports:%:#{job_type}:%") }

    scope :with_secure_reports_from_config_options, -> (job_types) do
      joins(:metadata).where("ci_builds_metadata.config_options -> 'artifacts' -> 'reports' ?| array[:job_types]", job_types: job_types)
    end

150 151
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
152
        .where(taggable_type: CommitStatus.name)
153 154 155 156 157 158 159 160 161
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id')
        .where.not(tag_id: tag_ids).select('1')

      where("NOT EXISTS (?)", matcher)
    end

    scope :with_any_tags, -> do
      matcher = ::ActsAsTaggableOn::Tagging
162
        .where(taggable_type: CommitStatus.name)
163 164 165 166 167 168
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

      where("EXISTS (?)", matcher)
    end

169
    scope :queued_before, ->(time) { where(arel_table[:queued_at].lt(time)) }
170
    scope :order_id_desc, -> { order('ci_builds.id DESC') }
171

172 173 174 175
    scope :preload_project_and_pipeline_project, -> do
      preload(Ci::Pipeline::PROJECT_ROUTE_AND_NAMESPACE_ROUTE,
              pipeline: Ci::Pipeline::PROJECT_ROUTE_AND_NAMESPACE_ROUTE)
    end
176

D
Douwe Maan 已提交
177 178
    acts_as_taggable

K
Kamil Trzciński 已提交
179
    add_authentication_token_field :token, encrypted: :optional
180 181

    before_save :ensure_token
182
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
183

184
    after_create unless: :importing? do |build|
185
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
186 187
    end

D
Douwe Maan 已提交
188
    class << self
189 190 191 192 193 194
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

D
Douwe Maan 已提交
195 196 197 198
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

199
      def retry(build, current_user)
200
        # rubocop: disable CodeReuse/ServiceClass
201 202 203
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
204
        # rubocop: enable CodeReuse/ServiceClass
D
Douwe Maan 已提交
205 206 207
      end
    end

208
    state_machine :status do
T
Tiger 已提交
209
      event :enqueue do
210
        transition [:created, :skipped, :manual, :scheduled] => :waiting_for_resource, if: :requires_resource?
T
Tiger 已提交
211 212 213
        transition [:created, :skipped, :manual, :scheduled] => :preparing, if: :any_unmet_prerequisites?
      end

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      event :enqueue_scheduled do
        transition scheduled: :waiting_for_resource, if: :requires_resource?
        transition scheduled: :preparing, if: :any_unmet_prerequisites?
        transition scheduled: :pending
      end

      event :enqueue_waiting_for_resource do
        transition waiting_for_resource: :preparing, if: :any_unmet_prerequisites?
        transition waiting_for_resource: :pending
      end

      event :enqueue_preparing do
        transition preparing: :pending
      end

229 230
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
231 232
      end

233 234 235 236 237 238 239 240
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

241 242
      before_transition on: :enqueue_scheduled do |build|
        build.scheduled_at.nil? || build.scheduled_at.past? # If false is returned, it stops the transition
243 244 245
      end

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
246 247 248 249
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
250
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
251 252
      end

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
      before_transition any => :waiting_for_resource do |build|
        build.waiting_for_resource_at = Time.now
      end

      before_transition on: :enqueue_waiting_for_resource do |build|
        next unless build.requires_resource?

        build.resource_group.assign_resource_to(build) # If false is returned, it stops the transition
      end

      after_transition any => :waiting_for_resource do |build|
        build.run_after_commit do
          Ci::ResourceGroups::AssignResourceFromResourceGroupWorker
            .perform_async(build.resource_group_id)
        end
      end

      before_transition on: :enqueue_preparing do |build|
271
        !build.any_unmet_prerequisites? # If false is returned, it stops the transition
272 273
      end

S
Shinya Maeda 已提交
274 275 276 277
      after_transition created: :scheduled do |build|
        build.run_after_commit do
          Ci::BuildScheduleWorker.perform_at(build.scheduled_at, build.id)
        end
278 279
      end

T
Tiger 已提交
280 281 282 283 284 285
      after_transition any => [:preparing] do |build|
        build.run_after_commit do
          Ci::BuildPrepareWorker.perform_async(id)
        end
      end

286 287
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
288
          BuildQueueWorker.perform_async(id)
289 290 291
        end
      end

292
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
293 294
        build.deployment&.run

295
        build.run_after_commit do
296 297
          build.pipeline.persistent_ref.create

298 299
          BuildHooksWorker.perform_async(id)
        end
300 301
      end

302 303 304 305 306 307 308 309 310 311
      after_transition any => ::Ci::Build.completed_statuses do |build|
        next unless build.resource_group_id.present?
        next unless build.resource_group.release_resource_from(build)

        build.run_after_commit do
          Ci::ResourceGroups::AssignResourceFromResourceGroupWorker
            .perform_async(build.resource_group_id)
        end
      end

312
      after_transition any => [:success, :failed, :canceled] do |build|
313
        build.run_after_commit do
314
          BuildFinishedWorker.perform_async(id)
315
        end
D
Douwe Maan 已提交
316
      end
317

318
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
319 320
        build.deployment&.succeed

321
        build.run_after_commit do
322
          BuildSuccessWorker.perform_async(id)
323
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
324 325
        end
      end
326

327
      before_transition any => [:failed] do |build|
328
        next unless build.project
329
        next unless build.deployment
S
Shinya Maeda 已提交
330

331 332 333
        begin
          build.deployment.drop!
        rescue => e
334
          Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e, build_id: build.id)
335 336 337
        end

        true
338 339 340 341
      end

      after_transition any => [:failed] do |build|
        next unless build.project
S
Shinya Maeda 已提交
342

343
        if build.retry_failure?
344 345 346
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
M
Mayra Cabrera 已提交
347
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}" # rubocop:disable Gitlab/RailsLogger
348
          end
349 350
        end
      end
351

352
      after_transition pending: :running do |build|
353
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
354
      end
F
Francisco Javier López 已提交
355 356 357 358

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
359 360 361 362

      after_transition any => [:skipped, :canceled] do |build|
        build.deployment&.cancel
      end
D
Douwe Maan 已提交
363 364
    end

365
    def detailed_status(current_user)
366 367 368
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
369 370
    end

371
    def other_manual_actions
372
      pipeline.manual_actions.where.not(name: name)
373 374
    end

375 376
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
377 378
    end

379 380 381 382 383
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

384 385 386 387
    def runnable?
      true
    end

388 389 390 391 392 393 394
    def archived?
      return true if degenerated?

      archive_builds_older_than = Gitlab::CurrentSettings.current_application_settings.archive_builds_older_than
      archive_builds_older_than.present? && created_at < archive_builds_older_than
    end

395
    def playable?
396
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
397 398
    end

S
Shinya Maeda 已提交
399
    def schedulable?
400
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
401 402
    end

S
Shinya Maeda 已提交
403
    def options_scheduled_at
S
Shinya Maeda 已提交
404
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
405 406
    end

407
    def action?
408
      %w[manual delayed].include?(self.when)
409 410
    end

411
    # rubocop: disable CodeReuse/ServiceClass
M
Matija Čupić 已提交
412
    def play(current_user, job_variables_attributes = nil)
413 414
      Ci::PlayBuildService
        .new(project, current_user)
M
Matija Čupić 已提交
415
        .execute(self, job_variables_attributes)
416
    end
417
    # rubocop: enable CodeReuse/ServiceClass
418

K
Kamil Trzcinski 已提交
419
    def cancelable?
J
Jacopo 已提交
420
      active? || created?
K
Kamil Trzcinski 已提交
421 422
    end

K
Kamil Trzcinski 已提交
423
    def retryable?
K
Kamil Trzciński 已提交
424
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
425
    end
426 427 428 429 430

    def retries_count
      pipeline.builds.retried.where(name: self.name).count
    end

431 432 433 434 435 436
    def retry_failure?
      max_allowed_retries = nil
      max_allowed_retries ||= options_retry_max if retry_on_reason_or_always?
      max_allowed_retries ||= DEFAULT_RETRIES.fetch(failure_reason.to_sym, 0)

      max_allowed_retries > 0 && retries_count < max_allowed_retries
437
    end
K
Kamil Trzcinski 已提交
438

439 440
    def options_retry_max
      options_retry[:max]
441 442
    end

443 444 445
    def options_retry_when
      options_retry.fetch(:when, ['always'])
    end
446

447 448 449
    def retry_on_reason_or_always?
      options_retry_when.include?(failure_reason.to_s) ||
        options_retry_when.include?('always')
450
    end
K
Kamil Trzcinski 已提交
451

T
Tiger 已提交
452 453 454 455 456 457 458 459
    def any_unmet_prerequisites?
      prerequisites.present?
    end

    def prerequisites
      Gitlab::Ci::Build::Prerequisite::Factory.new(self).unmet
    end

460
    def expanded_environment_name
461 462 463
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
464 465 466 467 468 469 470 471
        # We're using a persisted expanded environment name in order to avoid
        # variable expansion per request.
        if Feature.enabled?(:ci_persisted_expanded_environment_name, project, default_enabled: true) &&
          metadata&.expanded_environment_name.present?
          metadata.expanded_environment_name
        else
          ExpandVariables.expand(environment, -> { simple_variables })
        end
472
      end
473 474
    end

475 476 477 478 479 480 481 482 483 484 485 486
    def expanded_kubernetes_namespace
      return unless has_environment?

      namespace = options.dig(:environment, :kubernetes, :namespace)

      if namespace.present?
        strong_memoize(:expanded_kubernetes_namespace) do
          ExpandVariables.expand(namespace, -> { simple_variables })
        end
      end
    end

487
    def requires_resource?
488
      Feature.enabled?(:ci_resource_group, project, default_enabled: true) &&
489 490 491
        self.resource_group_id.present?
    end

492
    def has_environment?
493
      environment.present?
494 495
    end

496
    def starts_environment?
497
      has_environment? && self.environment_action == 'start'
498 499 500
    end

    def stops_environment?
501
      has_environment? && self.environment_action == 'stop'
502 503 504
    end

    def environment_action
505
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
506 507 508
    end

    def outdated_deployment?
S
Shinya Maeda 已提交
509
      success? && !deployment.try(:last?)
510
    end
511

512 513
    def depends_on_builds
      # Get builds of the same type
514
      latest_builds = self.pipeline.builds.latest
515 516 517 518 519

      # Return builds from previous stages
      latest_builds.where('stage_idx < ?', stage_idx)
    end

520
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
521 522 523
      user == current_user
    end

S
Shinya Maeda 已提交
524 525 526 527
    def on_stop
      options&.dig(:environment, :on_stop)
    end

528 529 530 531
    ##
    # All variables, including persisted environment variables.
    #
    def variables
532 533 534 535
      strong_memoize(:variables) do
        Gitlab::Ci::Variables::Collection.new
          .concat(persisted_variables)
          .concat(scoped_variables)
M
Matija Čupić 已提交
536
          .concat(job_variables)
537
          .concat(environment_changed_page_variables)
538 539 540
          .concat(persisted_environment_variables)
          .to_runner_variables
      end
541 542
    end

543
    CI_REGISTRY_USER = 'gitlab-ci-token'
544 545 546 547 548 549 550 551 552

    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        break variables unless persisted?

        variables
          .concat(pipeline.persisted_variables)
          .append(key: 'CI_JOB_ID', value: id.to_s)
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
553
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false, masked: true)
554
          .append(key: 'CI_BUILD_ID', value: id.to_s)
555
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false, masked: true)
556
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
557
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false, masked: true)
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
          .append(key: 'CI_REPOSITORY_URL', value: repo_url.to_s, public: false)
          .concat(deploy_token_variables)
      end
    end

    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        break variables unless persisted? && persisted_environment.present?

        variables.concat(persisted_environment.predefined_variables)

        # Here we're passing unexpanded environment_url for runner to expand,
        # and we need to make sure that CI_ENVIRONMENT_NAME and
        # CI_ENVIRONMENT_SLUG so on are available for the URL be expanded.
        variables.append(key: 'CI_ENVIRONMENT_URL', value: environment_url) if environment_url
      end
    end

576 577 578 579 580 581 582 583 584
    def environment_changed_page_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        break variables unless environment_status

        variables.append(key: 'CI_MERGE_REQUEST_CHANGED_PAGE_PATHS', value: environment_status.changed_paths.join(','))
        variables.append(key: 'CI_MERGE_REQUEST_CHANGED_PAGE_URLS', value: environment_status.changed_urls.join(','))
      end
    end

585 586 587 588 589
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        break variables unless gitlab_deploy_token

        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
590
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false, masked: true)
591
      end
592 593
    end

594 595 596 597
    def features
      { trace_sections: true }
    end

598
    def merge_request
Z
Z.J. van de Weg 已提交
599
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
600

601 602
      @merge_request ||=
        begin
603
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
604 605
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
606
            .reorder(iid: :desc)
607 608

          merge_requests.find do |merge_request|
609
            merge_request.commit_shas.include?(pipeline.sha)
610 611
          end
        end
612 613
    end

D
Douwe Maan 已提交
614
    def repo_url
K
Kamil Trzciński 已提交
615 616 617
      return unless token

      auth = "gitlab-ci-token:#{token}@"
618
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
619 620
        prefix + auth
      end
D
Douwe Maan 已提交
621 622 623
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
624
      project.build_allow_git_fetch
D
Douwe Maan 已提交
625 626 627
    end

    def update_coverage
628
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
629
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
630 631
    end

632
    # rubocop: disable CodeReuse/ServiceClass
633
    def parse_trace_sections!
634
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
635
    end
636
    # rubocop: enable CodeReuse/ServiceClass
637

638 639
    def trace
      Gitlab::Ci::Trace.new(self)
640 641
    end

642
    def has_trace?
643
      trace.exist?
T
Tomasz Maczukin 已提交
644 645
    end

646 647 648 649 650 651 652 653
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    def artifacts_file
      job_artifacts_archive&.file
    end

    def artifacts_size
      job_artifacts_archive&.size
    end

    def artifacts_metadata
      job_artifacts_metadata&.file
    end

    def artifacts?
      !artifacts_expired? && artifacts_file&.exists?
    end

    def artifacts_metadata?
      artifacts? && artifacts_metadata&.exists?
    end

674 675
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
676 677
    end

S
Shinya Maeda 已提交
678 679 680 681
    def has_old_trace?
      old_trace.present?
    end

682 683
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
684 685
    end

686 687
    def old_trace
      read_attribute(:trace)
688 689
    end

690
    def erase_old_trace!
691
      return unless has_old_trace?
S
Shinya Maeda 已提交
692

693
      update_column(:trace, nil)
D
Douwe Maan 已提交
694 695
    end

696 697 698 699 700 701 702 703
    def artifacts_expose_as
      options.dig(:artifacts, :expose_as)
    end

    def artifacts_paths
      options.dig(:artifacts, :paths)
    end

704 705 706 707
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
708
    def valid_token?(token)
H
Heinrich Lee Yu 已提交
709
      self.token && ActiveSupport::SecurityUtils.secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
710 711
    end

712 713 714 715
    def has_tags?
      tag_list.any?
    end

716
    def any_runners_online?
717
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
718 719
    end

K
Kamil Trzcinski 已提交
720
    def stuck?
721 722 723
      pending? && !any_runners_online?
    end

724
    def execute_hooks
725
      return unless project
726

727 728
      project.execute_hooks(build_data.dup, :job_hooks) if project.has_active_hooks?(:job_hooks)
      project.execute_services(build_data.dup, :job_hooks) if project.has_active_services?(:job_hooks)
729 730
    end

731 732 733 734
    def browsable_artifacts?
      artifacts_metadata?
    end

735
    def artifacts_metadata_entry(path, **options)
736
      artifacts_metadata.open do |metadata_stream|
737
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
738
          metadata_stream,
739 740
          path,
          **options)
741

742 743
        metadata.to_entry
      end
744 745
    end

746 747 748
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
S
Shinya Maeda 已提交
749 750
    end

751 752 753
    def erase(opts = {})
      return false unless erasable?

754
      job_artifacts.destroy_all # rubocop: disable DestroyAll
755 756 757 758 759
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
760
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
761 762 763 764 765 766
    end

    def erased?
      !self.erased_at.nil?
    end

767
    def artifacts_expired?
768
      artifacts_expire_at && artifacts_expire_at < Time.now
769 770
    end

771 772 773 774 775
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
776 777
      self.artifacts_expire_at =
        if value
778
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
779
        end
780 781
    end

782 783
    def has_expiring_archive_artifacts?
      has_expiring_artifacts? && job_artifacts_archive.present?
784 785
    end

786
    def keep_artifacts!
787
      self.update(artifacts_expire_at: nil)
788
      self.job_artifacts.update_all(expire_at: nil)
789 790
    end

791
    def artifacts_file_for_type(type)
792
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
793 794
    end

795
    def coverage_regex
796
      super || project.try(:build_coverage_regex)
797 798
    end

799
    def steps
T
Tomasz Maczukin 已提交
800 801
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
802 803 804
    end

    def image
805
      Gitlab::Ci::Build::Image.from_image(self)
806 807 808
    end

    def services
809
      Gitlab::Ci::Build::Image.from_services(self)
810 811 812
    end

    def cache
M
Matija Čupić 已提交
813 814 815 816
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
817
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
818
      end
M
Matija Čupić 已提交
819 820

      [cache]
821 822
    end

823
    def credentials
824
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
825 826
    end

827 828 829 830
    def all_dependencies
      (dependencies + cross_dependencies).uniq
    end

T
Tomasz Maczukin 已提交
831
    def dependencies
832 833
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
834 835
      depended_jobs = depends_on_builds

K
Kamil Trzciński 已提交
836
      # find all jobs that are needed
837
      if Feature.enabled?(:ci_dag_support, project, default_enabled: true) && scheduling_type_dag?
838
        depended_jobs = depended_jobs.where(name: needs.artifacts.select(:name))
K
Kamil Trzciński 已提交
839
      end
T
Tomasz Maczukin 已提交
840

K
Kamil Trzciński 已提交
841 842 843
      # find all jobs that are dependent on
      if options[:dependencies].present?
        depended_jobs = depended_jobs.where(name: options[:dependencies])
T
Tomasz Maczukin 已提交
844
      end
K
Kamil Trzciński 已提交
845

846 847
      # if both needs and dependencies are used,
      # the end result will be an intersection between them
K
Kamil Trzciński 已提交
848
      depended_jobs
T
Tomasz Maczukin 已提交
849 850
    end

851 852 853 854
    def cross_dependencies
      []
    end

855 856 857 858
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
859
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
860
      return true if Feature.enabled?('ci_disable_validates_dependencies')
861

K
Kamil Trzciński 已提交
862
      dependencies.all?(&:valid_dependency?)
863 864
    end

K
Kamil Trzciński 已提交
865
    def valid_dependency?
S
Shinya Maeda 已提交
866 867 868 869 870 871
      return false if artifacts_expired?
      return false if erased?

      true
    end

872 873 874 875
    def invalid_dependencies
      dependencies.reject(&:valid_dependency?)
    end

876 877 878 879 880 881 882 883
    def runner_required_feature_names
      strong_memoize(:runner_required_feature_names) do
        RUNNER_FEATURES.select do |feature, method|
          method.call(self)
        end.keys
      end
    end

884
    def supported_runner?(features)
885
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
886
        features&.dig(feature_name)
887 888 889
      end
    end

890
    def publishes_artifacts_reports?
891
      options&.dig(:artifacts, :reports)&.any?
892 893
    end

894 895 896 897
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
898
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
899
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
900 901 902
      trace
    end

903
    def serializable_hash(options = {})
J
James Lopez 已提交
904
      super(options).merge(when: read_attribute(:when))
905 906
    end

F
Francisco Javier López 已提交
907 908 909 910
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
911 912
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
913
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
914
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
915 916 917 918
        end
      end
    end

919 920 921 922 923 924 925 926
    def collect_coverage_reports!(coverage_report)
      each_report(Ci::JobArtifact::COVERAGE_REPORT_FILE_TYPES) do |file_type, blob|
        Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, coverage_report)
      end

      coverage_report
    end

927 928 929 930
    def report_artifacts
      job_artifacts.with_reports
    end

931 932
    # Virtual deployment status depending on the environment status.
    def deployment_status
933
      return unless starts_environment?
934 935 936

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
937
      elsif failed?
938 939 940 941 942 943
        return :failed
      end

      :creating
    end

944 945 946 947 948 949 950
    # Consider this object to have a structural integrity problems
    def doom!
      update_columns(
        status: :failed,
        failure_reason: :data_integrity_failure)
    end

951 952
    private

953 954 955 956
    def build_data
      @build_data ||= Gitlab::DataBuilder::Build.build(self)
    end

957
    def successful_deployment_status
S
Shinya Maeda 已提交
958 959 960 961
      if deployment&.last?
        :last
      else
        :out_of_date
962 963 964
      end
    end

965 966 967
    def each_report(report_types)
      job_artifacts_for_types(report_types).each do |report_artifact|
        report_artifact.each_blob do |blob|
968
          yield report_artifact.file_type, blob, report_artifact
S
Shinya Maeda 已提交
969 970 971 972
        end
      end
    end

973 974 975 976 977
    def job_artifacts_for_types(report_types)
      # Use select to leverage cached associations and avoid N+1 queries
      job_artifacts.select { |artifact| artifact.file_type.in?(report_types) }
    end

978
    def erase_trace!
979
      trace.erase!
980 981 982
    end

    def update_erased!(user = nil)
983
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
984 985
    end

986
    def unscoped_project
K
Kamil Trzciński 已提交
987
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
988 989
    end

990
    def environment_url
991
      options&.dig(:environment, :url) || persisted_environment&.external_url
992 993
    end

994 995 996 997 998 999 1000 1001
    def environment_status
      strong_memoize(:environment_status) do
        if has_environment? && merge_request
          EnvironmentStatus.new(project, persisted_environment, merge_request, pipeline.sha)
        end
      end
    end

1002 1003 1004 1005 1006
    # The format of the retry option changed in GitLab 11.5: Before it was
    # integer only, after it is a hash. New builds are created with the new
    # format, but builds created before GitLab 11.5 and saved in database still
    # have the old integer only format. This method returns the retry option
    # normalized as a hash in 11.5+ format.
1007 1008
    def options_retry
      strong_memoize(:options_retry) do
1009 1010 1011 1012
        value = options&.dig(:retry)
        value = value.is_a?(Integer) ? { max: value } : value.to_h
        value.with_indifferent_access
      end
M
Markus Doits 已提交
1013
    end
1014 1015 1016 1017

    def has_expiring_artifacts?
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
    end
D
Douwe Maan 已提交
1018 1019
  end
end
1020 1021

Ci::Build.prepend_if_ee('EE::Ci::Build')