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

D
Douwe Maan 已提交
3
module Ci
K
Kamil Trzcinski 已提交
4
  class Build < CommitStatus
Z
Zeger-Jan van de Weg 已提交
5
    prepend ArtifactMigratable
6
    include Ci::Processable
7
    include Ci::Metadatable
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 IgnorableColumn
14
    include Gitlab::Utils::StrongMemoize
S
Shinya Maeda 已提交
15
    include Deployable
16
    include HasRef
17

18 19 20 21
    BuildArchivedError = Class.new(StandardError)

    ignore_column :commands

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 28 29 30
    RUNNER_FEATURES = {
      upload_multiple_artifacts: -> (build) { build.publishes_artifacts_reports? }
    }.freeze

S
Shinya Maeda 已提交
31
    has_one :deployment, as: :deployable, class_name: 'Deployment'
32
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
33
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
34

35
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
S
Shinya Maeda 已提交
36 37 38 39

    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
40

F
Francisco Javier López 已提交
41 42 43 44 45 46
    has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build

    accepts_nested_attributes_for :runner_session

    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
47
    delegate :gitlab_deploy_token, to: :project
48
    delegate :trigger_short_token, to: :trigger_request, allow_nil: true
T
Tomasz Maczukin 已提交
49

50 51 52
    ##
    # The "environment" field for builds is a String, and is the unexpanded name!
    #
53
    def persisted_environment
54 55 56 57 58
      return unless has_environment?

      strong_memoize(:persisted_environment) do
        Environment.find_by(name: expanded_environment_name, project: project)
      end
59 60
    end

61 62
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
63

D
Douwe Maan 已提交
64 65
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
66
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
67
    validates :ref, presence: true
D
Douwe Maan 已提交
68 69

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
70
    scope :ignore_failures, ->() { where(allow_failure: false) }
71
    scope :with_artifacts_archive, ->() do
72
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
73
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
74
    end
75

76 77 78 79
    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

80
    scope :with_archived_trace, ->() do
81
      with_existing_job_artifacts(Ci::JobArtifact.trace)
82 83
    end

84 85 86 87
    scope :without_archived_trace, ->() do
      where('NOT EXISTS (?)', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').trace)
    end

S
Shinya Maeda 已提交
88
    scope :with_test_reports, ->() do
89 90
      with_existing_job_artifacts(Ci::JobArtifact.test_reports)
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
91 92
    end

93 94
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

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

105 106
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
107
        .where(taggable_type: CommitStatus.name)
108 109 110 111 112 113 114 115 116
        .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
117
        .where(taggable_type: CommitStatus.name)
118 119 120 121 122 123
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

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

124 125
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
126

D
Douwe Maan 已提交
127 128
    acts_as_taggable

K
Kamil Trzciński 已提交
129
    add_authentication_token_field :token, encrypted: true, fallback: true
130

L
Lin Jen-Shin 已提交
131
    before_save :update_artifacts_size, if: :artifacts_file_changed?
132
    before_save :ensure_token
133
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
134

135
    after_create unless: :importing? do |build|
136
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
137 138
    end

139 140
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
D
Douwe Maan 已提交
141 142

    class << self
143 144 145 146 147 148
      # 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 已提交
149 150 151 152
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

153
      def retry(build, current_user)
154
        # rubocop: disable CodeReuse/ServiceClass
155 156 157
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
158
        # rubocop: enable CodeReuse/ServiceClass
D
Douwe Maan 已提交
159 160 161
      end
    end

162
    state_machine :status do
163 164
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
165 166
      end

167 168 169 170 171 172 173 174
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

S
Shinya Maeda 已提交
175
      event :enqueue_scheduled do
176 177
        transition scheduled: :pending, if: ->(build) do
          build.scheduled_at && build.scheduled_at < Time.now
S
Shinya Maeda 已提交
178
        end
179 180 181
      end

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
182 183 184 185
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
186
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
187 188 189 190 191 192
      end

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

195 196
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
197
          BuildQueueWorker.perform_async(id)
198 199 200
        end
      end

201
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
202 203
        build.deployment&.run

204 205 206
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
207 208
      end

209
      after_transition any => [:success, :failed, :canceled] do |build|
210
        build.run_after_commit do
211
          BuildFinishedWorker.perform_async(id)
212
        end
D
Douwe Maan 已提交
213
      end
214

215
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
216 217
        build.deployment&.succeed

218
        build.run_after_commit do
219
          BuildSuccessWorker.perform_async(id)
220
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
221 222
        end
      end
223

224
      before_transition any => [:failed] do |build|
225
        next unless build.project
226
        next unless build.deployment
S
Shinya Maeda 已提交
227

228 229 230 231 232 233 234
        begin
          build.deployment.drop!
        rescue => e
          Gitlab::Sentry.track_exception(e, extra: { build_id: build.id })
        end

        true
235 236 237 238
      end

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

240
        if build.retry_failure?
241 242 243 244 245
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
246 247
        end
      end
248

249
      after_transition pending: :running do |build|
250
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
251
      end
F
Francisco Javier López 已提交
252 253 254 255

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
256 257 258 259

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

262
    def detailed_status(current_user)
263 264 265
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
266 267
    end

268
    def other_manual_actions
269
      pipeline.manual_actions.where.not(name: name)
270 271
    end

272 273
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
274 275
    end

276 277 278 279 280
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

281 282 283 284 285 286 287
    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

288
    def playable?
289
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
290 291
    end

S
Shinya Maeda 已提交
292
    def schedulable?
293
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
294 295
    end

S
Shinya Maeda 已提交
296
    def options_scheduled_at
S
Shinya Maeda 已提交
297
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
298 299
    end

300
    def action?
301
      %w[manual delayed].include?(self.when)
302 303
    end

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

K
Kamil Trzcinski 已提交
312
    def cancelable?
J
Jacopo 已提交
313
      active? || created?
K
Kamil Trzcinski 已提交
314 315
    end

K
Kamil Trzcinski 已提交
316
    def retryable?
317
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
318
    end
319 320 321 322 323 324

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

    def retries_max
M
Markus Doits 已提交
325
      normalized_retry.fetch(:max, 0)
326
    end
K
Kamil Trzcinski 已提交
327

328
    def retry_when
M
Markus Doits 已提交
329
      normalized_retry.fetch(:when, ['always'])
330 331
    end

332 333 334
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

335
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
336
    end
K
Kamil Trzcinski 已提交
337

338 339
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
340 341
    end

342
    def expanded_environment_name
343 344 345
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
346 347
        ExpandVariables.expand(environment, simple_variables)
      end
348 349
    end

350
    def has_environment?
351
      environment.present?
352 353
    end

354
    def starts_environment?
355
      has_environment? && self.environment_action == 'start'
356 357 358
    end

    def stops_environment?
359
      has_environment? && self.environment_action == 'stop'
360 361 362
    end

    def environment_action
363
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
364 365
    end

S
Shinya Maeda 已提交
366 367 368 369
    def has_deployment?
      !!self.deployment
    end

370
    def outdated_deployment?
S
Shinya Maeda 已提交
371
      success? && !deployment.try(:last?)
372
    end
373

374 375
    def depends_on_builds
      # Get builds of the same type
376
      latest_builds = self.pipeline.builds.latest
377 378 379 380 381

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

382
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
383 384 385
      user == current_user
    end

S
Shinya Maeda 已提交
386 387 388 389
    def on_stop
      options&.dig(:environment, :on_stop)
    end

N
Nick Thomas 已提交
390 391 392 393 394 395
    # 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
S
Shinya Maeda 已提交
396
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
397
    def ref_slug
V
vanadium23 已提交
398
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
399 400
    end

401
    ##
402
    # Variables in the environment name scope.
403
    #
404 405
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
406 407 408 409
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
410
        variables.concat(project.deployment_variables(environment: environment)) if environment
411 412
        variables.concat(yaml_variables)
        variables.concat(user_variables)
413 414
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
415 416 417 418
        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
419
    end
420

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

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

441 442 443 444 445
    ##
    # 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
446
      scoped_variables.to_hash
447 448
    end

449 450 451 452
    def features
      { trace_sections: true }
    end

453
    def merge_request
Z
Z.J. van de Weg 已提交
454
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
455

456 457
      @merge_request ||=
        begin
458
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
459 460
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
461
            .reorder(iid: :desc)
462 463

          merge_requests.find do |merge_request|
464
            merge_request.commit_shas.include?(pipeline.sha)
465 466
          end
        end
467 468
    end

D
Douwe Maan 已提交
469
    def repo_url
K
Kamil Trzciński 已提交
470 471 472
      return unless token

      auth = "gitlab-ci-token:#{token}@"
473
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
474 475
        prefix + auth
      end
D
Douwe Maan 已提交
476 477 478
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
479
      project.build_allow_git_fetch
D
Douwe Maan 已提交
480 481 482
    end

    def update_coverage
483
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
484
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
485 486
    end

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

493 494
    def trace
      Gitlab::Ci::Trace.new(self)
495 496
    end

497
    def has_trace?
498
      trace.exist?
T
Tomasz Maczukin 已提交
499 500
    end

501 502
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
503 504
    end

S
Shinya Maeda 已提交
505 506 507 508
    def has_old_trace?
      old_trace.present?
    end

509 510
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
511 512
    end

513 514
    def old_trace
      read_attribute(:trace)
515 516
    end

517
    def erase_old_trace!
518
      return unless has_old_trace?
S
Shinya Maeda 已提交
519

520
      update_column(:trace, nil)
D
Douwe Maan 已提交
521 522
    end

523 524 525 526
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
527
    def valid_token?(token)
528
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
529 530
    end

531 532 533 534
    def has_tags?
      tag_list.any?
    end

535
    def any_runners_online?
536
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
537 538
    end

K
Kamil Trzcinski 已提交
539
    def stuck?
540 541 542
      pending? && !any_runners_online?
    end

543
    def execute_hooks
544
      return unless project
545

546
      build_data = Gitlab::DataBuilder::Build.build(self)
547 548
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
549 550
    end

551 552 553 554
    def browsable_artifacts?
      artifacts_metadata?
    end

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

562 563
        metadata.to_entry
      end
564 565
    end

566 567 568 569
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
S
Shinya Maeda 已提交
570 571
    end

572 573 574
    def erase(opts = {})
      return false unless erasable?

575 576
      job_artifacts.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
577 578 579 580 581
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
582
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
583 584 585 586 587 588
    end

    def erased?
      !self.erased_at.nil?
    end

589
    def artifacts_expired?
590
      artifacts_expire_at && artifacts_expire_at < Time.now
591 592
    end

593 594 595 596 597
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
598 599
      self.artifacts_expire_at =
        if value
600
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
601
        end
602 603
    end

604
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
605
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
606 607
    end

608
    def keep_artifacts!
609
      self.update(artifacts_expire_at: nil)
610
      self.job_artifacts.update_all(expire_at: nil)
611 612
    end

613 614 615 616 617 618 619
    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

620
    def coverage_regex
621
      super || project.try(:build_coverage_regex)
622 623
    end

624
    def user_variables
625
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
626
        break variables if user.blank?
627

628 629 630 631 632
        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
633 634
    end

635 636 637
    def secret_group_variables
      return [] unless project.group

638
      project.group.ci_variables_for(git_ref, project)
639 640 641
    end

    def secret_project_variables(environment: persisted_environment)
642
      project.ci_variables_for(ref: git_ref, environment: environment)
L
Lin Jen-Shin 已提交
643 644
    end

645
    def steps
T
Tomasz Maczukin 已提交
646 647
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
648 649 650
    end

    def image
651
      Gitlab::Ci::Build::Image.from_image(self)
652 653 654
    end

    def services
655
      Gitlab::Ci::Build::Image.from_services(self)
656 657 658
    end

    def cache
M
Matija Čupić 已提交
659 660 661 662
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
663
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
664
      end
M
Matija Čupić 已提交
665 666

      [cache]
667 668
    end

669
    def credentials
670
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
671 672
    end

T
Tomasz Maczukin 已提交
673
    def dependencies
674 675
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
676 677
      depended_jobs = depends_on_builds

678
      return depended_jobs unless options[:dependencies].present?
T
Tomasz Maczukin 已提交
679

680 681
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
682 683 684
      end
    end

685 686 687 688
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
689
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
690
      return true if Feature.enabled?('ci_disable_validates_dependencies')
691

K
Kamil Trzciński 已提交
692
      dependencies.all?(&:valid_dependency?)
693 694
    end

K
Kamil Trzciński 已提交
695
    def valid_dependency?
S
Shinya Maeda 已提交
696 697 698 699 700 701
      return false if artifacts_expired?
      return false if erased?

      true
    end

702 703 704 705 706 707 708 709
    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

710
    def supported_runner?(features)
711
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
712
        features&.dig(feature_name)
713 714 715
      end
    end

716
    def publishes_artifacts_reports?
717
      options&.dig(:artifacts, :reports)&.any?
718 719
    end

720 721 722 723
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
724
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
725
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
726 727 728
      trace
    end

729
    def serializable_hash(options = {})
J
James Lopez 已提交
730
      super(options).merge(when: read_attribute(:when))
731 732
    end

F
Francisco Javier López 已提交
733 734 735 736
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
737 738
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
739
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
740
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
741 742 743 744
        end
      end
    end

745 746 747 748 749 750
    # Virtual deployment status depending on the environment status.
    def deployment_status
      return nil unless starts_environment?

      if success?
        return successful_deployment_status
S
Shinya Maeda 已提交
751
      elsif failed?
752 753 754 755 756 757
        return :failed
      end

      :creating
    end

758 759
    private

760 761 762 763 764 765 766
    def erase_old_artifacts!
      # TODO: To be removed once we get rid of
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

767
    def successful_deployment_status
S
Shinya Maeda 已提交
768 769 770 771
      if deployment&.last?
        :last
      else
        :out_of_date
772 773 774
      end
    end

775 776 777 778
    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 已提交
779 780 781 782
        end
      end
    end

783 784 785 786 787
    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

L
Lin Jen-Shin 已提交
788
    def update_artifacts_size
K
Kamil Trzcinski 已提交
789
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
790 791
    end

792
    def erase_trace!
793
      trace.erase!
794 795 796
    end

    def update_erased!(user = nil)
797
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
798 799
    end

800
    def unscoped_project
K
Kamil Trzciński 已提交
801
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
802 803
    end

804 805
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

806 807
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
808
        break variables unless persisted?
809 810

        variables
811
          .concat(pipeline.persisted_variables)
812
          .append(key: 'CI_JOB_ID', value: id.to_s)
K
Kamil Trzciński 已提交
813
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
K
Kamil Trzciński 已提交
814
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false)
815
          .append(key: 'CI_BUILD_ID', value: id.to_s)
K
Kamil Trzciński 已提交
816
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false)
817
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
K
Kamil Trzciński 已提交
818 819
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false)
          .append(key: 'CI_REPOSITORY_URL', value: repo_url.to_s, public: false)
820
          .concat(deploy_token_variables)
821 822 823
      end
    end

M
Matija Čupić 已提交
824
    def predefined_variables # rubocop:disable Metrics/AbcSize
825 826 827
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
828
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
829 830
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
K
Kamil Trzciński 已提交
831 832 833
        variables.append(key: 'CI_SERVER_VERSION_MAJOR', value: Gitlab.version_info.major.to_s)
        variables.append(key: 'CI_SERVER_VERSION_MINOR', value: Gitlab.version_info.minor.to_s)
        variables.append(key: 'CI_SERVER_VERSION_PATCH', value: Gitlab.version_info.patch.to_s)
834
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
835 836 837
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
838
        variables.append(key: 'CI_COMMIT_SHORT_SHA', value: short_sha)
839
        variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
840 841 842 843 844
        variables.append(key: 'CI_COMMIT_REF_NAME', value: ref)
        variables.append(key: 'CI_COMMIT_REF_SLUG', value: ref_slug)
        variables.append(key: "CI_COMMIT_TAG", value: ref) if tag?
        variables.append(key: "CI_PIPELINE_TRIGGERED", value: 'true') if trigger_request
        variables.append(key: "CI_JOB_MANUAL", value: 'true') if action?
845
        variables.append(key: "CI_NODE_INDEX", value: self.options[:instance].to_s) if self.options&.include?(:instance)
846
        variables.append(key: "CI_NODE_TOTAL", value: (self.options&.dig(:parallel) || 1).to_s)
847 848
        variables.concat(legacy_variables)
      end
849 850 851
    end

    def legacy_variables
852 853 854 855 856 857 858 859 860 861 862
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI_BUILD_REF', value: sha)
        variables.append(key: 'CI_BUILD_BEFORE_SHA', value: before_sha)
        variables.append(key: 'CI_BUILD_REF_NAME', value: ref)
        variables.append(key: 'CI_BUILD_REF_SLUG', value: ref_slug)
        variables.append(key: 'CI_BUILD_NAME', value: name)
        variables.append(key: 'CI_BUILD_STAGE', value: stage)
        variables.append(key: "CI_BUILD_TAG", value: ref) if tag?
        variables.append(key: "CI_BUILD_TRIGGERED", value: 'true') if trigger_request
        variables.append(key: "CI_BUILD_MANUAL", value: 'true') if action?
      end
863
    end
864

865 866
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
867
        break variables unless persisted? && persisted_environment.present?
868 869 870 871 872 873 874 875 876 877

        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

878 879
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
880 881
        break variables unless gitlab_deploy_token

882
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
883
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
884 885 886
      end
    end

887
    def environment_url
888
      options&.dig(:environment, :url) || persisted_environment&.external_url
889 890
    end

891 892 893 894 895
    # The format of the retry option changed in GitLab 11.5: Before it was
    # integer only, after it is a hash. New builds are created with the new
    # format, but builds created before GitLab 11.5 and saved in database still
    # have the old integer only format. This method returns the retry option
    # normalized as a hash in 11.5+ format.
M
Markus Doits 已提交
896
    def normalized_retry
897 898 899 900 901
      strong_memoize(:normalized_retry) do
        value = options&.dig(:retry)
        value = value.is_a?(Integer) ? { max: value } : value.to_h
        value.with_indifferent_access
      end
M
Markus Doits 已提交
902 903
    end

904 905
    def build_attributes_from_config
      return {} unless pipeline.config_processor
906

907 908
      pipeline.config_processor.build_attributes(name)
    end
909

910 911 912
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
913

914 915
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
916
    end
917

918 919 920 921 922 923
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
924
    end
D
Douwe Maan 已提交
925 926
  end
end