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

Douwe Maan's avatar
Douwe Maan committed
3
module Ci
Kamil Trzcinski's avatar
Kamil Trzcinski committed
4
  class Build < CommitStatus
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
5
    prepend ArtifactMigratable
6
    include TokenAuthenticatable
7
    include AfterCommitQueue
8
    include ObjectStorage::BackgroundMove
Rémy Coutable's avatar
Rémy Coutable committed
9
    include Presentable
Shinya Maeda's avatar
Shinya Maeda committed
10
    include Importable
11
    include Gitlab::Utils::StrongMemoize
12
    include Deployable
13

14
    belongs_to :project, inverse_of: :builds
15 16
    belongs_to :runner
    belongs_to :trigger_request
17
    belongs_to :erased_by, class_name: 'User'
Douwe Maan's avatar
Douwe Maan committed
18

19 20 21 22
    RUNNER_FEATURES = {
      upload_multiple_artifacts: -> (build) { build.publishes_artifacts_reports? }
    }.freeze

23
    has_one :deployment, as: :deployable, class_name: 'Deployment'
24
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
25
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
26

27
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
28 29 30 31

    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
32

33
    has_one :metadata, class_name: 'Ci::BuildMetadata'
34 35 36 37
    has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build

    accepts_nested_attributes_for :runner_session

Tomasz Maczukin's avatar
Tomasz Maczukin committed
38
    delegate :timeout, to: :metadata, prefix: true, allow_nil: true
39 40
    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
41
    delegate :gitlab_deploy_token, to: :project
42
    delegate :trigger_short_token, to: :trigger_request, allow_nil: true
Tomasz Maczukin's avatar
Tomasz Maczukin committed
43

44 45 46
    ##
    # The "environment" field for builds is a String, and is the unexpanded name!
    #
47
    def persisted_environment
48 49 50 51 52
      return unless has_environment?

      strong_memoize(:persisted_environment) do
        Environment.find_by(name: expanded_environment_name, project: project)
      end
53 54
    end

55 56
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
Douwe Maan's avatar
Douwe Maan committed
57

Douwe Maan's avatar
Douwe Maan committed
58 59
    delegate :name, to: :project, prefix: true

Douwe Maan's avatar
Douwe Maan committed
60
    validates :coverage, numericality: true, allow_blank: true
Douwe Maan's avatar
Douwe Maan committed
61
    validates :ref, presence: true
Douwe Maan's avatar
Douwe Maan committed
62 63

    scope :unstarted, ->() { where(runner_id: nil) }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
64
    scope :ignore_failures, ->() { where(allow_failure: false) }
65
    scope :with_artifacts_archive, ->() do
66
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
67
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
68
    end
69

70 71 72 73
    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

74
    scope :with_archived_trace, ->() do
75
      with_existing_job_artifacts(Ci::JobArtifact.trace)
76 77
    end

78 79 80 81
    scope :without_archived_trace, ->() do
      where('NOT EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').trace)
    end

82
    scope :with_test_reports, ->() do
83 84
      with_existing_job_artifacts(Ci::JobArtifact.test_reports)
        .eager_load_job_artifacts
85 86
    end

87 88
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

89
    scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
90
    scope :with_archived_trace_stored_locally, -> { with_archived_trace.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
91 92
    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) }
93
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
94 95
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
96
    scope :ref_protected, -> { where(protected: true) }
97
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
98

99 100
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
101
        .where(taggable_type: CommitStatus.name)
102 103 104 105 106 107 108 109 110
        .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
111
        .where(taggable_type: CommitStatus.name)
112 113 114 115 116 117
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

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

118 119
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
Kamil Trzcinski's avatar
Kamil Trzcinski committed
120

Douwe Maan's avatar
Douwe Maan committed
121 122
    acts_as_taggable

Kamil Trzciński's avatar
Kamil Trzciński committed
123
    add_authentication_token_field :token, encrypted: true, fallback: true
124

125
    before_save :update_artifacts_size, if: :artifacts_file_changed?
126
    before_save :ensure_token
127
    before_destroy { unscoped_project }
Grzegorz Bizon's avatar
Grzegorz Bizon committed
128

129
    before_create :ensure_metadata
130
    after_create unless: :importing? do |build|
131
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
132 133
    end

134 135
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
Douwe Maan's avatar
Douwe Maan committed
136 137

    class << self
138 139 140 141 142 143
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

Douwe Maan's avatar
Douwe Maan committed
144 145 146 147
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

148
      def retry(build, current_user)
149
        # rubocop: disable CodeReuse/ServiceClass
150 151 152
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
153
        # rubocop: enable CodeReuse/ServiceClass
Douwe Maan's avatar
Douwe Maan committed
154 155 156
      end
    end

157
    state_machine :status do
158 159
      event :actionize do
        transition created: :manual
Kamil Trzcinski's avatar
Kamil Trzcinski committed
160 161
      end

162 163 164 165 166 167 168 169
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

170
      event :enqueue_scheduled do
171 172
        transition scheduled: :pending, if: ->(build) do
          build.scheduled_at && build.scheduled_at < Time.now
173
        end
174 175 176
      end

      before_transition scheduled: any do |build|
177 178 179 180
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
Shinya Maeda's avatar
Shinya Maeda committed
181
        build.scheduled_at = build.options_scheduled_at
182 183 184 185 186 187
      end

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

190 191
      after_transition any => [:pending] do |build|
        build.run_after_commit do
Kim "BKC" Carlbäcker's avatar
linting  
Kim "BKC" Carlbäcker committed
192
          BuildQueueWorker.perform_async(id)
193 194 195
        end
      end

196
      after_transition pending: :running do |build|
197 198
        build.deployment&.run

199 200 201
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
202 203
      end

204
      after_transition any => [:success, :failed, :canceled] do |build|
205
        build.run_after_commit do
206
          BuildFinishedWorker.perform_async(id)
207
        end
Douwe Maan's avatar
Douwe Maan committed
208
      end
209

210
      after_transition any => [:success] do |build|
211 212
        build.deployment&.succeed

213
        build.run_after_commit do
214
          BuildSuccessWorker.perform_async(id)
215
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
216 217
        end
      end
218

219
      before_transition any => [:failed] do |build|
220
        next unless build.project
221 222 223

        build.deployment&.drop

224
        if build.retry_failure?
225 226 227 228 229
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
230 231
        end
      end
232

233
      after_transition pending: :running do |build|
234
        build.ensure_metadata.update_timeout_state
235
      end
236 237 238 239

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
240 241 242 243

      after_transition any => [:skipped, :canceled] do |build|
        build.deployment&.cancel
      end
Douwe Maan's avatar
Douwe Maan committed
244 245
    end

246
    def ensure_metadata
Tomasz Maczukin's avatar
Tomasz Maczukin committed
247
      metadata || build_metadata(project: project)
Douwe Maan's avatar
Douwe Maan committed
248 249
    end

250
    def detailed_status(current_user)
251 252 253
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
Kamil Trzcinski's avatar
Kamil Trzcinski committed
254 255
    end

256
    def other_manual_actions
257
      pipeline.manual_actions.where.not(name: name)
258 259
    end

260 261
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
262 263
    end

264 265 266 267 268
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    # degenerated build is one that cannot be run by Runner
    def degenerated?
      self.options.nil?
    end

    def degenerate!
      self.update!(options: nil, yaml_variables: nil, commands: nil)
    end

    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

285
    def playable?
286
      action? && !archived? && (manual? || scheduled? || retryable?)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
287 288
    end

Shinya Maeda's avatar
Shinya Maeda committed
289
    def schedulable?
290
      self.when == 'delayed' && options[:start_in].present?
Shinya Maeda's avatar
Shinya Maeda committed
291 292
    end

Shinya Maeda's avatar
Shinya Maeda committed
293
    def options_scheduled_at
Shinya Maeda's avatar
Shinya Maeda committed
294
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
Kamil Trzcinski's avatar
Kamil Trzcinski committed
295 296
    end

297
    def action?
298
      %w[manual delayed].include?(self.when)
299 300
    end

301
    # rubocop: disable CodeReuse/ServiceClass
302
    def play(current_user)
303 304 305
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
306
    end
307
    # rubocop: enable CodeReuse/ServiceClass
308

Kamil Trzcinski's avatar
Kamil Trzcinski committed
309
    def cancelable?
Jacopo's avatar
Jacopo committed
310
      active? || created?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
311 312
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
313
    def retryable?
314
      !archived? && (success? || failed? || canceled?)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
315
    end
316 317 318 319 320 321

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

    def retries_max
322
      normalized_retry.fetch(:max, 0)
323
    end
Kamil Trzcinski's avatar
Kamil Trzcinski committed
324

325
    def retry_when
326
      normalized_retry.fetch(:when, ['always'])
327 328
    end

329 330 331
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

332
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
333
    end
Kamil Trzcinski's avatar
Kamil Trzcinski committed
334

335 336
    def latest?
      !retried?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
337 338
    end

339
    def expanded_environment_name
340 341 342
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
343 344
        ExpandVariables.expand(environment, simple_variables)
      end
345 346
    end

347
    def has_environment?
348
      environment.present?
349 350
    end

351
    def starts_environment?
352
      has_environment? && self.environment_action == 'start'
353 354 355
    end

    def stops_environment?
356
      has_environment? && self.environment_action == 'stop'
357 358 359
    end

    def environment_action
360
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
361 362
    end

363 364 365 366
    def has_deployment?
      !!self.deployment
    end

367
    def outdated_deployment?
368
      success? && !deployment.try(:last?)
369
    end
370

371 372
    def depends_on_builds
      # Get builds of the same type
373
      latest_builds = self.pipeline.builds.latest
374 375 376 377 378

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

379
    def triggered_by?(current_user)
Shinya Maeda's avatar
Shinya Maeda committed
380 381 382
      user == current_user
    end

383 384 385 386
    def on_stop
      options&.dig(:environment, :on_stop)
    end

Nick Thomas's avatar
Nick Thomas committed
387 388 389 390 391 392
    # A slugified version of the build ref, suitable for inclusion in URLs and
    # domain names. Rules:
    #
    #   * Lowercased
    #   * Anything not matching [a-z0-9-] is replaced with a -
    #   * Maximum length is 63 bytes
Shinya Maeda's avatar
Shinya Maeda committed
393
    #   * First/Last Character is not a hyphen
Nick Thomas's avatar
Nick Thomas committed
394
    def ref_slug
vanadium23's avatar
vanadium23 committed
395
      Gitlab::Utils.slugify(ref.to_s)
Nick Thomas's avatar
Nick Thomas committed
396 397
    end

398
    ##
399
    # Variables in the environment name scope.
400
    #
401 402
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
403 404 405 406
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
407
        variables.concat(project.deployment_variables(environment: environment)) if environment
408 409
        variables.concat(yaml_variables)
        variables.concat(user_variables)
410 411
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
412 413 414 415
        variables.concat(trigger_request.user_variables) if trigger_request
        variables.concat(pipeline.variables)
        variables.concat(pipeline.pipeline_schedule.job_variables) if pipeline.pipeline_schedule
      end
416
    end
417

418 419 420 421
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
422 423 424
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
425 426 427 428 429 430
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
431 432 433
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
434 435 436 437
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

438 439 440 441 442
    ##
    # Regular Ruby hash of scoped variables, without duplicates that are
    # possible to be present in an array of hashes returned from `variables`.
    #
    def scoped_variables_hash
443
      scoped_variables.to_hash
444 445
    end

446 447 448 449
    def features
      { trace_sections: true }
    end

450
    def merge_request
Z.J. van de Weg's avatar
Z.J. van de Weg committed
451
      return @merge_request if defined?(@merge_request)
Z.J. van de Weg's avatar
Z.J. van de Weg committed
452

453 454
      @merge_request ||=
        begin
455
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
456 457
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z.J. van de Weg's avatar
Z.J. van de Weg committed
458
            .reorder(iid: :desc)
459 460

          merge_requests.find do |merge_request|
461
            merge_request.commit_shas.include?(pipeline.sha)
462 463
          end
        end
464 465
    end

Douwe Maan's avatar
Douwe Maan committed
466
    def repo_url
Kamil Trzciński's avatar
Kamil Trzciński committed
467 468 469
      return unless token

      auth = "gitlab-ci-token:#{token}@"
470
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
471 472
        prefix + auth
      end
Douwe Maan's avatar
Douwe Maan committed
473 474 475
    end

    def allow_git_fetch
476
      project.build_allow_git_fetch
Douwe Maan's avatar
Douwe Maan committed
477 478 479
    end

    def update_coverage
480
      coverage = trace.extract_coverage(coverage_regex)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
481
      update(coverage: coverage) if coverage.present?
Douwe Maan's avatar
Douwe Maan committed
482 483
    end

484
    # rubocop: disable CodeReuse/ServiceClass
485
    def parse_trace_sections!
486
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
487
    end
488
    # rubocop: enable CodeReuse/ServiceClass
489

490 491
    def trace
      Gitlab::Ci::Trace.new(self)
492 493
    end

494
    def has_trace?
495
      trace.exist?
Tomasz Maczukin's avatar
Tomasz Maczukin committed
496 497
    end

498 499
    def has_job_artifacts?
      job_artifacts.any?
500 501
    end

Shinya Maeda's avatar
Shinya Maeda committed
502 503 504 505
    def has_old_trace?
      old_trace.present?
    end

506 507
    def trace=(data)
      raise NotImplementedError
Tomasz Maczukin's avatar
Tomasz Maczukin committed
508 509
    end

510 511
    def old_trace
      read_attribute(:trace)
512 513
    end

514
    def erase_old_trace!
515
      return unless has_old_trace?
Shinya Maeda's avatar
Shinya Maeda committed
516

517
      update_column(:trace, nil)
Douwe Maan's avatar
Douwe Maan committed
518 519
    end

520 521 522 523
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
524
    def valid_token?(token)
525
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
526 527
    end

528 529 530 531
    def has_tags?
      tag_list.any?
    end

532
    def any_runners_online?
533
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
534 535
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
536
    def stuck?
537 538 539
      pending? && !any_runners_online?
    end

540
    def execute_hooks
541
      return unless project
542

543
      build_data = Gitlab::DataBuilder::Build.build(self)
544 545
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
546 547
    end

548 549 550 551
    def browsable_artifacts?
      artifacts_metadata?
    end

552
    def artifacts_metadata_entry(path, **options)
553
      artifacts_metadata.open do |metadata_stream|
554
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
555
          metadata_stream,
556 557
          path,
          **options)
558

559 560
        metadata.to_entry
      end
561 562
    end

563 564 565 566
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
567 568
    end

569 570 571
    def erase(opts = {})
      return false unless erasable?

572 573
      job_artifacts.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
574 575 576 577 578
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
579
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
580 581 582 583 584 585
    end

    def erased?
      !self.erased_at.nil?
    end

586
    def artifacts_expired?
587
      artifacts_expire_at && artifacts_expire_at < Time.now
588 589
    end

590 591 592 593 594
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
595 596
      self.artifacts_expire_at =
        if value
597
          ChronicDuration.parse(value)&.seconds&.from_now
598
        end
599 600
    end

601
    def has_expiring_artifacts?
Z.J. van de Weg's avatar
Z.J. van de Weg committed
602
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
603 604
    end

605
    def keep_artifacts!
606
      self.update(artifacts_expire_at: nil)
607
      self.job_artifacts.update_all(expire_at: nil)
608 609
    end

610 611 612 613 614 615 616
    def artifacts_file_for_type(type)
      file = job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
      # TODO: to be removed once legacy artifacts is removed
      file ||= legacy_artifacts_file if type == :archive
      file
    end

617
    def coverage_regex
618
      super || project.try(:build_coverage_regex)
619 620
    end

621 622
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
623 624
    end

625 626
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
627 628
    end

629
    def user_variables
630
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
631
        break variables if user.blank?
632

633 634 635 636 637
        variables.append(key: 'GITLAB_USER_ID', value: user.id.to_s)
        variables.append(key: 'GITLAB_USER_EMAIL', value: user.email)
        variables.append(key: 'GITLAB_USER_LOGIN', value: user.username)
        variables.append(key: 'GITLAB_USER_NAME', value: user.name)
      end
638 639
    end

640 641 642
    def secret_group_variables
      return [] unless project.group

643
      project.group.ci_variables_for(ref, project)
644 645 646
    end

    def secret_project_variables(environment: persisted_environment)
647
      project.ci_variables_for(ref: ref, environment: environment)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
648 649
    end

650
    def steps
Tomasz Maczukin's avatar
Tomasz Maczukin committed
651 652
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
653 654 655
    end

    def image
656
      Gitlab::Ci::Build::Image.from_image(self)
657 658 659
    end

    def services
660
      Gitlab::Ci::Build::Image.from_services(self)
661 662 663
    end

    def cache
Matija Čupić's avatar
Matija Čupić committed
664 665 666 667
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
668
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
669
      end
Matija Čupić's avatar
Matija Čupić committed
670 671

      [cache]
672 673
    end

674
    def credentials
675
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
676 677
    end

678
    def dependencies
679 680
      return [] if empty_dependencies?

681 682
      depended_jobs = depends_on_builds

683
      return depended_jobs unless options[:dependencies].present?
684

685 686
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
687 688 689
      end
    end

690 691 692 693
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

Kamil Trzciński's avatar
Kamil Trzciński committed
694
    def has_valid_build_dependencies?
Kamil Trzciński's avatar
Kamil Trzciński committed
695
      return true if Feature.enabled?('ci_disable_validates_dependencies')
696

Kamil Trzciński's avatar
Kamil Trzciński committed
697
      dependencies.all?(&:valid_dependency?)
698 699
    end

Kamil Trzciński's avatar
Kamil Trzciński committed
700
    def valid_dependency?
Shinya Maeda's avatar
Shinya Maeda committed
701 702 703 704 705 706
      return false if artifacts_expired?
      return false if erased?

      true
    end

707 708 709 710 711 712 713 714
    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

715
    def supported_runner?(features)
716
      runner_required_feature_names.all? do |feature_name|
Kamil Trzciński's avatar
Kamil Trzciński committed
717
        features&.dig(feature_name)
718 719 720
      end
    end

721
    def publishes_artifacts_reports?
722
      options&.dig(:artifacts, :reports)&.any?
723 724
    end

725 726 727 728
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
729
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
Kamil Trzciński's avatar
Kamil Trzciński committed
730
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
731 732 733
      trace
    end

734
    def serializable_hash(options = {})
James Lopez's avatar
James Lopez committed
735
      super(options).merge(when: read_attribute(:when))
736 737
    end

738 739 740 741
    def has_terminal?
      running? && runner_session_url.present?
    end

742 743
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
744
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
745
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
746 747 748 749
        end
      end
    end

750 751 752 753 754 755
    # Virtual deployment status depending on the environment status.
    def deployment_status
      return nil unless starts_environment?

      if success?
        return successful_deployment_status
756
      elsif failed?
757 758 759 760 761 762
        return :failed
      end

      :creating
    end

763 764
    private

765 766 767 768 769 770 771
    def erase_old_artifacts!
      # TODO: To be removed once we get rid of
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

772
    def successful_deployment_status
773 774 775 776
      if deployment&.last?
        :last
      else
        :out_of_date
777 778 779
      end
    end

780 781 782 783
    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
784 785 786 787
        end
      end
    end

788 789 790 791 792
    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

793
    def update_artifacts_size
Kamil Trzcinski's avatar
Kamil Trzcinski committed
794
      self.artifacts_size = legacy_artifacts_file&.size
795 796
    end

797
    def erase_trace!
798
      trace.erase!
799 800 801
    end

    def update_erased!(user = nil)
802
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)