build.rb 24.2 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 TokenAuthenticatable
7
    include AfterCommitQueue
8
    include ObjectStorage::BackgroundMove
R
Rémy Coutable 已提交
9
    include Presentable
S
Shinya Maeda 已提交
10
    include Importable
11
    include Gitlab::Utils::StrongMemoize
12

13
    belongs_to :project, inverse_of: :builds
14 15
    belongs_to :runner
    belongs_to :trigger_request
16
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
17

18
    has_many :deployments, as: :deployable
19

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

24
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
25
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
26
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
27

28
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
S
Shinya Maeda 已提交
29 30 31 32

    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
33

34
    has_one :metadata, class_name: 'Ci::BuildMetadata'
F
Francisco Javier López 已提交
35 36 37 38
    has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build

    accepts_nested_attributes_for :runner_session

T
Tomasz Maczukin 已提交
39
    delegate :timeout, to: :metadata, prefix: true, allow_nil: true
F
Francisco Javier López 已提交
40 41
    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
42
    delegate :gitlab_deploy_token, to: :project
43
    delegate :trigger_short_token, to: :trigger_request, allow_nil: true
T
Tomasz Maczukin 已提交
44

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

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

56 57
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
58

D
Douwe Maan 已提交
59 60
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
61
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
62
    validates :ref, presence: true
D
Douwe Maan 已提交
63 64

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

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

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

79 80 81 82
    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 已提交
83
    scope :with_test_reports, ->() do
84 85
      with_existing_job_artifacts(Ci::JobArtifact.test_reports)
        .eager_load_job_artifacts
S
Shinya Maeda 已提交
86 87
    end

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

90
    scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
91
    scope :with_archived_trace_stored_locally, -> { with_archived_trace.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
92 93
    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) }
94
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
95
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
        .where(taggable_type: CommitStatus)
        .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
        .where(taggable_type: CommitStatus)
        .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
K
Kamil Trzcinski 已提交
120

D
Douwe Maan 已提交
121 122
    acts_as_taggable

123 124
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
125
    before_save :update_artifacts_size, if: :artifacts_file_changed?
126
    before_save :ensure_token
127
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
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?
D
Douwe Maan 已提交
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

D
Douwe Maan 已提交
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
D
Douwe Maan 已提交
154 155 156
      end
    end

157
    state_machine :status do
158 159
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
160 161
      end

162 163
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
164
          BuildQueueWorker.perform_async(id)
165 166 167
        end
      end

168
      after_transition pending: :running do |build|
169 170 171
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
172 173
      end

174
      after_transition any => [:success, :failed, :canceled] do |build|
175
        build.run_after_commit do
176
          BuildFinishedWorker.perform_async(id)
177
        end
D
Douwe Maan 已提交
178
      end
179

180
      after_transition any => [:success] do |build|
181 182
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
183
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
184 185
        end
      end
186

187
      before_transition any => [:failed] do |build|
188
        next unless build.project
189
        next if build.retries_max.zero?
190

191
        if build.retries_count < build.retries_max
192 193 194 195 196
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
197 198
        end
      end
199

200
      after_transition pending: :running do |build|
201
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
202
      end
F
Francisco Javier López 已提交
203 204 205 206

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
D
Douwe Maan 已提交
207 208
    end

209
    def ensure_metadata
T
Tomasz Maczukin 已提交
210
      metadata || build_metadata(project: project)
D
Douwe Maan 已提交
211 212
    end

213
    def detailed_status(current_user)
214 215 216
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
217 218
    end

219
    def other_actions
220
      pipeline.manual_actions.where.not(name: name)
221 222
    end

223 224 225 226 227
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

228
    def playable?
229
      action? && (manual? || retryable?)
K
Kamil Trzcinski 已提交
230 231
    end

232
    def action?
233 234 235
      self.when == 'manual'
    end

236
    # rubocop: disable CodeReuse/ServiceClass
237
    def play(current_user)
238 239 240
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
241
    end
242
    # rubocop: enable CodeReuse/ServiceClass
243

K
Kamil Trzcinski 已提交
244
    def cancelable?
J
Jacopo 已提交
245
      active? || created?
K
Kamil Trzcinski 已提交
246 247
    end

K
Kamil Trzcinski 已提交
248
    def retryable?
249
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
250
    end
251 252 253 254 255 256 257 258

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

    def retries_max
      self.options.fetch(:retry, 0).to_i
    end
K
Kamil Trzcinski 已提交
259

260 261
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
262 263
    end

264
    def expanded_environment_name
265 266 267
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
268 269
        ExpandVariables.expand(environment, simple_variables)
      end
270 271
    end

272
    def has_environment?
273
      environment.present?
274 275
    end

276
    def starts_environment?
277
      has_environment? && self.environment_action == 'start'
278 279 280
    end

    def stops_environment?
281
      has_environment? && self.environment_action == 'stop'
282 283 284
    end

    def environment_action
285
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
286 287 288 289
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
290
    end
291

292 293
    def depends_on_builds
      # Get builds of the same type
294
      latest_builds = self.pipeline.builds.latest
295 296 297 298 299

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

300
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
301 302 303
      user == current_user
    end

N
Nick Thomas 已提交
304 305 306 307 308 309
    # 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 已提交
310
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
311
    def ref_slug
V
vanadium23 已提交
312
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
313 314
    end

315
    ##
316
    # Variables in the environment name scope.
317
    #
318 319
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
320 321 322 323
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
324
        variables.concat(project.deployment_variables(environment: environment)) if environment
325 326
        variables.concat(yaml_variables)
        variables.concat(user_variables)
327 328
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
329 330 331 332
        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
333
    end
334

335 336 337 338
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
339 340 341
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
342 343 344 345 346 347
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
348 349 350
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
351 352 353 354
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

355 356 357 358 359
    ##
    # 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
360
      scoped_variables.to_hash
361 362
    end

363 364 365 366
    def features
      { trace_sections: true }
    end

367
    def merge_request
Z
Z.J. van de Weg 已提交
368
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
369

370 371
      @merge_request ||=
        begin
372
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
373 374
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
375
            .reorder(iid: :desc)
376 377

          merge_requests.find do |merge_request|
378
            merge_request.commit_shas.include?(pipeline.sha)
379 380
          end
        end
381 382
    end

D
Douwe Maan 已提交
383
    def repo_url
K
Kamil Trzcinski 已提交
384
      auth = "gitlab-ci-token:#{ensure_token!}@"
385
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
386 387
        prefix + auth
      end
D
Douwe Maan 已提交
388 389 390
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
391
      project.build_allow_git_fetch
D
Douwe Maan 已提交
392 393 394
    end

    def update_coverage
395
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
396
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
397 398
    end

399
    # rubocop: disable CodeReuse/ServiceClass
400
    def parse_trace_sections!
401
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
402
    end
403
    # rubocop: enable CodeReuse/ServiceClass
404

405 406
    def trace
      Gitlab::Ci::Trace.new(self)
407 408
    end

409
    def has_trace?
410
      trace.exist?
T
Tomasz Maczukin 已提交
411 412
    end

413 414
    def has_job_artifacts?
      job_artifacts.any?
S
Shinya Maeda 已提交
415 416
    end

S
Shinya Maeda 已提交
417 418 419 420
    def has_old_trace?
      old_trace.present?
    end

421 422
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
423 424
    end

425 426
    def old_trace
      read_attribute(:trace)
427 428
    end

429
    def erase_old_trace!
430
      return unless has_old_trace?
S
Shinya Maeda 已提交
431

432
      update_column(:trace, nil)
D
Douwe Maan 已提交
433 434
    end

435 436 437 438
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
439
    def valid_token?(token)
440
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
441 442
    end

443 444 445 446
    def has_tags?
      tag_list.any?
    end

447
    def any_runners_online?
448
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
449 450
    end

K
Kamil Trzcinski 已提交
451
    def stuck?
452 453 454
      pending? && !any_runners_online?
    end

455
    def execute_hooks
456
      return unless project
457

458
      build_data = Gitlab::DataBuilder::Build.build(self)
459 460
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
461 462
    end

463 464 465 466
    def browsable_artifacts?
      artifacts_metadata?
    end

467
    def artifacts_metadata_entry(path, **options)
468
      artifacts_metadata.open do |metadata_stream|
469
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
470
          metadata_stream,
471 472
          path,
          **options)
473

474 475
        metadata.to_entry
      end
476 477
    end

478 479 480 481
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
S
Shinya Maeda 已提交
482 483
    end

484 485 486
    def erase(opts = {})
      return false unless erasable?

487 488
      job_artifacts.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
489 490 491 492 493
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
494
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
495 496 497 498 499 500
    end

    def erased?
      !self.erased_at.nil?
    end

501
    def artifacts_expired?
502
      artifacts_expire_at && artifacts_expire_at < Time.now
503 504
    end

505 506 507 508 509
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
510 511
      self.artifacts_expire_at =
        if value
512
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
513
        end
514 515
    end

516
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
517
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
518 519
    end

520
    def keep_artifacts!
521
      self.update(artifacts_expire_at: nil)
522
      self.job_artifacts.update_all(expire_at: nil)
523 524
    end

525
    def coverage_regex
526
      super || project.try(:build_coverage_regex)
527 528
    end

529 530
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
531 532
    end

533 534
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
535 536
    end

537
    def user_variables
538
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
539
        break variables if user.blank?
540

541 542 543 544 545
        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
546 547
    end

548 549 550 551 552 553 554
    def secret_group_variables
      return [] unless project.group

      project.group.secret_variables_for(ref, project)
    end

    def secret_project_variables(environment: persisted_environment)
L
Lin Jen-Shin 已提交
555 556 557
      project.secret_variables_for(ref: ref, environment: environment)
    end

558
    def steps
T
Tomasz Maczukin 已提交
559 560
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
561 562 563
    end

    def image
564
      Gitlab::Ci::Build::Image.from_image(self)
565 566 567
    end

    def services
568
      Gitlab::Ci::Build::Image.from_services(self)
569 570 571
    end

    def cache
M
Matija Čupić 已提交
572 573 574 575
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
576
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
577
      end
M
Matija Čupić 已提交
578 579

      [cache]
580 581
    end

582
    def credentials
583
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
584 585
    end

T
Tomasz Maczukin 已提交
586
    def dependencies
587 588
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
589 590
      depended_jobs = depends_on_builds

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

593 594
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
595 596 597
      end
    end

598 599 600 601
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
602
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
603
      return true if Feature.enabled?('ci_disable_validates_dependencies')
604

K
Kamil Trzciński 已提交
605
      dependencies.all?(&:valid_dependency?)
606 607
    end

K
Kamil Trzciński 已提交
608
    def valid_dependency?
S
Shinya Maeda 已提交
609 610 611 612 613 614
      return false if artifacts_expired?
      return false if erased?

      true
    end

615 616 617 618 619 620 621 622
    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

623
    def supported_runner?(features)
624
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
625
        features&.dig(feature_name)
626 627 628
      end
    end

629
    def publishes_artifacts_reports?
630
      options&.dig(:artifacts, :reports)&.any?
631 632
    end

633 634 635 636
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
637 638
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
639 640 641
      trace
    end

642
    def serializable_hash(options = {})
J
James Lopez 已提交
643
      super(options).merge(when: read_attribute(:when))
644 645
    end

F
Francisco Javier López 已提交
646 647 648 649
    def has_terminal?
      running? && runner_session_url.present?
    end

S
Shinya Maeda 已提交
650 651
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
652 653
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
          Gitlab::Ci::Parsers::Test.fabricate!(file_type).parse!(blob, test_suite)
S
Shinya Maeda 已提交
654 655 656 657
        end
      end
    end

658 659 660 661 662 663 664 665 666 667 668 669 670
    # Virtual deployment status depending on the environment status.
    def deployment_status
      return nil unless starts_environment?

      if success?
        return successful_deployment_status
      elsif complete? && !success?
        return :failed
      end

      :creating
    end

671 672
    private

673 674 675 676 677 678 679
    def erase_old_artifacts!
      # TODO: To be removed once we get rid of
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

680 681 682 683 684 685 686 687 688 689
    def successful_deployment_status
      if success? && last_deployment&.last?
        return :last
      elsif success? && last_deployment.present?
        return :out_of_date
      end

      :creating
    end

690 691 692 693
    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 已提交
694 695 696 697
        end
      end
    end

698 699 700 701 702
    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 已提交
703
    def update_artifacts_size
K
Kamil Trzcinski 已提交
704
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
705 706
    end

707
    def erase_trace!
708
      trace.erase!
709 710 711
    end

    def update_erased!(user = nil)
712
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
713 714
    end

715
    def unscoped_project
K
Kamil Trzciński 已提交
716
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
717 718
    end

719 720
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

721 722
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
723
        break variables unless persisted?
724 725

        variables
726
          .concat(pipeline.persisted_variables)
727
          .append(key: 'CI_JOB_ID', value: id.to_s)
K
Kamil Trzciński 已提交
728
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
729 730 731 732 733 734
          .append(key: 'CI_JOB_TOKEN', value: token, public: false)
          .append(key: 'CI_BUILD_ID', value: id.to_s)
          .append(key: 'CI_BUILD_TOKEN', value: token, public: false)
          .append(key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER)
          .append(key: 'CI_REGISTRY_PASSWORD', value: token, public: false)
          .append(key: 'CI_REPOSITORY_URL', value: repo_url, public: false)
735
          .concat(deploy_token_variables)
736 737 738
      end
    end

739
    def predefined_variables
740 741 742
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
743
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
744 745
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
746
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
747 748 749
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
750
        variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
751 752 753 754 755 756 757
        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?
        variables.concat(legacy_variables)
      end
758 759 760
    end

    def legacy_variables
761 762 763 764 765 766 767 768 769 770 771
      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
772
    end
773

774 775
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
776
        break variables unless persisted? && persisted_environment.present?
777 778 779 780 781 782 783 784 785 786

        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

787 788
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
789 790
        break variables unless gitlab_deploy_token

791
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
792
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
793 794 795
      end
    end

796
    def environment_url
797
      options&.dig(:environment, :url) || persisted_environment&.external_url
798 799
    end

800 801
    def build_attributes_from_config
      return {} unless pipeline.config_processor
802

803 804
      pipeline.config_processor.build_attributes(name)
    end
805

806 807 808
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
809

810 811
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
812
    end
813

814 815 816 817 818 819
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
820
    end
D
Douwe Maan 已提交
821 822
  end
end