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

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

18 19
    BuildArchivedError = Class.new(StandardError)

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

22
    belongs_to :project, inverse_of: :builds
23 24
    belongs_to :runner
    belongs_to :trigger_request
25
    belongs_to :erased_by, class_name: 'User'
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_many :trace_sections, class_name: 'Ci::BuildTraceSection'
38
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
39

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

    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
47

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

146 147 148 149 150 151
    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

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

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

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

D
Douwe Maan 已提交
174 175
    acts_as_taggable

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

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

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

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

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

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

210 211
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
212 213
      end

214 215 216 217 218 219 220 221
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

S
Shinya Maeda 已提交
222
      event :enqueue_scheduled do
T
Tiger 已提交
223 224 225 226
        transition scheduled: :preparing, if: ->(build) do
          build.scheduled_at&.past? && build.any_unmet_prerequisites?
        end

227
        transition scheduled: :pending, if: ->(build) do
T
Tiger 已提交
228
          build.scheduled_at&.past? && !build.any_unmet_prerequisites?
S
Shinya Maeda 已提交
229
        end
230 231 232
      end

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
233 234 235 236
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
237
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
238 239 240 241 242 243
      end

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

T
Tiger 已提交
246 247 248 249 250 251
      after_transition any => [:preparing] do |build|
        build.run_after_commit do
          Ci::BuildPrepareWorker.perform_async(id)
        end
      end

252 253
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
254
          BuildQueueWorker.perform_async(id)
255 256 257
        end
      end

258
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
259 260
        build.deployment&.run

261
        build.run_after_commit do
262 263
          build.pipeline.persistent_ref.create

264 265
          BuildHooksWorker.perform_async(id)
        end
266 267
      end

268
      after_transition any => [:success, :failed, :canceled] do |build|
269
        build.run_after_commit do
270
          BuildFinishedWorker.perform_async(id)
271
        end
D
Douwe Maan 已提交
272
      end
273

274
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
275 276
        build.deployment&.succeed

277
        build.run_after_commit do
278
          BuildSuccessWorker.perform_async(id)
279
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
280 281
        end
      end
282

283
      before_transition any => [:failed] do |build|
284
        next unless build.project
285
        next unless build.deployment
S
Shinya Maeda 已提交
286

287 288 289
        begin
          build.deployment.drop!
        rescue => e
290
          Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e, build_id: build.id)
291 292 293
        end

        true
294 295 296 297
      end

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

299
        if build.retry_failure?
300 301 302
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
M
Mayra Cabrera 已提交
303
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}" # rubocop:disable Gitlab/RailsLogger
304
          end
305 306
        end
      end
307

308
      after_transition pending: :running do |build|
309
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
310
      end
F
Francisco Javier López 已提交
311 312 313 314

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
315 316 317 318

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

321
    def detailed_status(current_user)
322 323 324
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
325 326
    end

327
    def other_manual_actions
328
      pipeline.manual_actions.where.not(name: name)
329 330
    end

331 332
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
333 334
    end

335 336 337 338 339
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

340 341 342 343
    def runnable?
      true
    end

344 345 346 347 348 349 350
    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

351
    def playable?
352
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
353 354
    end

S
Shinya Maeda 已提交
355
    def schedulable?
356
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
357 358
    end

S
Shinya Maeda 已提交
359
    def options_scheduled_at
S
Shinya Maeda 已提交
360
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
361 362
    end

363
    def action?
364
      %w[manual delayed].include?(self.when)
365 366
    end

367
    # rubocop: disable CodeReuse/ServiceClass
M
Matija Čupić 已提交
368
    def play(current_user, job_variables_attributes = nil)
369 370
      Ci::PlayBuildService
        .new(project, current_user)
M
Matija Čupić 已提交
371
        .execute(self, job_variables_attributes)
372
    end
373
    # rubocop: enable CodeReuse/ServiceClass
374

K
Kamil Trzcinski 已提交
375
    def cancelable?
J
Jacopo 已提交
376
      active? || created?
K
Kamil Trzcinski 已提交
377 378
    end

K
Kamil Trzcinski 已提交
379
    def retryable?
K
Kamil Trzciński 已提交
380
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
381
    end
382 383 384 385 386

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

387 388 389 390 391 392
    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
393
    end
K
Kamil Trzcinski 已提交
394

395 396
    def options_retry_max
      options_retry[:max]
397 398
    end

399 400 401
    def options_retry_when
      options_retry.fetch(:when, ['always'])
    end
402

403 404 405
    def retry_on_reason_or_always?
      options_retry_when.include?(failure_reason.to_s) ||
        options_retry_when.include?('always')
406
    end
K
Kamil Trzcinski 已提交
407

408 409
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
410 411
    end

T
Tiger 已提交
412 413 414 415 416 417 418 419
    def any_unmet_prerequisites?
      prerequisites.present?
    end

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

420
    def expanded_environment_name
421 422 423
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
424
        ExpandVariables.expand(environment, -> { simple_variables })
425
      end
426 427
    end

428 429 430 431 432 433 434 435 436 437 438 439
    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

440
    def has_environment?
441
      environment.present?
442 443
    end

444
    def starts_environment?
445
      has_environment? && self.environment_action == 'start'
446 447 448
    end

    def stops_environment?
449
      has_environment? && self.environment_action == 'stop'
450 451 452
    end

    def environment_action
453
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
454 455 456
    end

    def outdated_deployment?
S
Shinya Maeda 已提交
457
      success? && !deployment.try(:last?)
458
    end
459

460 461
    def depends_on_builds
      # Get builds of the same type
462
      latest_builds = self.pipeline.builds.latest
463 464 465 466 467

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

468
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
469 470 471
      user == current_user
    end

S
Shinya Maeda 已提交
472 473 474 475
    def on_stop
      options&.dig(:environment, :on_stop)
    end

476 477 478 479
    ##
    # All variables, including persisted environment variables.
    #
    def variables
480 481 482 483
      strong_memoize(:variables) do
        Gitlab::Ci::Variables::Collection.new
          .concat(persisted_variables)
          .concat(scoped_variables)
M
Matija Čupić 已提交
484
          .concat(job_variables)
485 486 487
          .concat(persisted_environment_variables)
          .to_runner_variables
      end
488 489
    end

490
    CI_REGISTRY_USER = 'gitlab-ci-token'
491 492 493 494 495 496 497 498 499

    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))
500
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false, masked: true)
501
          .append(key: 'CI_BUILD_ID', value: id.to_s)
502
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false, masked: true)
503
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
504
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false, masked: true)
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
          .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)
528
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false, masked: true)
529
      end
530 531
    end

532 533 534 535
    def features
      { trace_sections: true }
    end

536
    def merge_request
Z
Z.J. van de Weg 已提交
537
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
538

539 540
      @merge_request ||=
        begin
541
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
542 543
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
544
            .reorder(iid: :desc)
545 546

          merge_requests.find do |merge_request|
547
            merge_request.commit_shas.include?(pipeline.sha)
548 549
          end
        end
550 551
    end

D
Douwe Maan 已提交
552
    def repo_url
K
Kamil Trzciński 已提交
553 554 555
      return unless token

      auth = "gitlab-ci-token:#{token}@"
556
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
557 558
        prefix + auth
      end
D
Douwe Maan 已提交
559 560 561
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
562
      project.build_allow_git_fetch
D
Douwe Maan 已提交
563 564 565
    end

    def update_coverage
566
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
567
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
568 569
    end

570
    # rubocop: disable CodeReuse/ServiceClass
571
    def parse_trace_sections!
572
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
573
    end
574
    # rubocop: enable CodeReuse/ServiceClass
575

576 577
    def trace
      Gitlab::Ci::Trace.new(self)
578 579
    end

580
    def has_trace?
581
      trace.exist?
T
Tomasz Maczukin 已提交
582 583
    end

584 585 586 587 588 589 590 591
    def has_live_trace?
      trace.live_trace_exist?
    end

    def has_archived_trace?
      trace.archived_trace_exist?
    end

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    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

612 613
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
614 615
    end

S
Shinya Maeda 已提交
616 617 618 619
    def has_old_trace?
      old_trace.present?
    end

620 621
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
622 623
    end

624 625
    def old_trace
      read_attribute(:trace)
626 627
    end

628
    def erase_old_trace!
629
      return unless has_old_trace?
S
Shinya Maeda 已提交
630

631
      update_column(:trace, nil)
D
Douwe Maan 已提交
632 633
    end

634 635 636 637 638 639 640 641
    def artifacts_expose_as
      options.dig(:artifacts, :expose_as)
    end

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

642 643 644 645
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
646
    def valid_token?(token)
H
Heinrich Lee Yu 已提交
647
      self.token && ActiveSupport::SecurityUtils.secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
648 649
    end

650 651 652 653
    def has_tags?
      tag_list.any?
    end

654
    def any_runners_online?
655
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
656 657
    end

K
Kamil Trzcinski 已提交
658
    def stuck?
659 660 661
      pending? && !any_runners_online?
    end

662
    def execute_hooks
663
      return unless project
664

665 666
      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)
667 668
    end

669 670 671 672
    def browsable_artifacts?
      artifacts_metadata?
    end

673
    def artifacts_metadata_entry(path, **options)
674
      artifacts_metadata.open do |metadata_stream|
675
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
676
          metadata_stream,
677 678
          path,
          **options)
679

680 681
        metadata.to_entry
      end
682 683
    end

684 685 686
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
S
Shinya Maeda 已提交
687 688
    end

689 690 691
    def erase(opts = {})
      return false unless erasable?

692
      job_artifacts.destroy_all # rubocop: disable DestroyAll
693 694 695 696 697
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
698
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
699 700 701 702 703 704
    end

    def erased?
      !self.erased_at.nil?
    end

705
    def artifacts_expired?
706
      artifacts_expire_at && artifacts_expire_at < Time.now
707 708
    end

709 710 711 712 713
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
714 715
      self.artifacts_expire_at =
        if value
716
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
717
        end
718 719
    end

720
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
721
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
722 723
    end

724
    def keep_artifacts!
725
      self.update(artifacts_expire_at: nil)
726
      self.job_artifacts.update_all(expire_at: nil)
727 728
    end

729
    def artifacts_file_for_type(type)
730
      job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
731 732
    end

733
    def coverage_regex
734
      super || project.try(:build_coverage_regex)
735 736
    end

737
    def steps
T
Tomasz Maczukin 已提交
738 739
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
740 741 742
    end

    def image
743
      Gitlab::Ci::Build::Image.from_image(self)
744 745 746
    end

    def services
747
      Gitlab::Ci::Build::Image.from_services(self)
748 749 750
    end

    def cache
M
Matija Čupić 已提交
751 752 753 754
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
755
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
756
      end
M
Matija Čupić 已提交
757 758

      [cache]
759 760
    end

761
    def credentials
762
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
763 764
    end

T
Tomasz Maczukin 已提交
765
    def dependencies
766 767
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
768 769
      depended_jobs = depends_on_builds

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

K
Kamil Trzciński 已提交
775 776 777
      # find all jobs that are dependent on
      if options[:dependencies].present?
        depended_jobs = depended_jobs.where(name: options[:dependencies])
T
Tomasz Maczukin 已提交
778
      end
K
Kamil Trzciński 已提交
779

780 781
      # if both needs and dependencies are used,
      # the end result will be an intersection between them
K
Kamil Trzciński 已提交
782
      depended_jobs
T
Tomasz Maczukin 已提交
783 784
    end

785 786 787 788
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
789
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
790
      return true if Feature.enabled?('ci_disable_validates_dependencies')
791

K
Kamil Trzciński 已提交
792
      dependencies.all?(&:valid_dependency?)
793 794
    end

K
Kamil Trzciński 已提交
795
    def valid_dependency?
S
Shinya Maeda 已提交
796 797 798 799 800 801
      return false if artifacts_expired?
      return false if erased?

      true
    end

802 803 804 805
    def invalid_dependencies
      dependencies.reject(&:valid_dependency?)
    end

806 807 808 809 810 811 812 813
    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

814
    def supported_runner?(features)
815
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
816
        features&.dig(feature_name)
817 818 819
      end
    end

820
    def publishes_artifacts_reports?
821
      options&.dig(:artifacts, :reports)&.any?
822 823
    end

824 825 826 827
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
828
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
829
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
830 831 832
      trace
    end

833
    def serializable_hash(options = {})
J
James Lopez 已提交
834
      super(options).merge(when: read_attribute(:when))
835 836
    end

F
Francisco Javier López 已提交
837 838 839 840
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
841 842
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
843
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
844
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
845 846 847 848
        end
      end
    end

849 850 851 852
    def report_artifacts
      job_artifacts.with_reports
    end

853 854
    # Virtual deployment status depending on the environment status.
    def deployment_status
855
      return unless starts_environment?
856 857 858

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
859
      elsif failed?
860 861 862 863 864 865
        return :failed
      end

      :creating
    end

866 867 868 869 870 871 872
    # Consider this object to have a structural integrity problems
    def doom!
      update_columns(
        status: :failed,
        failure_reason: :data_integrity_failure)
    end

873 874
    private

875 876 877 878
    def build_data
      @build_data ||= Gitlab::DataBuilder::Build.build(self)
    end

879
    def successful_deployment_status
S
Shinya Maeda 已提交
880 881 882 883
      if deployment&.last?
        :last
      else
        :out_of_date
884 885 886
      end
    end

887 888 889 890
    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 已提交
891 892 893 894
        end
      end
    end

895 896 897 898 899
    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

900
    def erase_trace!
901
      trace.erase!
902 903 904
    end

    def update_erased!(user = nil)
905
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
906 907
    end

908
    def unscoped_project
K
Kamil Trzciński 已提交
909
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
910 911
    end

912
    def environment_url
913
      options&.dig(:environment, :url) || persisted_environment&.external_url
914 915
    end

916 917 918 919 920
    # 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.
921 922
    def options_retry
      strong_memoize(:options_retry) do
923 924 925 926
        value = options&.dig(:retry)
        value = value.is_a?(Integer) ? { max: value } : value.to_h
        value.with_indifferent_access
      end
M
Markus Doits 已提交
927
    end
D
Douwe Maan 已提交
928 929
  end
end
930 931

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