build.rb 24.0 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 IgnorableColumn
15
    include Gitlab::Utils::StrongMemoize
S
Shinya Maeda 已提交
16
    include Deployable
17
    include HasRef
18

19 20 21
    BuildArchivedError = Class.new(StandardError)

    ignore_column :commands
22 23 24 25 26
    ignore_column :artifacts_file
    ignore_column :artifacts_metadata
    ignore_column :artifacts_file_store
    ignore_column :artifacts_metadata_store
    ignore_column :artifacts_size
27

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

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

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

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

    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
49

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

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

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

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.
    # (See more https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/22380)
67
    #
68 69 70 71 72
    # 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.
73
    def persisted_environment
74 75 76
      return unless has_environment?

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

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

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

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

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

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

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

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

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

115 116
    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) }
117 118
    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) }
119
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
120 121
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
122
    scope :ref_protected, -> { where(protected: true) }
123
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
124

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

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

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

D
Douwe Maan 已提交
146 147
    acts_as_taggable

K
Kamil Trzciński 已提交
148
    add_authentication_token_field :token, encrypted: :optional
149 150

    before_save :ensure_token
151
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
152

153
    after_create unless: :importing? do |build|
154
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
155 156
    end

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

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

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

182 183
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
184 185
      end

186 187 188 189 190 191 192 193
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

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

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

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
205 206 207 208
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
209
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
210 211 212 213 214 215
      end

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

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

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

230
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
231 232
        build.deployment&.run

233 234 235
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
236 237
      end

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

244
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
245 246
        build.deployment&.succeed

247
        build.run_after_commit do
248
          BuildSuccessWorker.perform_async(id)
249
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
250 251
        end
      end
252

253
      before_transition any => [:failed] do |build|
254
        next unless build.project
255
        next unless build.deployment
S
Shinya Maeda 已提交
256

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

        true
264 265 266 267
      end

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

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

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

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
285 286 287 288

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

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

297
    def other_manual_actions
298
      pipeline.manual_actions.where.not(name: name)
299 300
    end

301 302
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
303 304
    end

305 306 307 308 309
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

310 311 312 313
    def runnable?
      true
    end

314 315 316 317 318 319 320
    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

321
    def playable?
322
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
323 324
    end

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

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

333
    def action?
334
      %w[manual delayed].include?(self.when)
335 336
    end

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

K
Kamil Trzcinski 已提交
345
    def cancelable?
J
Jacopo 已提交
346
      active? || created?
K
Kamil Trzcinski 已提交
347 348
    end

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

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

    def retries_max
M
Markus Doits 已提交
358
      normalized_retry.fetch(:max, 0)
359
    end
K
Kamil Trzcinski 已提交
360

361
    def retry_when
M
Markus Doits 已提交
362
      normalized_retry.fetch(:when, ['always'])
363 364
    end

365 366 367
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

368
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
369
    end
K
Kamil Trzcinski 已提交
370

371 372
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
373 374
    end

T
Tiger 已提交
375 376 377 378 379 380 381 382
    def any_unmet_prerequisites?
      prerequisites.present?
    end

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

383
    def expanded_environment_name
384 385 386
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
387 388
        ExpandVariables.expand(environment, simple_variables)
      end
389 390
    end

391
    def has_environment?
392
      environment.present?
393 394
    end

395
    def starts_environment?
396
      has_environment? && self.environment_action == 'start'
397 398 399
    end

    def stops_environment?
400
      has_environment? && self.environment_action == 'stop'
401 402 403
    end

    def environment_action
404
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
405 406
    end

S
Shinya Maeda 已提交
407 408 409 410
    def has_deployment?
      !!self.deployment
    end

411
    def outdated_deployment?
S
Shinya Maeda 已提交
412
      success? && !deployment.try(:last?)
413
    end
414

415 416
    def depends_on_builds
      # Get builds of the same type
417
      latest_builds = self.pipeline.builds.latest
418 419 420 421 422

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

423
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
424 425 426
      user == current_user
    end

S
Shinya Maeda 已提交
427 428 429 430
    def on_stop
      options&.dig(:environment, :on_stop)
    end

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

445 446 447 448 449 450 451 452 453 454
    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))
455
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false, masked: true)
456
          .append(key: 'CI_BUILD_ID', value: id.to_s)
457
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false, masked: true)
458
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
459
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false, masked: true)
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
          .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)
483
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false, masked: true)
484
      end
485 486
    end

487 488 489 490
    def features
      { trace_sections: true }
    end

491
    def merge_request
Z
Z.J. van de Weg 已提交
492
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
493

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

          merge_requests.find do |merge_request|
502
            merge_request.commit_shas.include?(pipeline.sha)
503 504
          end
        end
505 506
    end

D
Douwe Maan 已提交
507
    def repo_url
K
Kamil Trzciński 已提交
508 509 510
      return unless token

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
517
      project.build_allow_git_fetch
D
Douwe Maan 已提交
518 519 520
    end

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

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

531 532
    def trace
      Gitlab::Ci::Trace.new(self)
533 534
    end

535
    def has_trace?
536
      trace.exist?
T
Tomasz Maczukin 已提交
537 538
    end

539 540 541 542 543 544 545 546
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

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

567 568
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
569 570
    end

S
Shinya Maeda 已提交
571 572 573 574
    def has_old_trace?
      old_trace.present?
    end

575 576
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
577 578
    end

579 580
    def old_trace
      read_attribute(:trace)
581 582
    end

583
    def erase_old_trace!
584
      return unless has_old_trace?
S
Shinya Maeda 已提交
585

586
      update_column(:trace, nil)
D
Douwe Maan 已提交
587 588
    end

589 590 591 592
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

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

597 598 599 600
    def has_tags?
      tag_list.any?
    end

601
    def any_runners_online?
602
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
603 604
    end

K
Kamil Trzcinski 已提交
605
    def stuck?
606 607 608
      pending? && !any_runners_online?
    end

609
    def execute_hooks
610
      return unless project
611

612
      build_data = Gitlab::DataBuilder::Build.build(self)
613 614
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
615 616
    end

617 618 619 620
    def browsable_artifacts?
      artifacts_metadata?
    end

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

628 629
        metadata.to_entry
      end
630 631
    end

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

637 638 639
    def erase(opts = {})
      return false unless erasable?

640
      job_artifacts.destroy_all # rubocop: disable DestroyAll
641 642 643 644 645
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
646
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
647 648 649 650 651 652
    end

    def erased?
      !self.erased_at.nil?
    end

653
    def artifacts_expired?
654
      artifacts_expire_at && artifacts_expire_at < Time.now
655 656
    end

657 658 659 660 661
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

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

668
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
669
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
670 671
    end

672
    def keep_artifacts!
673
      self.update(artifacts_expire_at: nil)
674
      self.job_artifacts.update_all(expire_at: nil)
675 676
    end

677
    def artifacts_file_for_type(type)
678
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
679 680
    end

681
    def coverage_regex
682
      super || project.try(:build_coverage_regex)
683 684
    end

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

    def image
691
      Gitlab::Ci::Build::Image.from_image(self)
692 693 694
    end

    def services
695
      Gitlab::Ci::Build::Image.from_services(self)
696 697 698
    end

    def cache
M
Matija Čupić 已提交
699 700 701 702
      cache = options[:cache]

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

      [cache]
707 708
    end

709
    def credentials
710
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
711 712
    end

T
Tomasz Maczukin 已提交
713
    def dependencies
714 715
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
716 717
      depended_jobs = depends_on_builds

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

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

      depended_jobs
T
Tomasz Maczukin 已提交
729 730
    end

731 732 733 734
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
735
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
736
      return true if Feature.enabled?('ci_disable_validates_dependencies')
737

K
Kamil Trzciński 已提交
738
      dependencies.all?(&:valid_dependency?)
739 740
    end

K
Kamil Trzciński 已提交
741
    def valid_dependency?
S
Shinya Maeda 已提交
742 743 744 745 746 747
      return false if artifacts_expired?
      return false if erased?

      true
    end

748 749 750 751 752 753 754 755
    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

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

762
    def publishes_artifacts_reports?
763
      options&.dig(:artifacts, :reports)&.any?
764 765
    end

766 767 768 769
    def hide_secrets(trace)
      return unless trace

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

775
    def serializable_hash(options = {})
J
James Lopez 已提交
776
      super(options).merge(when: read_attribute(:when))
777 778
    end

F
Francisco Javier López 已提交
779 780 781 782
    def has_terminal?
      running? && runner_session_url.present?
    end

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

791 792 793 794
    def report_artifacts
      job_artifacts.with_reports
    end

795 796
    # Virtual deployment status depending on the environment status.
    def deployment_status
797
      return unless starts_environment?
798 799 800

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
801
      elsif failed?
802 803 804 805 806 807
        return :failed
      end

      :creating
    end

808 809
    private

810
    def successful_deployment_status
S
Shinya Maeda 已提交
811 812 813 814
      if deployment&.last?
        :last
      else
        :out_of_date
815 816 817
      end
    end

818 819 820 821
    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 已提交
822 823 824 825
        end
      end
    end

826 827 828 829 830
    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

831
    def erase_trace!
832
      trace.erase!
833 834 835
    end

    def update_erased!(user = nil)
836
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
837 838
    end

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

843
    def environment_url
844
      options&.dig(:environment, :url) || persisted_environment&.external_url
845 846
    end

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

860 861
    def build_attributes_from_config
      return {} unless pipeline.config_processor
862

863 864
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
865 866
  end
end