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

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

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

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

D
Douwe Maan 已提交
154 155
    acts_as_taggable

K
Kamil Trzciński 已提交
156
    add_authentication_token_field :token, encrypted: :optional
157 158

    before_save :ensure_token
159
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
160

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

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

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

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

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

194 195 196 197 198 199 200 201
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

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

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

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

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

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

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

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

238
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
239 240
        build.deployment&.run

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

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

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

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

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

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

        true
272 273 274 275
      end

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

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

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

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

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

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

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

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

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

318 319 320 321
    def runnable?
      true
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

391
    def expanded_environment_name
392 393 394
      return unless has_environment?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def has_archived_trace?
      trace.archived_trace_exist?
    end

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

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

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

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

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

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

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

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

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

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

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

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

617
    def execute_hooks
618
      return unless project
619

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

625 626 627 628
    def browsable_artifacts?
      artifacts_metadata?
    end

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

636 637
        metadata.to_entry
      end
638 639
    end

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

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

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

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

    def erased?
      !self.erased_at.nil?
    end

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

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

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

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

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

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

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

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

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

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

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

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

      [cache]
715 716
    end

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

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

T
Tomasz Maczukin 已提交
724 725
      depended_jobs = depends_on_builds

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

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

      depended_jobs
T
Tomasz Maczukin 已提交
737 738
    end

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

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

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

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

      true
    end

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

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

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

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

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

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

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

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

799 800 801 802
    def report_artifacts
      job_artifacts.with_reports
    end

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

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

      :creating
    end

816 817
    private

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

826 827 828 829
    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 已提交
830 831 832 833
        end
      end
    end

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

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

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

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

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

855 856 857 858 859
    # 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 已提交
860
    def normalized_retry
861 862 863 864 865
      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 已提交
866 867
    end

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

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

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