build.rb 28.0 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 Gitlab::Utils::StrongMemoize
14
    include HasRef
15
    include IgnorableColumns
16

17 18
    BuildArchivedError = Class.new(StandardError)

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

21
    belongs_to :project, inverse_of: :builds
22 23
    belongs_to :runner
    belongs_to :trigger_request
24
    belongs_to :erased_by, class_name: 'User'
25
    belongs_to :resource_group, class_name: 'Ci::ResourceGroup', inverse_of: :builds
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

D
Douwe Maan 已提交
175 176
    acts_as_taggable

K
Kamil Trzciński 已提交
177
    add_authentication_token_field :token, encrypted: :optional
178 179

    before_save :ensure_token
180
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
181

182
    after_create unless: :importing? do |build|
183
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
184 185
    end

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

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

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

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      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

227 228
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
229 230
      end

231 232 233 234 235 236 237 238
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

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

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
244 245 246 247
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
248
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
249 250
      end

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
      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|
269
        !build.any_unmet_prerequisites? # If false is returned, it stops the transition
270 271
      end

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

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

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

290
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
291 292
        build.deployment&.run

293
        build.run_after_commit do
294 295
          build.pipeline.persistent_ref.create

296 297
          BuildHooksWorker.perform_async(id)
        end
298 299
      end

300 301 302 303 304 305 306 307 308 309
      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

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

316
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
317 318
        build.deployment&.succeed

319
        build.run_after_commit do
320
          BuildSuccessWorker.perform_async(id)
321
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
322 323
        end
      end
324

325
      before_transition any => [:failed] do |build|
326
        next unless build.project
327
        next unless build.deployment
S
Shinya Maeda 已提交
328

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

        true
336 337 338 339
      end

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

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

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

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
357 358 359 360

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

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

369
    def other_manual_actions
370
      pipeline.manual_actions.where.not(name: name)
371 372
    end

373 374
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
375 376
    end

377 378 379 380 381
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

382 383 384 385
    def runnable?
      true
    end

386 387 388 389 390 391 392
    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

393
    def playable?
394
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
395 396
    end

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

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

405
    def action?
406
      %w[manual delayed].include?(self.when)
407 408
    end

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

K
Kamil Trzcinski 已提交
417
    def cancelable?
J
Jacopo 已提交
418
      active? || created?
K
Kamil Trzcinski 已提交
419 420
    end

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

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

429 430 431 432 433 434
    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
435
    end
K
Kamil Trzcinski 已提交
436

437 438
    def options_retry_max
      options_retry[:max]
439 440
    end

441 442 443
    def options_retry_when
      options_retry.fetch(:when, ['always'])
    end
444

445 446 447
    def retry_on_reason_or_always?
      options_retry_when.include?(failure_reason.to_s) ||
        options_retry_when.include?('always')
448
    end
K
Kamil Trzcinski 已提交
449

450 451
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
452 453
    end

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

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

462
    def expanded_environment_name
463 464 465
      return unless has_environment?

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

470 471 472 473 474 475 476 477 478 479 480 481
    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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def has_archived_trace?
      trace.archived_trace_exist?
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

709
    def execute_hooks
710
      return unless project
711

712 713
      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)
714 715
    end

716 717 718 719
    def browsable_artifacts?
      artifacts_metadata?
    end

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

727 728
        metadata.to_entry
      end
729 730
    end

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

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

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

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

    def erased?
      !self.erased_at.nil?
    end

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

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

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

767 768
    def has_expiring_artifacts?
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
769 770
    end

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

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

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

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

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

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

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

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

      [cache]
806 807
    end

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

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

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

T
Tomasz Maczukin 已提交
819 820
      depended_jobs = depends_on_builds

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

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

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

836 837 838 839
    def cross_dependencies
      []
    end

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

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

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

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

      true
    end

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

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

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

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

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

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

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

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

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

904 905 906 907
    def report_artifacts
      job_artifacts.with_reports
    end

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

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

      :creating
    end

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

928 929
    private

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

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

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

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

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

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

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

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

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

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