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

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

18 19
    BuildArchivedError = Class.new(StandardError)

20 21 22 23 24 25 26 27
    self.ignored_columns += %i[
      artifacts_file
      artifacts_file_store
      artifacts_metadata
      artifacts_metadata_store
      artifacts_size
      commands
    ]
28

29
    belongs_to :project, inverse_of: :builds
30 31
    belongs_to :runner
    belongs_to :trigger_request
32
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
33

34
    RUNNER_FEATURES = {
35 36
      upload_multiple_artifacts: -> (build) { build.publishes_artifacts_reports? },
      refspecs: -> (build) { build.merge_request_ref? }
37 38
    }.freeze

S
Shinya Maeda 已提交
39
    has_one :deployment, as: :deployable, class_name: 'Deployment'
40
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
41
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
K
Kamil Trzciński 已提交
42
    has_many :needs, class_name: 'Ci::BuildNeed', foreign_key: :build_id, inverse_of: :build
43

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

    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
50

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

    accepts_nested_attributes_for :runner_session
M
Matija Čupić 已提交
54
    accepts_nested_attributes_for :job_variables
K
Kamil Trzciński 已提交
55
    accepts_nested_attributes_for :needs
F
Francisco Javier López 已提交
56 57 58

    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
59
    delegate :gitlab_deploy_token, to: :project
60
    delegate :trigger_short_token, to: :trigger_request, allow_nil: true
T
Tomasz Maczukin 已提交
61

62
    ##
63 64 65 66
    # Since Gitlab 11.5, deployments records started being created right after
    # `ci_builds` creation. We can look up a relevant `environment` through
    # `deployment` relation today. This is much more efficient than expanding
    # environment name with variables.
67
    # (See more https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/22380)
68
    #
69 70 71 72 73
    # However, we have to still expand environment name if it's a stop action,
    # because `deployment` persists information for start action only.
    #
    # We will follow up this by persisting expanded name in build metadata or
    # persisting stop action in database.
74
    def persisted_environment
75 76 77
      return unless has_environment?

      strong_memoize(:persisted_environment) do
78 79
        deployment&.environment ||
          Environment.find_by(name: expanded_environment_name, project: project)
80
      end
81 82
    end

83 84
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
85

D
Douwe Maan 已提交
86 87
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
88
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
89
    validates :ref, presence: true
D
Douwe Maan 已提交
90

91 92 93 94 95
    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 已提交
96
    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
97
    scope :ignore_failures, ->() { where(allow_failure: false) }
98
    scope :with_artifacts_archive, ->() do
99
      where('EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
100
    end
101

102 103 104 105
    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

106
    scope :with_archived_trace, ->() do
107
      with_existing_job_artifacts(Ci::JobArtifact.trace)
108 109
    end

110 111 112 113
    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ć 已提交
114 115
    scope :with_reports, ->(reports_scope) do
      with_existing_job_artifacts(reports_scope)
116
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
117 118
    end

119 120
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

121 122
    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) }
123
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
124 125
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
126
    scope :ref_protected, -> { where(protected: true) }
127
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
128 129
    scope :with_stale_live_trace, -> { with_live_trace.finished_before(12.hours.ago) }
    scope :finished_before, -> (date) { finished.where('finished_at < ?', date) }
130

131 132
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
133
        .where(taggable_type: CommitStatus.name)
134 135 136 137 138 139 140 141 142
        .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
143
        .where(taggable_type: CommitStatus.name)
144 145 146 147 148 149
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

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

150 151
    scope :queued_before, ->(time) { where(arel_table[:queued_at].lt(time)) }

D
Douwe Maan 已提交
152 153
    acts_as_taggable

K
Kamil Trzciński 已提交
154
    add_authentication_token_field :token, encrypted: :optional
155 156

    before_save :ensure_token
157
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
158

159
    after_create unless: :importing? do |build|
160
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
161 162
    end

D
Douwe Maan 已提交
163
    class << self
164 165 166 167 168 169
      # 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 已提交
170 171 172 173
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

174
      def retry(build, current_user)
175
        # rubocop: disable CodeReuse/ServiceClass
176 177 178
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
179
        # rubocop: enable CodeReuse/ServiceClass
D
Douwe Maan 已提交
180 181 182
      end
    end

183
    state_machine :status do
T
Tiger 已提交
184 185 186 187
      event :enqueue do
        transition [:created, :skipped, :manual, :scheduled] => :preparing, if: :any_unmet_prerequisites?
      end

188 189
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
190 191
      end

192 193 194 195 196 197 198 199
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

S
Shinya Maeda 已提交
200
      event :enqueue_scheduled do
T
Tiger 已提交
201 202 203 204
        transition scheduled: :preparing, if: ->(build) do
          build.scheduled_at&.past? && build.any_unmet_prerequisites?
        end

205
        transition scheduled: :pending, if: ->(build) do
T
Tiger 已提交
206
          build.scheduled_at&.past? && !build.any_unmet_prerequisites?
S
Shinya Maeda 已提交
207
        end
208 209 210
      end

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
211 212 213 214
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
215
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
216 217 218 219 220 221
      end

      after_transition created: :scheduled do |build|
        build.run_after_commit do
          Ci::BuildScheduleWorker.perform_at(build.scheduled_at, build.id)
        end
222 223
      end

T
Tiger 已提交
224 225 226 227 228 229
      after_transition any => [:preparing] do |build|
        build.run_after_commit do
          Ci::BuildPrepareWorker.perform_async(id)
        end
      end

230 231
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
232
          BuildQueueWorker.perform_async(id)
233 234 235
        end
      end

236
      after_transition pending: :running do |build|
237
        build.pipeline.persistent_ref.create
S
Shinya Maeda 已提交
238 239
        build.deployment&.run

240 241 242
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
243 244
      end

245
      after_transition any => [:success, :failed, :canceled] do |build|
246
        build.run_after_commit do
247
          BuildFinishedWorker.perform_async(id)
248
        end
D
Douwe Maan 已提交
249
      end
250

251
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
252 253
        build.deployment&.succeed

254
        build.run_after_commit do
255
          BuildSuccessWorker.perform_async(id)
256
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
257 258
        end
      end
259

260
      before_transition any => [:failed] do |build|
261
        next unless build.project
262
        next unless build.deployment
S
Shinya Maeda 已提交
263

264 265 266 267 268 269 270
        begin
          build.deployment.drop!
        rescue => e
          Gitlab::Sentry.track_exception(e, extra: { build_id: build.id })
        end

        true
271 272 273 274
      end

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

276
        if build.retry_failure?
277 278 279
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
M
Mayra Cabrera 已提交
280
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}" # rubocop:disable Gitlab/RailsLogger
281
          end
282 283
        end
      end
284

285
      after_transition pending: :running do |build|
286
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
287
      end
F
Francisco Javier López 已提交
288 289 290 291

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
292 293 294 295

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

298
    def detailed_status(current_user)
299 300 301
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
302 303
    end

304
    def other_manual_actions
305
      pipeline.manual_actions.where.not(name: name)
306 307
    end

308 309
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
310 311
    end

312 313 314 315 316
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

317 318 319 320
    def runnable?
      true
    end

321 322 323 324 325 326 327
    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

328
    def playable?
329
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
330 331
    end

S
Shinya Maeda 已提交
332
    def schedulable?
333
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
334 335
    end

S
Shinya Maeda 已提交
336
    def options_scheduled_at
S
Shinya Maeda 已提交
337
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
338 339
    end

340
    def action?
341
      %w[manual delayed].include?(self.when)
342 343
    end

344
    # rubocop: disable CodeReuse/ServiceClass
M
Matija Čupić 已提交
345
    def play(current_user, job_variables_attributes = nil)
346 347
      Ci::PlayBuildService
        .new(project, current_user)
M
Matija Čupić 已提交
348
        .execute(self, job_variables_attributes)
349
    end
350
    # rubocop: enable CodeReuse/ServiceClass
351

K
Kamil Trzcinski 已提交
352
    def cancelable?
J
Jacopo 已提交
353
      active? || created?
K
Kamil Trzcinski 已提交
354 355
    end

K
Kamil Trzcinski 已提交
356
    def retryable?
K
Kamil Trzciński 已提交
357
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
358
    end
359 360 361 362 363 364

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

    def retries_max
M
Markus Doits 已提交
365
      normalized_retry.fetch(:max, 0)
366
    end
K
Kamil Trzcinski 已提交
367

368
    def retry_when
M
Markus Doits 已提交
369
      normalized_retry.fetch(:when, ['always'])
370 371
    end

372 373 374
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

375
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
376
    end
K
Kamil Trzcinski 已提交
377

378 379
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
380 381
    end

T
Tiger 已提交
382 383 384 385 386 387 388 389
    def any_unmet_prerequisites?
      prerequisites.present?
    end

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

390
    def expanded_environment_name
391 392 393
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
394
        ExpandVariables.expand(environment, -> { simple_variables })
395
      end
396 397
    end

398
    def has_environment?
399
      environment.present?
400 401
    end

402
    def starts_environment?
403
      has_environment? && self.environment_action == 'start'
404 405 406
    end

    def stops_environment?
407
      has_environment? && self.environment_action == 'stop'
408 409 410
    end

    def environment_action
411
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
412 413
    end

S
Shinya Maeda 已提交
414 415 416 417
    def has_deployment?
      !!self.deployment
    end

418
    def outdated_deployment?
S
Shinya Maeda 已提交
419
      success? && !deployment.try(:last?)
420
    end
421

422 423
    def depends_on_builds
      # Get builds of the same type
424
      latest_builds = self.pipeline.builds.latest
425 426 427 428 429

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

430
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
431 432 433
      user == current_user
    end

S
Shinya Maeda 已提交
434 435 436 437
    def on_stop
      options&.dig(:environment, :on_stop)
    end

438 439 440 441
    ##
    # All variables, including persisted environment variables.
    #
    def variables
442 443 444 445
      strong_memoize(:variables) do
        Gitlab::Ci::Variables::Collection.new
          .concat(persisted_variables)
          .concat(scoped_variables)
M
Matija Čupić 已提交
446
          .concat(job_variables)
447 448 449
          .concat(persisted_environment_variables)
          .to_runner_variables
      end
450 451
    end

452
    CI_REGISTRY_USER = 'gitlab-ci-token'
453 454 455 456 457 458 459 460 461

    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))
462
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false, masked: true)
463
          .append(key: 'CI_BUILD_ID', value: id.to_s)
464
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false, masked: true)
465
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
466
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false, masked: true)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
          .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

    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)
490
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false, masked: true)
491
      end
492 493
    end

494 495 496 497
    def features
      { trace_sections: true }
    end

498
    def merge_request
Z
Z.J. van de Weg 已提交
499
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
500

501 502
      @merge_request ||=
        begin
503
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
504 505
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
506
            .reorder(iid: :desc)
507 508

          merge_requests.find do |merge_request|
509
            merge_request.commit_shas.include?(pipeline.sha)
510 511
          end
        end
512 513
    end

D
Douwe Maan 已提交
514
    def repo_url
K
Kamil Trzciński 已提交
515 516 517
      return unless token

      auth = "gitlab-ci-token:#{token}@"
518
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
519 520
        prefix + auth
      end
D
Douwe Maan 已提交
521 522 523
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
524
      project.build_allow_git_fetch
D
Douwe Maan 已提交
525 526 527
    end

    def update_coverage
528
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
529
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
530 531
    end

532
    # rubocop: disable CodeReuse/ServiceClass
533
    def parse_trace_sections!
534
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
535
    end
536
    # rubocop: enable CodeReuse/ServiceClass
537

538 539
    def trace
      Gitlab::Ci::Trace.new(self)
540 541
    end

542
    def has_trace?
543
      trace.exist?
T
Tomasz Maczukin 已提交
544 545
    end

546 547 548 549 550 551 552 553
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    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

574 575
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
576 577
    end

S
Shinya Maeda 已提交
578 579 580 581
    def has_old_trace?
      old_trace.present?
    end

582 583
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
584 585
    end

586 587
    def old_trace
      read_attribute(:trace)
588 589
    end

590
    def erase_old_trace!
591
      return unless has_old_trace?
S
Shinya Maeda 已提交
592

593
      update_column(:trace, nil)
D
Douwe Maan 已提交
594 595
    end

596 597 598 599
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
600
    def valid_token?(token)
H
Heinrich Lee Yu 已提交
601
      self.token && ActiveSupport::SecurityUtils.secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
602 603
    end

604 605 606 607
    def has_tags?
      tag_list.any?
    end

608
    def any_runners_online?
609
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
610 611
    end

K
Kamil Trzcinski 已提交
612
    def stuck?
613 614 615
      pending? && !any_runners_online?
    end

616
    def execute_hooks
617
      return unless project
618

619
      build_data = Gitlab::DataBuilder::Build.build(self)
620 621
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
622 623
    end

624 625 626 627
    def browsable_artifacts?
      artifacts_metadata?
    end

628
    def artifacts_metadata_entry(path, **options)
629
      artifacts_metadata.open do |metadata_stream|
630
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
631
          metadata_stream,
632 633
          path,
          **options)
634

635 636
        metadata.to_entry
      end
637 638
    end

639 640 641
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
S
Shinya Maeda 已提交
642 643
    end

644 645 646
    def erase(opts = {})
      return false unless erasable?

647
      job_artifacts.destroy_all # rubocop: disable DestroyAll
648 649 650 651 652
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
653
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
654 655 656 657 658 659
    end

    def erased?
      !self.erased_at.nil?
    end

660
    def artifacts_expired?
661
      artifacts_expire_at && artifacts_expire_at < Time.now
662 663
    end

664 665 666 667 668
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
669 670
      self.artifacts_expire_at =
        if value
671
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
672
        end
673 674
    end

675
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
676
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
677 678
    end

679
    def keep_artifacts!
680
      self.update(artifacts_expire_at: nil)
681
      self.job_artifacts.update_all(expire_at: nil)
682 683
    end

684
    def artifacts_file_for_type(type)
685
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
686 687
    end

688
    def coverage_regex
689
      super || project.try(:build_coverage_regex)
690 691
    end

692
    def steps
T
Tomasz Maczukin 已提交
693 694
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
695 696 697
    end

    def image
698
      Gitlab::Ci::Build::Image.from_image(self)
699 700 701
    end

    def services
702
      Gitlab::Ci::Build::Image.from_services(self)
703 704 705
    end

    def cache
M
Matija Čupić 已提交
706 707 708 709
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
710
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
711
      end
M
Matija Čupić 已提交
712 713

      [cache]
714 715
    end

716
    def credentials
717
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
718 719
    end

T
Tomasz Maczukin 已提交
720
    def dependencies
721 722
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
723 724
      depended_jobs = depends_on_builds

K
Kamil Trzciński 已提交
725
      # find all jobs that are needed
K
Kamil Trzciński 已提交
726
      if Feature.enabled?(:ci_dag_support, project, default_enabled: true) && needs.exists?
K
Kamil Trzciński 已提交
727
        depended_jobs = depended_jobs.where(name: needs.select(:name))
K
Kamil Trzciński 已提交
728
      end
T
Tomasz Maczukin 已提交
729

K
Kamil Trzciński 已提交
730 731 732
      # find all jobs that are dependent on
      if options[:dependencies].present?
        depended_jobs = depended_jobs.where(name: options[:dependencies])
T
Tomasz Maczukin 已提交
733
      end
K
Kamil Trzciński 已提交
734 735

      depended_jobs
T
Tomasz Maczukin 已提交
736 737
    end

738 739 740 741
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
742
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
743
      return true if Feature.enabled?('ci_disable_validates_dependencies')
744

K
Kamil Trzciński 已提交
745
      dependencies.all?(&:valid_dependency?)
746 747
    end

K
Kamil Trzciński 已提交
748
    def valid_dependency?
S
Shinya Maeda 已提交
749 750 751 752 753 754
      return false if artifacts_expired?
      return false if erased?

      true
    end

755 756 757 758 759 760 761 762
    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

763
    def supported_runner?(features)
764
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
765
        features&.dig(feature_name)
766 767 768
      end
    end

769
    def publishes_artifacts_reports?
770
      options&.dig(:artifacts, :reports)&.any?
771 772
    end

773 774 775 776
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
777
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
778
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
779 780 781
      trace
    end

782
    def serializable_hash(options = {})
J
James Lopez 已提交
783
      super(options).merge(when: read_attribute(:when))
784 785
    end

F
Francisco Javier López 已提交
786 787 788 789
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
790 791
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
792
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
793
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
794 795 796 797
        end
      end
    end

798 799 800 801
    def report_artifacts
      job_artifacts.with_reports
    end

802 803
    # Virtual deployment status depending on the environment status.
    def deployment_status
804
      return unless starts_environment?
805 806 807

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
808
      elsif failed?
809 810 811 812 813 814
        return :failed
      end

      :creating
    end

815 816
    private

817
    def successful_deployment_status
S
Shinya Maeda 已提交
818 819 820 821
      if deployment&.last?
        :last
      else
        :out_of_date
822 823 824
      end
    end

825 826 827 828
    def each_report(report_types)
      job_artifacts_for_types(report_types).each do |report_artifact|
        report_artifact.each_blob do |blob|
          yield report_artifact.file_type, blob
S
Shinya Maeda 已提交
829 830 831 832
        end
      end
    end

833 834 835 836 837
    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

838
    def erase_trace!
839
      trace.erase!
840 841 842
    end

    def update_erased!(user = nil)
843
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
844 845
    end

846
    def unscoped_project
K
Kamil Trzciński 已提交
847
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
848 849
    end

850
    def environment_url
851
      options&.dig(:environment, :url) || persisted_environment&.external_url
852 853
    end

854 855 856 857 858
    # 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.
M
Markus Doits 已提交
859
    def normalized_retry
860 861 862 863 864
      strong_memoize(:normalized_retry) do
        value = options&.dig(:retry)
        value = value.is_a?(Integer) ? { max: value } : value.to_h
        value.with_indifferent_access
      end
M
Markus Doits 已提交
865 866
    end

867 868
    def build_attributes_from_config
      return {} unless pipeline.config_processor
869

870 871
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
872 873
  end
end
874 875

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