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 67
    # 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.
    # (See more https://gitlab.com/gitlab-org/gitlab-ce/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

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

97 98 99 100
    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

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

105 106 107 108
    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ć 已提交
109 110
    scope :with_reports, ->(reports_scope) do
      with_existing_job_artifacts(reports_scope)
111
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
112 113
    end

114 115
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

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

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

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

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

D
Douwe Maan 已提交
149 150
    acts_as_taggable

K
Kamil Trzciński 已提交
151
    add_authentication_token_field :token, encrypted: :optional
152 153

    before_save :ensure_token
154
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
155

156
    after_create unless: :importing? do |build|
157
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
158 159
    end

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

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

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

185 186
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
187 188
      end

189 190 191 192 193 194 195 196
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

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

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

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
208 209 210 211
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
212
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
213 214 215 216 217 218
      end

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

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

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

233
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
234 235
        build.deployment&.run

236 237 238
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
239 240
      end

241
      after_transition any => [:success, :failed, :canceled] do |build|
242
        build.run_after_commit do
243
          BuildFinishedWorker.perform_async(id)
244
        end
D
Douwe Maan 已提交
245
      end
246

247
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
248 249
        build.deployment&.succeed

250
        build.run_after_commit do
251
          BuildSuccessWorker.perform_async(id)
252
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
253 254
        end
      end
255

256
      before_transition any => [:failed] do |build|
257
        next unless build.project
258
        next unless build.deployment
S
Shinya Maeda 已提交
259

260 261 262 263 264 265 266
        begin
          build.deployment.drop!
        rescue => e
          Gitlab::Sentry.track_exception(e, extra: { build_id: build.id })
        end

        true
267 268 269 270
      end

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

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

281
      after_transition pending: :running do |build|
282
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
283
      end
F
Francisco Javier López 已提交
284 285 286 287

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
288 289 290 291

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

294
    def detailed_status(current_user)
295 296 297
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
298 299
    end

300
    def other_manual_actions
301
      pipeline.manual_actions.where.not(name: name)
302 303
    end

304 305
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
306 307
    end

308 309 310 311 312
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

313 314 315 316
    def runnable?
      true
    end

317 318 319 320 321 322 323
    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

324
    def playable?
325
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
326 327
    end

S
Shinya Maeda 已提交
328
    def schedulable?
329
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
330 331
    end

S
Shinya Maeda 已提交
332
    def options_scheduled_at
S
Shinya Maeda 已提交
333
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
334 335
    end

336
    def action?
337
      %w[manual delayed].include?(self.when)
338 339
    end

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

K
Kamil Trzcinski 已提交
348
    def cancelable?
J
Jacopo 已提交
349
      active? || created?
K
Kamil Trzcinski 已提交
350 351
    end

K
Kamil Trzcinski 已提交
352
    def retryable?
K
Kamil Trzciński 已提交
353
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
354
    end
355 356 357 358 359 360

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

    def retries_max
M
Markus Doits 已提交
361
      normalized_retry.fetch(:max, 0)
362
    end
K
Kamil Trzcinski 已提交
363

364
    def retry_when
M
Markus Doits 已提交
365
      normalized_retry.fetch(:when, ['always'])
366 367
    end

368 369 370
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

371
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
372
    end
K
Kamil Trzcinski 已提交
373

374 375
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
376 377
    end

T
Tiger 已提交
378 379 380 381 382 383 384 385
    def any_unmet_prerequisites?
      prerequisites.present?
    end

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

386
    def expanded_environment_name
387 388 389
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
390
        ExpandVariables.expand(environment, -> { simple_variables })
391
      end
392 393
    end

394
    def has_environment?
395
      environment.present?
396 397
    end

398
    def starts_environment?
399
      has_environment? && self.environment_action == 'start'
400 401 402
    end

    def stops_environment?
403
      has_environment? && self.environment_action == 'stop'
404 405 406
    end

    def environment_action
407
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
408 409
    end

S
Shinya Maeda 已提交
410 411 412 413
    def has_deployment?
      !!self.deployment
    end

414
    def outdated_deployment?
S
Shinya Maeda 已提交
415
      success? && !deployment.try(:last?)
416
    end
417

418 419
    def depends_on_builds
      # Get builds of the same type
420
      latest_builds = self.pipeline.builds.latest
421 422 423 424 425

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

426
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
427 428 429
      user == current_user
    end

S
Shinya Maeda 已提交
430 431 432 433
    def on_stop
      options&.dig(:environment, :on_stop)
    end

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

448 449 450 451 452 453 454 455 456 457
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

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

490 491 492 493
    def features
      { trace_sections: true }
    end

494
    def merge_request
Z
Z.J. van de Weg 已提交
495
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
496

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

          merge_requests.find do |merge_request|
505
            merge_request.commit_shas.include?(pipeline.sha)
506 507
          end
        end
508 509
    end

D
Douwe Maan 已提交
510
    def repo_url
K
Kamil Trzciński 已提交
511 512 513
      return unless token

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
520
      project.build_allow_git_fetch
D
Douwe Maan 已提交
521 522 523
    end

    def update_coverage
524
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
525
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
526 527
    end

528
    # rubocop: disable CodeReuse/ServiceClass
529
    def parse_trace_sections!
530
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
531
    end
532
    # rubocop: enable CodeReuse/ServiceClass
533

534 535
    def trace
      Gitlab::Ci::Trace.new(self)
536 537
    end

538
    def has_trace?
539
      trace.exist?
T
Tomasz Maczukin 已提交
540 541
    end

542 543 544 545 546 547 548 549
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    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

570 571
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
572 573
    end

S
Shinya Maeda 已提交
574 575 576 577
    def has_old_trace?
      old_trace.present?
    end

578 579
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
580 581
    end

582 583
    def old_trace
      read_attribute(:trace)
584 585
    end

586
    def erase_old_trace!
587
      return unless has_old_trace?
S
Shinya Maeda 已提交
588

589
      update_column(:trace, nil)
D
Douwe Maan 已提交
590 591
    end

592 593 594 595
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
596
    def valid_token?(token)
H
Heinrich Lee Yu 已提交
597
      self.token && ActiveSupport::SecurityUtils.secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
598 599
    end

600 601 602 603
    def has_tags?
      tag_list.any?
    end

604
    def any_runners_online?
605
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
606 607
    end

K
Kamil Trzcinski 已提交
608
    def stuck?
609 610 611
      pending? && !any_runners_online?
    end

612
    def execute_hooks
613
      return unless project
614

615
      build_data = Gitlab::DataBuilder::Build.build(self)
616 617
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
618 619
    end

620 621 622 623
    def browsable_artifacts?
      artifacts_metadata?
    end

624
    def artifacts_metadata_entry(path, **options)
625
      artifacts_metadata.open do |metadata_stream|
626
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
627
          metadata_stream,
628 629
          path,
          **options)
630

631 632
        metadata.to_entry
      end
633 634
    end

635 636 637
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
S
Shinya Maeda 已提交
638 639
    end

640 641 642
    def erase(opts = {})
      return false unless erasable?

643
      job_artifacts.destroy_all # rubocop: disable DestroyAll
644 645 646 647 648
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
649
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
650 651 652 653 654 655
    end

    def erased?
      !self.erased_at.nil?
    end

656
    def artifacts_expired?
657
      artifacts_expire_at && artifacts_expire_at < Time.now
658 659
    end

660 661 662 663 664
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
665 666
      self.artifacts_expire_at =
        if value
667
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
668
        end
669 670
    end

671
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
672
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
673 674
    end

675
    def keep_artifacts!
676
      self.update(artifacts_expire_at: nil)
677
      self.job_artifacts.update_all(expire_at: nil)
678 679
    end

680
    def artifacts_file_for_type(type)
681
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
682 683
    end

684
    def coverage_regex
685
      super || project.try(:build_coverage_regex)
686 687
    end

688
    def steps
T
Tomasz Maczukin 已提交
689 690
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
691 692 693
    end

    def image
694
      Gitlab::Ci::Build::Image.from_image(self)
695 696 697
    end

    def services
698
      Gitlab::Ci::Build::Image.from_services(self)
699 700 701
    end

    def cache
M
Matija Čupić 已提交
702 703 704 705
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
706
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
707
      end
M
Matija Čupić 已提交
708 709

      [cache]
710 711
    end

712
    def credentials
713
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
714 715
    end

T
Tomasz Maczukin 已提交
716
    def dependencies
717 718
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
719 720
      depended_jobs = depends_on_builds

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

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

      depended_jobs
T
Tomasz Maczukin 已提交
732 733
    end

734 735 736 737
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
738
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
739
      return true if Feature.enabled?('ci_disable_validates_dependencies')
740

K
Kamil Trzciński 已提交
741
      dependencies.all?(&:valid_dependency?)
742 743
    end

K
Kamil Trzciński 已提交
744
    def valid_dependency?
S
Shinya Maeda 已提交
745 746 747 748 749 750
      return false if artifacts_expired?
      return false if erased?

      true
    end

751 752 753 754 755 756 757 758
    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

759
    def supported_runner?(features)
760
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
761
        features&.dig(feature_name)
762 763 764
      end
    end

765
    def publishes_artifacts_reports?
766
      options&.dig(:artifacts, :reports)&.any?
767 768
    end

769 770 771 772
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
773
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
774
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
775 776 777
      trace
    end

778
    def serializable_hash(options = {})
J
James Lopez 已提交
779
      super(options).merge(when: read_attribute(:when))
780 781
    end

F
Francisco Javier López 已提交
782 783 784 785
    def has_terminal?
      running? && runner_session_url.present?
    end

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

794 795 796 797
    def report_artifacts
      job_artifacts.with_reports
    end

798 799
    # Virtual deployment status depending on the environment status.
    def deployment_status
800
      return unless starts_environment?
801 802 803

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
804
      elsif failed?
805 806 807 808 809 810
        return :failed
      end

      :creating
    end

811 812
    private

813
    def successful_deployment_status
S
Shinya Maeda 已提交
814 815 816 817
      if deployment&.last?
        :last
      else
        :out_of_date
818 819 820
      end
    end

821 822 823 824
    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 已提交
825 826 827 828
        end
      end
    end

829 830 831 832 833
    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

834
    def erase_trace!
835
      trace.erase!
836 837 838
    end

    def update_erased!(user = nil)
839
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
840 841
    end

842
    def unscoped_project
K
Kamil Trzciński 已提交
843
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
844 845
    end

846
    def environment_url
847
      options&.dig(:environment, :url) || persisted_environment&.external_url
848 849
    end

850 851 852 853 854
    # 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 已提交
855
    def normalized_retry
856 857 858 859 860
      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 已提交
861 862
    end

863 864
    def build_attributes_from_config
      return {} unless pipeline.config_processor
865

866 867
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
868 869
  end
end