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

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

16 17
    BuildArchivedError = Class.new(StandardError)

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

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

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

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

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

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

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

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

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

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

59
    ##
60 61 62 63
    # 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.
64
    # (See more https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/22380)
65
    #
66 67 68 69 70
    # 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.
71
    def persisted_environment
72 73 74
      return unless has_environment?

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

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

D
Douwe Maan 已提交
83 84
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
85
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
86
    validates :ref, presence: true
D
Douwe Maan 已提交
87

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

99 100 101 102
    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

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

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

116 117
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

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

132 133 134 135 136
    scope :with_exposed_artifacts, -> do
      joins(:metadata).merge(Ci::BuildMetadata.with_exposed_artifacts)
        .includes(:metadata, :job_artifacts_metadata)
    end

137 138
    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) }
139
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
140 141
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
142
    scope :ref_protected, -> { where(protected: true) }
143
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
144 145
    scope :with_stale_live_trace, -> { with_live_trace.finished_before(12.hours.ago) }
    scope :finished_before, -> (date) { finished.where('finished_at < ?', date) }
146

147 148 149 150 151 152
    scope :with_secure_reports_from_options, -> (job_type) { where('options like :job_type', job_type: "%:artifacts:%:reports:%:#{job_type}:%") }

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

153 154
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
155
        .where(taggable_type: CommitStatus.name)
156 157 158 159 160 161 162 163 164
        .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
165
        .where(taggable_type: CommitStatus.name)
166 167 168 169 170 171
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

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

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

175 176 177
    PROJECT_ROUTE_AND_NAMESPACE_ROUTE = { project: [:project_feature, :route, { namespace: :route }] }.freeze
    scope :preload_project_and_pipeline_project, -> { preload(PROJECT_ROUTE_AND_NAMESPACE_ROUTE, pipeline: PROJECT_ROUTE_AND_NAMESPACE_ROUTE) }

D
Douwe Maan 已提交
178 179
    acts_as_taggable

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

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

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

D
Douwe Maan 已提交
189
    class << self
190 191 192 193 194 195
      # 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 已提交
196 197 198 199
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

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

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

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

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

      event :enqueue_preparing do
        transition preparing: :pending
      end

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

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

      event :unschedule do
        transition scheduled: :manual
      end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        true
339 340 341 342
      end

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

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

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

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

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

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

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

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

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

385 386 387 388
    def runnable?
      true
    end

389 390 391 392 393 394 395
    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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

461
    def expanded_environment_name
462 463 464
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
465
        ExpandVariables.expand(environment, -> { simple_variables })
466
      end
467 468
    end

469 470 471 472 473 474 475 476 477 478 479 480
    def expanded_kubernetes_namespace
      return unless has_environment?

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

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

481
    def requires_resource?
482
      Feature.enabled?(:ci_resource_group, project, default_enabled: true) &&
483 484 485
        self.resource_group_id.present?
    end

486
    def has_environment?
487
      environment.present?
488 489
    end

490
    def starts_environment?
491
      has_environment? && self.environment_action == 'start'
492 493 494
    end

    def stops_environment?
495
      has_environment? && self.environment_action == 'stop'
496 497 498
    end

    def environment_action
499
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
500 501 502
    end

    def outdated_deployment?
S
Shinya Maeda 已提交
503
      success? && !deployment.try(:last?)
504
    end
505

506 507
    def depends_on_builds
      # Get builds of the same type
508
      latest_builds = self.pipeline.builds.latest
509 510 511 512 513

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

514
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
515 516 517
      user == current_user
    end

S
Shinya Maeda 已提交
518 519 520 521
    def on_stop
      options&.dig(:environment, :on_stop)
    end

522 523 524 525
    ##
    # All variables, including persisted environment variables.
    #
    def variables
526 527 528 529
      strong_memoize(:variables) do
        Gitlab::Ci::Variables::Collection.new
          .concat(persisted_variables)
          .concat(scoped_variables)
M
Matija Čupić 已提交
530
          .concat(job_variables)
531 532 533
          .concat(persisted_environment_variables)
          .to_runner_variables
      end
534 535
    end

536
    CI_REGISTRY_USER = 'gitlab-ci-token'
537 538 539 540 541 542 543 544 545

    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))
546
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false, masked: true)
547
          .append(key: 'CI_BUILD_ID', value: id.to_s)
548
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false, masked: true)
549
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
550
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false, masked: true)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
          .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)
574
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false, masked: true)
575
      end
576 577
    end

578 579 580 581
    def features
      { trace_sections: true }
    end

582
    def merge_request
Z
Z.J. van de Weg 已提交
583
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
584

585 586
      @merge_request ||=
        begin
587
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
588 589
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
590
            .reorder(iid: :desc)
591 592

          merge_requests.find do |merge_request|
593
            merge_request.commit_shas.include?(pipeline.sha)
594 595
          end
        end
596 597
    end

D
Douwe Maan 已提交
598
    def repo_url
K
Kamil Trzciński 已提交
599 600 601
      return unless token

      auth = "gitlab-ci-token:#{token}@"
602
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
603 604
        prefix + auth
      end
D
Douwe Maan 已提交
605 606 607
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
608
      project.build_allow_git_fetch
D
Douwe Maan 已提交
609 610 611
    end

    def update_coverage
612
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
613
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
614 615
    end

616
    # rubocop: disable CodeReuse/ServiceClass
617
    def parse_trace_sections!
618
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
619
    end
620
    # rubocop: enable CodeReuse/ServiceClass
621

622 623
    def trace
      Gitlab::Ci::Trace.new(self)
624 625
    end

626
    def has_trace?
627
      trace.exist?
T
Tomasz Maczukin 已提交
628 629
    end

630 631 632 633 634 635 636 637
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    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

658 659
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
660 661
    end

S
Shinya Maeda 已提交
662 663 664 665
    def has_old_trace?
      old_trace.present?
    end

666 667
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
668 669
    end

670 671
    def old_trace
      read_attribute(:trace)
672 673
    end

674
    def erase_old_trace!
675
      return unless has_old_trace?
S
Shinya Maeda 已提交
676

677
      update_column(:trace, nil)
D
Douwe Maan 已提交
678 679
    end

680 681 682 683 684 685 686 687
    def artifacts_expose_as
      options.dig(:artifacts, :expose_as)
    end

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

688 689 690 691
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
692
    def valid_token?(token)
H
Heinrich Lee Yu 已提交
693
      self.token && ActiveSupport::SecurityUtils.secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
694 695
    end

696 697 698 699
    def has_tags?
      tag_list.any?
    end

700
    def any_runners_online?
701
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
702 703
    end

K
Kamil Trzcinski 已提交
704
    def stuck?
705 706 707
      pending? && !any_runners_online?
    end

708
    def execute_hooks
709
      return unless project
710

711 712
      project.execute_hooks(build_data.dup, :job_hooks) if project.has_active_hooks?(:job_hooks)
      project.execute_services(build_data.dup, :job_hooks) if project.has_active_services?(:job_hooks)
713 714
    end

715 716 717 718
    def browsable_artifacts?
      artifacts_metadata?
    end

719
    def artifacts_metadata_entry(path, **options)
720
      artifacts_metadata.open do |metadata_stream|
721
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
722
          metadata_stream,
723 724
          path,
          **options)
725

726 727
        metadata.to_entry
      end
728 729
    end

730 731 732
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
S
Shinya Maeda 已提交
733 734
    end

735 736 737
    def erase(opts = {})
      return false unless erasable?

738
      job_artifacts.destroy_all # rubocop: disable DestroyAll
739 740 741 742 743
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
744
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
745 746 747 748 749 750
    end

    def erased?
      !self.erased_at.nil?
    end

751
    def artifacts_expired?
752
      artifacts_expire_at && artifacts_expire_at < Time.now
753 754
    end

755 756 757 758 759
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
760 761
      self.artifacts_expire_at =
        if value
762
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
763
        end
764 765
    end

766 767
    def has_expiring_archive_artifacts?
      has_expiring_artifacts? && job_artifacts_archive.present?
768 769
    end

770
    def keep_artifacts!
771
      self.update(artifacts_expire_at: nil)
772
      self.job_artifacts.update_all(expire_at: nil)
773 774
    end

775
    def artifacts_file_for_type(type)
776
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
777 778
    end

779
    def coverage_regex
780
      super || project.try(:build_coverage_regex)
781 782
    end

783
    def steps
T
Tomasz Maczukin 已提交
784 785
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
786 787 788
    end

    def image
789
      Gitlab::Ci::Build::Image.from_image(self)
790 791 792
    end

    def services
793
      Gitlab::Ci::Build::Image.from_services(self)
794 795 796
    end

    def cache
M
Matija Čupić 已提交
797 798 799 800
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
801
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
802
      end
M
Matija Čupić 已提交
803 804

      [cache]
805 806
    end

807
    def credentials
808
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
809 810
    end

811 812 813 814
    def all_dependencies
      (dependencies + cross_dependencies).uniq
    end

T
Tomasz Maczukin 已提交
815
    def dependencies
816 817
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
818 819
      depended_jobs = depends_on_builds

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

K
Kamil Trzciński 已提交
825 826 827
      # find all jobs that are dependent on
      if options[:dependencies].present?
        depended_jobs = depended_jobs.where(name: options[:dependencies])
T
Tomasz Maczukin 已提交
828
      end
K
Kamil Trzciński 已提交
829

830 831
      # if both needs and dependencies are used,
      # the end result will be an intersection between them
K
Kamil Trzciński 已提交
832
      depended_jobs
T
Tomasz Maczukin 已提交
833 834
    end

835 836 837 838
    def cross_dependencies
      []
    end

839 840 841 842
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
843
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
844
      return true if Feature.enabled?('ci_disable_validates_dependencies')
845

K
Kamil Trzciński 已提交
846
      dependencies.all?(&:valid_dependency?)
847 848
    end

K
Kamil Trzciński 已提交
849
    def valid_dependency?
S
Shinya Maeda 已提交
850 851 852 853 854 855
      return false if artifacts_expired?
      return false if erased?

      true
    end

856 857 858 859
    def invalid_dependencies
      dependencies.reject(&:valid_dependency?)
    end

860 861 862 863 864 865 866 867
    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

868
    def supported_runner?(features)
869
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
870
        features&.dig(feature_name)
871 872 873
      end
    end

874
    def publishes_artifacts_reports?
875
      options&.dig(:artifacts, :reports)&.any?
876 877
    end

878 879 880 881
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
882
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
883
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
884 885 886
      trace
    end

887
    def serializable_hash(options = {})
J
James Lopez 已提交
888
      super(options).merge(when: read_attribute(:when))
889 890
    end

F
Francisco Javier López 已提交
891 892 893 894
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
895 896
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
897
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
898
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
899 900 901 902
        end
      end
    end

903 904 905 906
    def report_artifacts
      job_artifacts.with_reports
    end

907 908
    # Virtual deployment status depending on the environment status.
    def deployment_status
909
      return unless starts_environment?
910 911 912

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
913
      elsif failed?
914 915 916 917 918 919
        return :failed
      end

      :creating
    end

920 921 922 923 924 925 926
    # Consider this object to have a structural integrity problems
    def doom!
      update_columns(
        status: :failed,
        failure_reason: :data_integrity_failure)
    end

927 928
    private

929 930 931 932
    def build_data
      @build_data ||= Gitlab::DataBuilder::Build.build(self)
    end

933
    def successful_deployment_status
S
Shinya Maeda 已提交
934 935 936 937
      if deployment&.last?
        :last
      else
        :out_of_date
938 939 940
      end
    end

941 942 943
    def each_report(report_types)
      job_artifacts_for_types(report_types).each do |report_artifact|
        report_artifact.each_blob do |blob|
944
          yield report_artifact.file_type, blob, report_artifact
S
Shinya Maeda 已提交
945 946 947 948
        end
      end
    end

949 950 951 952 953
    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

954
    def erase_trace!
955
      trace.erase!
956 957 958
    end

    def update_erased!(user = nil)
959
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
960 961
    end

962
    def unscoped_project
K
Kamil Trzciński 已提交
963
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
964 965
    end

966
    def environment_url
967
      options&.dig(:environment, :url) || persisted_environment&.external_url
968 969
    end

970 971 972 973 974
    # 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.
975 976
    def options_retry
      strong_memoize(:options_retry) do
977 978 979 980
        value = options&.dig(:retry)
        value = value.is_a?(Integer) ? { max: value } : value.to_h
        value.with_indifferent_access
      end
M
Markus Doits 已提交
981
    end
982 983 984 985

    def has_expiring_artifacts?
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
    end
D
Douwe Maan 已提交
986 987
  end
end
988 989

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