build.rb 28.0 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 53 54 55
    # 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.
    # (See more https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/22380)
56
    #
57 58 59 60 61
    # 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.
62
    def persisted_environment
63 64 65
      return unless has_environment?

      strong_memoize(:persisted_environment) do
66 67
        deployment&.environment ||
          Environment.find_by(name: expanded_environment_name, project: project)
68
      end
69 70
    end

71 72
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
73

D
Douwe Maan 已提交
74 75
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
76
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
77
    validates :ref, presence: true
D
Douwe Maan 已提交
78 79

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
80
    scope :ignore_failures, ->() { where(allow_failure: false) }
81
    scope :with_artifacts_archive, ->() do
82
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
83
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
84
    end
85

86 87 88 89
    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

90
    scope :with_archived_trace, ->() do
91
      with_existing_job_artifacts(Ci::JobArtifact.trace)
92 93
    end

94 95 96 97
    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 已提交
98
    scope :with_test_reports, ->() do
99 100
      with_existing_job_artifacts(Ci::JobArtifact.test_reports)
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
101 102
    end

103 104
    scope :eager_load_job_artifacts, -> { includes(:job_artifacts) }

105
    scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
106
    scope :with_archived_trace_stored_locally, -> { with_archived_trace.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
107 108
    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) }
109
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
110 111
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
112
    scope :ref_protected, -> { where(protected: true) }
113
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
114

115 116
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
117
        .where(taggable_type: CommitStatus.name)
118 119 120 121 122 123 124 125 126
        .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
127
        .where(taggable_type: CommitStatus.name)
128 129 130 131 132 133
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

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

134 135
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
136

D
Douwe Maan 已提交
137 138
    acts_as_taggable

K
Kamil Trzciński 已提交
139
    add_authentication_token_field :token, encrypted: true, fallback: true
140

L
Lin Jen-Shin 已提交
141
    before_save :update_artifacts_size, if: :artifacts_file_changed?
142
    before_save :ensure_token
143
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
144

145
    after_create unless: :importing? do |build|
146
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
147 148
    end

149 150
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
D
Douwe Maan 已提交
151 152

    class << self
153 154 155 156 157 158
      # 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 已提交
159 160 161 162
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

163
      def retry(build, current_user)
164
        # rubocop: disable CodeReuse/ServiceClass
165 166 167
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
168
        # rubocop: enable CodeReuse/ServiceClass
D
Douwe Maan 已提交
169 170 171
      end
    end

172
    state_machine :status do
173 174
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
175 176
      end

177 178 179 180 181 182 183 184
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

S
Shinya Maeda 已提交
185
      event :enqueue_scheduled do
186 187
        transition scheduled: :pending, if: ->(build) do
          build.scheduled_at && build.scheduled_at < Time.now
S
Shinya Maeda 已提交
188
        end
189 190 191
      end

      before_transition scheduled: any do |build|
S
Shinya Maeda 已提交
192 193 194 195
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
S
Shinya Maeda 已提交
196
        build.scheduled_at = build.options_scheduled_at
S
Shinya Maeda 已提交
197 198 199 200 201 202
      end

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

205 206
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
207
          BuildQueueWorker.perform_async(id)
208 209 210
        end
      end

211
      after_transition pending: :running do |build|
S
Shinya Maeda 已提交
212 213
        build.deployment&.run

214 215 216
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
217 218
      end

219
      after_transition any => [:success, :failed, :canceled] do |build|
220
        build.run_after_commit do
221
          BuildFinishedWorker.perform_async(id)
222
        end
D
Douwe Maan 已提交
223
      end
224

225
      after_transition any => [:success] do |build|
S
Shinya Maeda 已提交
226 227
        build.deployment&.succeed

228
        build.run_after_commit do
229
          BuildSuccessWorker.perform_async(id)
230
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
231 232
        end
      end
233

234
      before_transition any => [:failed] do |build|
235
        next unless build.project
236
        next unless build.deployment
S
Shinya Maeda 已提交
237

238 239 240 241 242 243 244
        begin
          build.deployment.drop!
        rescue => e
          Gitlab::Sentry.track_exception(e, extra: { build_id: build.id })
        end

        true
245 246 247 248
      end

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

250
        if build.retry_failure?
251 252 253 254 255
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
256 257
        end
      end
258

259
      after_transition pending: :running do |build|
260
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
261
      end
F
Francisco Javier López 已提交
262 263 264 265

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
S
Shinya Maeda 已提交
266 267 268 269

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

272
    def detailed_status(current_user)
273 274 275
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
276 277
    end

278
    def other_manual_actions
279
      pipeline.manual_actions.where.not(name: name)
280 281
    end

282 283
    def other_scheduled_actions
      pipeline.scheduled_actions.where.not(name: name)
284 285
    end

286 287 288 289 290
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

291 292 293 294 295 296 297
    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

298
    def playable?
299
      action? && !archived? && (manual? || scheduled? || retryable?)
K
Kamil Trzcinski 已提交
300 301
    end

S
Shinya Maeda 已提交
302
    def schedulable?
303
      self.when == 'delayed' && options[:start_in].present?
S
Shinya Maeda 已提交
304 305
    end

S
Shinya Maeda 已提交
306
    def options_scheduled_at
S
Shinya Maeda 已提交
307
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
K
Kamil Trzcinski 已提交
308 309
    end

310
    def action?
311
      %w[manual delayed].include?(self.when)
312 313
    end

314
    # rubocop: disable CodeReuse/ServiceClass
315
    def play(current_user)
316 317 318
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
319
    end
320
    # rubocop: enable CodeReuse/ServiceClass
321

K
Kamil Trzcinski 已提交
322
    def cancelable?
J
Jacopo 已提交
323
      active? || created?
K
Kamil Trzcinski 已提交
324 325
    end

K
Kamil Trzcinski 已提交
326
    def retryable?
327
      !archived? && (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
328
    end
329 330 331 332 333 334

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

    def retries_max
M
Markus Doits 已提交
335
      normalized_retry.fetch(:max, 0)
336
    end
K
Kamil Trzcinski 已提交
337

338
    def retry_when
M
Markus Doits 已提交
339
      normalized_retry.fetch(:when, ['always'])
340 341
    end

342 343 344
    def retry_failure?
      return false if retries_max.zero? || retries_count >= retries_max

345
      retry_when.include?('always') || retry_when.include?(failure_reason.to_s)
346
    end
K
Kamil Trzcinski 已提交
347

348 349
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
350 351
    end

352
    def expanded_environment_name
353 354 355
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
356 357
        ExpandVariables.expand(environment, simple_variables)
      end
358 359
    end

360
    def has_environment?
361
      environment.present?
362 363
    end

364
    def starts_environment?
365
      has_environment? && self.environment_action == 'start'
366 367 368
    end

    def stops_environment?
369
      has_environment? && self.environment_action == 'stop'
370 371 372
    end

    def environment_action
373
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
374 375
    end

S
Shinya Maeda 已提交
376 377 378 379
    def has_deployment?
      !!self.deployment
    end

380
    def outdated_deployment?
S
Shinya Maeda 已提交
381
      success? && !deployment.try(:last?)
382
    end
383

384 385
    def depends_on_builds
      # Get builds of the same type
386
      latest_builds = self.pipeline.builds.latest
387 388 389 390 391

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

392
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
393 394 395
      user == current_user
    end

S
Shinya Maeda 已提交
396 397 398 399
    def on_stop
      options&.dig(:environment, :on_stop)
    end

N
Nick Thomas 已提交
400 401 402 403 404 405
    # 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 已提交
406
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
407
    def ref_slug
V
vanadium23 已提交
408
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
409 410
    end

411
    ##
412
    # Variables in the environment name scope.
413
    #
414 415
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
416 417 418 419
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
420
        variables.concat(project.deployment_variables(environment: environment)) if environment
421 422
        variables.concat(yaml_variables)
        variables.concat(user_variables)
423 424
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
425 426 427 428
        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
429
    end
430

431 432 433 434
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
435 436 437
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
438 439 440 441 442 443
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
444 445 446
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
447 448 449 450
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

451 452 453 454 455
    ##
    # 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
456
      scoped_variables.to_hash
457 458
    end

459 460 461 462
    def features
      { trace_sections: true }
    end

463
    def merge_request
Z
Z.J. van de Weg 已提交
464
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
465

466 467
      @merge_request ||=
        begin
468
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
469 470
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
471
            .reorder(iid: :desc)
472 473

          merge_requests.find do |merge_request|
474
            merge_request.commit_shas.include?(pipeline.sha)
475 476
          end
        end
477 478
    end

D
Douwe Maan 已提交
479
    def repo_url
K
Kamil Trzciński 已提交
480 481 482
      return unless token

      auth = "gitlab-ci-token:#{token}@"
483
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
484 485
        prefix + auth
      end
D
Douwe Maan 已提交
486 487 488
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
489
      project.build_allow_git_fetch
D
Douwe Maan 已提交
490 491 492
    end

    def update_coverage
493
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
494
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
495 496
    end

497
    # rubocop: disable CodeReuse/ServiceClass
498
    def parse_trace_sections!
499
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
500
    end
501
    # rubocop: enable CodeReuse/ServiceClass
502

503 504
    def trace
      Gitlab::Ci::Trace.new(self)
505 506
    end

507
    def has_trace?
508
      trace.exist?
T
Tomasz Maczukin 已提交
509 510
    end

511 512
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
513 514
    end

S
Shinya Maeda 已提交
515 516 517 518
    def has_old_trace?
      old_trace.present?
    end

519 520
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
521 522
    end

523 524
    def old_trace
      read_attribute(:trace)
525 526
    end

527
    def erase_old_trace!
528
      return unless has_old_trace?
S
Shinya Maeda 已提交
529

530
      update_column(:trace, nil)
D
Douwe Maan 已提交
531 532
    end

533 534 535 536
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
537
    def valid_token?(token)
538
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
539 540
    end

541 542 543 544
    def has_tags?
      tag_list.any?
    end

545
    def any_runners_online?
546
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
547 548
    end

K
Kamil Trzcinski 已提交
549
    def stuck?
550 551 552
      pending? && !any_runners_online?
    end

553
    def execute_hooks
554
      return unless project
555

556
      build_data = Gitlab::DataBuilder::Build.build(self)
557 558
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
559 560
    end

561 562 563 564
    def browsable_artifacts?
      artifacts_metadata?
    end

565
    def artifacts_metadata_entry(path, **options)
566
      artifacts_metadata.open do |metadata_stream|
567
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
568
          metadata_stream,
569 570
          path,
          **options)
571

572 573
        metadata.to_entry
      end
574 575
    end

576 577 578 579
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
S
Shinya Maeda 已提交
580 581
    end

582 583 584
    def erase(opts = {})
      return false unless erasable?

585 586
      job_artifacts.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
587 588 589 590 591
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
592
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
593 594 595 596 597 598
    end

    def erased?
      !self.erased_at.nil?
    end

599
    def artifacts_expired?
600
      artifacts_expire_at && artifacts_expire_at < Time.now
601 602
    end

603 604 605 606 607
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
608 609
      self.artifacts_expire_at =
        if value
610
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
611
        end
612 613
    end

614
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
615
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
616 617
    end

618
    def keep_artifacts!
619
      self.update(artifacts_expire_at: nil)
620
      self.job_artifacts.update_all(expire_at: nil)
621 622
    end

623 624 625 626 627 628 629
    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

630
    def coverage_regex
631
      super || project.try(:build_coverage_regex)
632 633
    end

634
    def user_variables
635
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
636
        break variables if user.blank?
637

638 639 640 641 642
        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
643 644
    end

645 646 647
    def secret_group_variables
      return [] unless project.group

648
      project.group.ci_variables_for(git_ref, project)
649 650 651
    end

    def secret_project_variables(environment: persisted_environment)
652
      project.ci_variables_for(ref: git_ref, environment: environment)
L
Lin Jen-Shin 已提交
653 654
    end

655
    def steps
T
Tomasz Maczukin 已提交
656 657
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
658 659 660
    end

    def image
661
      Gitlab::Ci::Build::Image.from_image(self)
662 663 664
    end

    def services
665
      Gitlab::Ci::Build::Image.from_services(self)
666 667 668
    end

    def cache
M
Matija Čupić 已提交
669 670 671 672
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
673
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
674
      end
M
Matija Čupić 已提交
675 676

      [cache]
677 678
    end

679
    def credentials
680
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
681 682
    end

T
Tomasz Maczukin 已提交
683
    def dependencies
684 685
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
686 687
      depended_jobs = depends_on_builds

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

690 691
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
692 693 694
      end
    end

695 696 697 698
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
699
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
700
      return true if Feature.enabled?('ci_disable_validates_dependencies')
701

K
Kamil Trzciński 已提交
702
      dependencies.all?(&:valid_dependency?)
703 704
    end

K
Kamil Trzciński 已提交
705
    def valid_dependency?
S
Shinya Maeda 已提交
706 707 708 709 710 711
      return false if artifacts_expired?
      return false if erased?

      true
    end

712 713 714 715 716 717 718 719
    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

720
    def supported_runner?(features)
721
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
722
        features&.dig(feature_name)
723 724 725
      end
    end

726
    def publishes_artifacts_reports?
727
      options&.dig(:artifacts, :reports)&.any?
728 729
    end

730 731 732 733
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
734
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
K
Kamil Trzciński 已提交
735
      Gitlab::Ci::MaskSecret.mask!(trace, token) if token
736 737 738
      trace
    end

739
    def serializable_hash(options = {})
J
James Lopez 已提交
740
      super(options).merge(when: read_attribute(:when))
741 742
    end

F
Francisco Javier López 已提交
743 744 745 746
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
747 748
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
749
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
G
Gilbert Roulot 已提交
750
          Gitlab::Ci::Parsers.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
751 752 753 754
        end
      end
    end

755 756 757 758 759 760
    # 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 已提交
761
      elsif failed?
762 763 764 765 766 767
        return :failed
      end

      :creating
    end

768 769
    private

770 771 772 773 774 775 776
    def erase_old_artifacts!
      # TODO: To be removed once we get rid of
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

777
    def successful_deployment_status
S
Shinya Maeda 已提交
778 779 780 781
      if deployment&.last?
        :last
      else
        :out_of_date
782 783 784
      end
    end

785 786 787 788
    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 已提交
789 790 791 792
        end
      end
    end

793 794 795 796 797
    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 已提交
798
    def update_artifacts_size
K
Kamil Trzcinski 已提交
799
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
800 801
    end

802
    def erase_trace!
803
      trace.erase!
804 805 806
    end

    def update_erased!(user = nil)
807
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
808 809
    end

810
    def unscoped_project
K
Kamil Trzciński 已提交
811
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
812 813
    end

814 815
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

816 817
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
818
        break variables unless persisted?
819 820

        variables
821
          .concat(pipeline.persisted_variables)
822
          .append(key: 'CI_JOB_ID', value: id.to_s)
K
Kamil Trzciński 已提交
823
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
K
Kamil Trzciński 已提交
824
          .append(key: 'CI_JOB_TOKEN', value: token.to_s, public: false)
825
          .append(key: 'CI_BUILD_ID', value: id.to_s)
K
Kamil Trzciński 已提交
826
          .append(key: 'CI_BUILD_TOKEN', value: token.to_s, public: false)
827
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
K
Kamil Trzciński 已提交
828 829
          .append(key: 'CI_REGISTRY_PASSWORD', value: token.to_s, public: false)
          .append(key: 'CI_REPOSITORY_URL', value: repo_url.to_s, public: false)
830
          .concat(deploy_token_variables)
831 832 833
      end
    end

M
Matija Čupić 已提交
834
    def predefined_variables # rubocop:disable Metrics/AbcSize
835 836 837
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
838
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
839 840
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
K
Kamil Trzciński 已提交
841 842 843
        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)
844
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
845 846 847
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
848
        variables.append(key: 'CI_COMMIT_SHORT_SHA', value: short_sha)
849
        variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
850 851 852 853 854
        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?
855
        variables.append(key: "CI_NODE_INDEX", value: self.options[:instance].to_s) if self.options&.include?(:instance)
856
        variables.append(key: "CI_NODE_TOTAL", value: (self.options&.dig(:parallel) || 1).to_s)
857 858
        variables.concat(legacy_variables)
      end
859 860 861
    end

    def legacy_variables
862 863 864 865 866 867 868 869 870 871 872
      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
873
    end
874

875 876
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
877
        break variables unless persisted? && persisted_environment.present?
878 879 880 881 882 883 884 885 886 887

        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

888 889
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
890 891
        break variables unless gitlab_deploy_token

892
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
893
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
894 895 896
      end
    end

897
    def environment_url
898
      options&.dig(:environment, :url) || persisted_environment&.external_url
899 900
    end

901 902 903 904 905
    # 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 已提交
906
    def normalized_retry
907 908 909 910 911
      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 已提交
912 913
    end

914 915
    def build_attributes_from_config
      return {} unless pipeline.config_processor
916

917 918
      pipeline.config_processor.build_attributes(name)
    end
919

920 921 922
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
923

924 925
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
926
    end
927

928 929 930 931 932 933
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
934
    end
D
Douwe Maan 已提交
935 936
  end
end