build.rb 21.6 KB
Newer Older
1
module Ci
2
  class Build < CommitStatus
3
    prepend ArtifactMigratable
4
    include TokenAuthenticatable
5
    include AfterCommitQueue
6
    include ObjectStorage::BackgroundMove
Rémy Coutable's avatar
Rémy Coutable committed
7
    include Presentable
8
    include Importable
9 10
    include Gitlab::Utils::StrongMemoize

11
    prepend EE::Ci::Build
12

13 14
    MissingDependenciesError = Class.new(StandardError)

15
    belongs_to :project, inverse_of: :builds
16 17
    belongs_to :runner
    belongs_to :trigger_request
18
    belongs_to :erased_by, class_name: 'User'
19

20 21
    has_many :sourced_pipelines, class_name: Ci::Sources::Pipeline, foreign_key: :source_job_id

22
    has_many :deployments, as: :deployable
23

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
29 30
    has_one :job_artifacts_archive, -> { where(file_type: Ci::JobArtifact.file_types[:archive]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
    has_one :job_artifacts_metadata, -> { where(file_type: Ci::JobArtifact.file_types[:metadata]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
Shinya Maeda's avatar
Shinya Maeda committed
31
    has_one :job_artifacts_trace, -> { where(file_type: Ci::JobArtifact.file_types[:trace]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
32

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

    accepts_nested_attributes_for :runner_session

38
    delegate :timeout, to: :metadata, prefix: true, allow_nil: true
39 40
    delegate :url, to: :runner_session, prefix: true, allow_nil: true
    delegate :terminal_specification, to: :runner_session, allow_nil: true
41
    delegate :gitlab_deploy_token, to: :project
42

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

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

54 55
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
56

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

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

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

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

73
    scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
74 75
    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) }
76
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
77
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
78
    scope :ref_protected, -> { where(protected: true) }
79
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    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

100 101
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
102

103 104
    acts_as_taggable

105 106
    add_authentication_token_field :token

107
    before_save :update_artifacts_size, if: :artifacts_file_changed?
108
    before_save :ensure_token
109
    before_destroy { unscoped_project }
110

111
    before_create :ensure_metadata
112
    after_create unless: :importing? do |build|
113
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
114 115
    end

116 117
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
118 119

    class << self
120 121 122 123 124 125
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

126 127 128 129
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

130
      def retry(build, current_user)
131 132 133
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
134 135 136
      end
    end

137
    state_machine :status do
138 139
      event :actionize do
        transition created: :manual
140 141
      end

142 143 144 145 146 147
      after_transition any => [:pending] do |build|
        build.run_after_commit do
          BuildQueueWorker.perform_async(id)
        end
      end

148
      after_transition pending: :running do |build|
149 150 151
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
152 153
      end

154
      after_transition any => [:success, :failed, :canceled] do |build|
155
        build.run_after_commit do
156
          BuildFinishedWorker.perform_async(id)
157
        end
158
      end
159

160
      after_transition any => [:success] do |build|
161 162
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
163
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
164 165
        end
      end
166

167
      before_transition any => [:failed] do |build|
168
        next unless build.project
169
        next if build.retries_max.zero?
170

171
        if build.retries_count < build.retries_max
172 173 174 175 176
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
177 178
        end
      end
179 180

      before_transition any => [:running] do |build|
181
        build.validates_dependencies! unless Feature.enabled?('ci_disable_validates_dependencies')
182
      end
183

184
      after_transition pending: :running do |build|
185 186
        build.ensure_metadata.update_timeout_state
      end
187 188

      after_transition running: any do |build|
189
        Ci::BuildRunnerSession.where(build: build).delete_all
190
      end
191 192 193 194
    end

    def ensure_metadata
      metadata || build_metadata(project: project)
195 196
    end

197
    def detailed_status(current_user)
198 199 200
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
Kamil Trzcinski's avatar
Kamil Trzcinski committed
201 202
    end

203
    def other_actions
204
      pipeline.manual_actions.where.not(name: name)
205 206
    end

207 208 209 210 211
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

212
    def playable?
213
      action? && (manual? || retryable?)
214 215
    end

216
    def action?
217 218 219
      self.when == 'manual'
    end

220
    def play(current_user)
221 222 223
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
224 225
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
226 227 228 229
    def cancelable?
      active?
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
230
    def retryable?
231
      success? || failed? || canceled?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
232 233
    end

234 235 236 237 238 239 240
    def retries_count
      pipeline.builds.retried.where(name: self.name).count
    end

    def retries_max
      self.options.fetch(:retry, 0).to_i
    end
Kamil Trzcinski's avatar
Kamil Trzcinski committed
241

242 243
    def latest?
      !retried?
244 245
    end

246
    def expanded_environment_name
247 248 249
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
250 251
        ExpandVariables.expand(environment, simple_variables)
      end
252 253
    end

254
    def has_environment?
255
      environment.present?
256 257
    end

258
    def starts_environment?
259
      has_environment? && self.environment_action == 'start'
260 261 262
    end

    def stops_environment?
263
      has_environment? && self.environment_action == 'stop'
264 265 266
    end

    def environment_action
267
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
268 269 270 271
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
272
    end
273

274 275
    def depends_on_builds
      # Get builds of the same type
276
      latest_builds = self.pipeline.builds.latest
277 278 279 280 281

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

282
    def triggered_by?(current_user)
283 284 285
      user == current_user
    end

Nick Thomas's avatar
Nick Thomas committed
286 287 288 289 290 291
    # 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
292
    #   * First/Last Character is not a hyphen
Nick Thomas's avatar
Nick Thomas committed
293
    def ref_slug
294
      Gitlab::Utils.slugify(ref.to_s)
Nick Thomas's avatar
Nick Thomas committed
295 296
    end

297 298 299 300 301
    ##
    # Variables in the environment name scope.
    #
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
302 303 304 305
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
306
        variables.concat(project.deployment_variables(environment: environment)) if environment
307 308
        variables.concat(yaml_variables)
        variables.concat(user_variables)
309 310
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
311 312 313 314
        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
315 316 317 318 319 320
    end

    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
321 322 323
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
324 325 326 327 328 329
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
330 331 332
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
333 334 335
        .concat(persisted_environment_variables)
        .to_runner_variables
    end
336

337 338 339 340 341
    ##
    # 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
342
      scoped_variables.to_hash
343 344
    end

345 346 347 348
    def features
      { trace_sections: true }
    end

349
    def merge_request
350 351 352 353
      return @merge_request if defined?(@merge_request)

      @merge_request ||=
        begin
354
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
355 356 357 358 359
            .where(source_branch: ref,
                   source_project: pipeline.project)
            .reorder(iid: :desc)

          merge_requests.find do |merge_request|
360
            merge_request.commit_shas.include?(pipeline.sha)
361 362
          end
        end
363 364
    end

365
    def repo_url
Kamil Trzcinski's avatar
Kamil Trzcinski committed
366
      auth = "gitlab-ci-token:#{ensure_token!}@"
367
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
368 369
        prefix + auth
      end
370 371 372
    end

    def allow_git_fetch
373
      project.build_allow_git_fetch
374 375 376
    end

    def update_coverage
377
      coverage = trace.extract_coverage(coverage_regex)
378
      update_attributes(coverage: coverage) if coverage.present?
379 380
    end

381
    def parse_trace_sections!
382
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
383 384
    end

385 386
    def trace
      Gitlab::Ci::Trace.new(self)
387 388
    end

389
    def has_trace?
390
      trace.exist?
391
    end
392

393 394
    def trace=(data)
      raise NotImplementedError
Tomasz Maczukin's avatar
Tomasz Maczukin committed
395 396
    end

397 398
    def old_trace
      read_attribute(:trace)
399
    end
400

401
    def erase_old_trace!
402
      update_column(:trace, nil)
403 404
    end

405 406 407 408
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

409
    def valid_token?(token)
410
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
411 412
    end

413 414 415 416
    def has_tags?
      tag_list.any?
    end

417
    def any_runners_online?
418
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
419 420
    end

421
    def stuck?
422 423 424
      pending? && !any_runners_online?
    end

425
    def execute_hooks
426
      return unless project
427

428
      build_data = Gitlab::DataBuilder::Build.build(self)
429 430
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
431 432
    end

433 434 435 436
    def browsable_artifacts?
      artifacts_metadata?
    end

437
    def artifacts_metadata_entry(path, **options)
438 439 440 441 442
      artifacts_metadata.use_file do |metadata_path|
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
          metadata_path,
          path,
          **options)
443

444 445
        metadata.to_entry
      end
446 447
    end

448 449 450
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
451
      save
452 453
    end

454 455 456
    def erase(opts = {})
      return false unless erasable?

457
      erase_artifacts!
458 459 460 461 462 463 464 465 466 467 468 469
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
      complete? && (artifacts? || has_trace?)
    end

    def erased?
      !self.erased_at.nil?
    end

470
    def artifacts_expired?
471
      artifacts_expire_at && artifacts_expire_at < Time.now
472 473
    end

474 475 476 477 478
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
479 480
      self.artifacts_expire_at =
        if value
481
          ChronicDuration.parse(value)&.seconds&.from_now
482
        end
483 484
    end

485
    def has_expiring_artifacts?
486
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
487 488
    end

489
    def keep_artifacts!
490
      self.update(artifacts_expire_at: nil)
491
      self.job_artifacts.update_all(expire_at: nil)
492 493
    end

494
    def coverage_regex
495
      super || project.try(:build_coverage_regex)
496 497
    end

498 499 500 501 502 503 504 505
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
    end

    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
    end

506
    def user_variables
507
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
Jacopo's avatar
Jacopo committed
508
        break variables if user.blank?
509

510 511 512 513 514
        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
515 516
    end

517 518 519 520 521 522 523
    def secret_group_variables
      return [] unless project.group

      project.group.secret_variables_for(ref, project)
    end

    def secret_project_variables(environment: persisted_environment)
524
      project.secret_variables_for(ref: ref, environment: environment)
525 526
    end

527
    def steps
Tomasz Maczukin's avatar
Tomasz Maczukin committed
528 529
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
530 531 532
    end

    def image
533
      Gitlab::Ci::Build::Image.from_image(self)
534 535 536
    end

    def services
537
      Gitlab::Ci::Build::Image.from_services(self)
538 539 540
    end

    def artifacts
541
      [options[:artifacts]]
542 543 544
    end

    def cache
Matija Čupić's avatar
Matija Čupić committed
545 546 547 548
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
549
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
550
      end
Matija Čupić's avatar
Matija Čupić committed
551 552

      [cache]
553 554
    end

555
    def credentials
556
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
557 558
    end

559
    def dependencies
560 561
      return [] if empty_dependencies?

562 563
      depended_jobs = depends_on_builds

564
      return depended_jobs unless options[:dependencies].present?
565

566 567
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
568 569 570
      end
    end

571 572 573 574
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

575
    def validates_dependencies!
576 577
      dependencies.each do |dependency|
        raise MissingDependenciesError unless dependency.valid_dependency?
578
      end
579 580
    end

Shinya Maeda's avatar
Shinya Maeda committed
581 582 583 584 585 586 587
    def valid_dependency?
      return false if artifacts_expired?
      return false if erased?

      true
    end

588 589 590 591
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
592 593
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
594 595 596
      trace
    end

597
    def serializable_hash(options = {})
598
      super(options).merge(when: read_attribute(:when))
599 600
    end

601 602 603 604
    def has_terminal?
      running? && runner_session_url.present?
    end

605 606
    private

607
    def update_artifacts_size
Kamil Trzcinski's avatar
Kamil Trzcinski committed
608
      self.artifacts_size = legacy_artifacts_file&.size
609 610
    end

611
    def erase_trace!
612
      trace.erase!
613 614 615
    end

    def update_erased!(user = nil)
616
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
617 618
    end

619
    def unscoped_project
620
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
621 622
    end

623 624
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

625 626
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
Jacopo's avatar
Jacopo committed
627
        break variables unless persisted?
628 629

        variables
630
          .concat(pipeline.persisted_variables)
631
          .append(key: 'CI_JOB_ID', value: id.to_s)
632
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
633 634 635 636 637 638
          .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)
639
          .concat(deploy_token_variables)
640 641 642
      end
    end

643
    def predefined_variables
644 645 646
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
647
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
648 649
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
650
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
651 652 653 654 655 656 657 658 659 660
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
        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
661 662 663
    end

    def legacy_variables
664 665 666 667 668 669 670 671 672 673 674
      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
675
    end
676

677 678
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
Jacopo's avatar
Jacopo committed
679
        break variables unless persisted? && persisted_environment.present?
680 681 682 683 684 685 686 687 688 689

        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

690 691
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
692 693
        break variables unless gitlab_deploy_token

694
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
695
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
696 697 698
      end
    end

699 700 701 702
    def environment_url
      options&.dig(:environment, :url) || persisted_environment&.external_url
    end

703 704
    def build_attributes_from_config
      return {} unless pipeline.config_processor
705

706 707
      pipeline.config_processor.build_attributes(name)
    end
708

709 710 711
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
712

713 714
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
715
    end
716

717 718 719 720 721 722
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
723
    end
724 725
  end
end