build.rb 20.9 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
Z
Zeger-Jan van de Weg 已提交
3
    prepend ArtifactMigratable
4
    include TokenAuthenticatable
5
    include AfterCommitQueue
6
    include ObjectStorage::BackgroundMove
R
Rémy Coutable 已提交
7
    include Presentable
S
Shinya Maeda 已提交
8
    include Importable
9
    include Gitlab::Utils::StrongMemoize
10

11 12
    MissingDependenciesError = Class.new(StandardError)

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
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
21
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
22
    has_many :trace_chunks, class_name: 'Ci::BuildTraceChunk', foreign_key: :build_id
23

24
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy, inverse_of: :job # rubocop:disable Cop/ActiveRecordDependent
25 26
    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
S
Shinya Maeda 已提交
27
    has_one :job_artifacts_trace, -> { where(file_type: Ci::JobArtifact.file_types[:trace]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
28

29
    has_one :metadata, class_name: 'Ci::BuildMetadata'
T
Tomasz Maczukin 已提交
30
    delegate :timeout, to: :metadata, prefix: true, allow_nil: true
31
    delegate :gitlab_deploy_token, to: :project
T
Tomasz Maczukin 已提交
32

33 34 35
    ##
    # The "environment" field for builds is a String, and is the unexpanded name!
    #
36
    def persisted_environment
37 38 39 40 41
      return unless has_environment?

      strong_memoize(:persisted_environment) do
        Environment.find_by(name: expanded_environment_name, project: project)
      end
42 43
    end

44 45
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
46

D
Douwe Maan 已提交
47 48
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
49
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
50
    validates :ref, presence: true
D
Douwe Maan 已提交
51 52

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
53
    scope :ignore_failures, ->() { where(allow_failure: false) }
54
    scope :with_artifacts_archive, ->() do
55
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
56
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id').archive)
57
    end
58 59 60 61 62

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

63
    scope :with_artifacts_stored_locally, -> { with_artifacts_archive.where(artifacts_file_store: [nil, LegacyArtifactUploader::Store::LOCAL]) }
64 65
    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) }
66
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
67
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
68
    scope :ref_protected, -> { where(protected: true) }
69
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    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

90 91
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
92

D
Douwe Maan 已提交
93 94
    acts_as_taggable

95 96
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
97
    before_save :update_artifacts_size, if: :artifacts_file_changed?
98
    before_save :ensure_token
99
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
100

101
    before_create :ensure_metadata
102
    after_create unless: :importing? do |build|
103
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
104 105
    end

106 107
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
D
Douwe Maan 已提交
108 109

    class << self
110 111 112 113 114 115
      # 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 已提交
116 117 118 119
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

120
      def retry(build, current_user)
121 122 123
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
124 125 126
      end
    end

127
    state_machine :status do
128 129
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
130 131
      end

132 133
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
134
          BuildQueueWorker.perform_async(id)
135 136 137
        end
      end

138
      after_transition pending: :running do |build|
139 140 141
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
142 143
      end

144
      after_transition any => [:success, :failed, :canceled] do |build|
145
        build.run_after_commit do
146
          BuildFinishedWorker.perform_async(id)
147
        end
D
Douwe Maan 已提交
148
      end
149

150
      after_transition any => [:success] do |build|
151 152
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
153
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
154 155
        end
      end
156

157
      before_transition any => [:failed] do |build|
158
        next unless build.project
159
        next if build.retries_max.zero?
160

161
        if build.retries_count < build.retries_max
162 163 164 165 166
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
167 168
        end
      end
169 170

      before_transition any => [:running] do |build|
171
        build.validates_dependencies! unless Feature.enabled?('ci_disable_validates_dependencies')
172
      end
T
Tomasz Maczukin 已提交
173

174
      after_transition pending: :running do |build|
175
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
176
      end
D
Douwe Maan 已提交
177 178
    end

179
    def ensure_metadata
T
Tomasz Maczukin 已提交
180
      metadata || build_metadata(project: project)
D
Douwe Maan 已提交
181 182
    end

183
    def detailed_status(current_user)
184 185 186
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
187 188
    end

189
    def other_actions
190
      pipeline.manual_actions.where.not(name: name)
191 192
    end

193 194 195 196 197
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

198
    def playable?
199
      action? && (manual? || retryable?)
K
Kamil Trzcinski 已提交
200 201
    end

202
    def action?
203 204 205
      self.when == 'manual'
    end

206
    def play(current_user)
207 208 209
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
210 211
    end

K
Kamil Trzcinski 已提交
212 213 214 215
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
216
    def retryable?
217
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
218
    end
219 220 221 222 223 224 225 226

    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 已提交
227

228 229
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
230 231
    end

232
    def expanded_environment_name
233 234 235
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
236 237
        ExpandVariables.expand(environment, simple_variables)
      end
238 239
    end

240
    def has_environment?
241
      environment.present?
242 243
    end

244
    def starts_environment?
245
      has_environment? && self.environment_action == 'start'
246 247 248
    end

    def stops_environment?
249
      has_environment? && self.environment_action == 'stop'
250 251 252
    end

    def environment_action
253
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
254 255 256 257
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
258
    end
259

260 261
    def depends_on_builds
      # Get builds of the same type
262
      latest_builds = self.pipeline.builds.latest
263 264 265 266 267

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

268
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
269 270 271
      user == current_user
    end

N
Nick Thomas 已提交
272 273 274 275 276 277
    # 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 已提交
278
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
279
    def ref_slug
V
vanadium23 已提交
280
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
281 282
    end

283
    ##
284
    # Variables in the environment name scope.
285
    #
286 287
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
288 289 290 291
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
292
        variables.concat(project.deployment_variables(environment: environment)) if environment
293 294
        variables.concat(yaml_variables)
        variables.concat(user_variables)
295 296
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
297 298 299 300
        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
301
    end
302

303 304 305 306
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
307 308 309
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
310 311 312 313 314 315
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
316 317 318
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
319 320 321 322
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

323 324 325 326 327
    ##
    # 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
328
      scoped_variables.to_hash
329 330
    end

331 332 333 334
    def features
      { trace_sections: true }
    end

335
    def merge_request
Z
Z.J. van de Weg 已提交
336
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
337

338 339
      @merge_request ||=
        begin
340
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
341 342
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
343
            .reorder(iid: :desc)
344 345

          merge_requests.find do |merge_request|
346
            merge_request.commit_shas.include?(pipeline.sha)
347 348
          end
        end
349 350
    end

D
Douwe Maan 已提交
351
    def repo_url
K
Kamil Trzcinski 已提交
352
      auth = "gitlab-ci-token:#{ensure_token!}@"
353
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
354 355
        prefix + auth
      end
D
Douwe Maan 已提交
356 357 358
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
359
      project.build_allow_git_fetch
D
Douwe Maan 已提交
360 361 362
    end

    def update_coverage
363
      coverage = trace.extract_coverage(coverage_regex)
364
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
365 366
    end

367
    def parse_trace_sections!
368
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
369 370
    end

371 372
    def trace
      Gitlab::Ci::Trace.new(self)
373 374
    end

375
    def has_trace?
376
      trace.exist?
T
Tomasz Maczukin 已提交
377 378
    end

379 380
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
381 382
    end

383 384
    def old_trace
      read_attribute(:trace)
385 386
    end

387
    def erase_old_trace!
388
      update_column(:trace, nil)
D
Douwe Maan 已提交
389 390
    end

391 392 393 394
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
395
    def valid_token?(token)
396
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
397 398
    end

399 400 401 402
    def has_tags?
      tag_list.any?
    end

403
    def any_runners_online?
404
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
405 406
    end

K
Kamil Trzcinski 已提交
407
    def stuck?
408 409 410
      pending? && !any_runners_online?
    end

411
    def execute_hooks
412
      return unless project
413

414
      build_data = Gitlab::DataBuilder::Build.build(self)
415 416
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
417 418
    end

419 420 421 422
    def browsable_artifacts?
      artifacts_metadata?
    end

423
    def artifacts_metadata_entry(path, **options)
424 425 426 427 428
      artifacts_metadata.use_file do |metadata_path|
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
          metadata_path,
          path,
          **options)
429

430 431
        metadata.to_entry
      end
432 433
    end

434 435 436
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
437
      save
438 439
    end

440 441 442
    def erase(opts = {})
      return false unless erasable?

443
      erase_artifacts!
444 445 446 447 448 449 450 451 452 453 454 455
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

456
    def artifacts_expired?
457
      artifacts_expire_at && artifacts_expire_at < Time.now
458 459
    end

460 461 462 463 464
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
465 466
      self.artifacts_expire_at =
        if value
467
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
468
        end
469 470
    end

471
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
472
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
473 474
    end

475
    def keep_artifacts!
476
      self.update(artifacts_expire_at: nil)
477
      self.job_artifacts.update_all(expire_at: nil)
478 479
    end

480
    def coverage_regex
481
      super || project.try(:build_coverage_regex)
482 483
    end

484 485
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
486 487
    end

488 489
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
490 491
    end

492
    def user_variables
493
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
494
        break variables if user.blank?
495

496 497 498 499 500
        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
501 502
    end

503 504 505 506 507 508 509
    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 已提交
510 511 512
      project.secret_variables_for(ref: ref, environment: environment)
    end

513
    def steps
T
Tomasz Maczukin 已提交
514 515
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
516 517 518
    end

    def image
519
      Gitlab::Ci::Build::Image.from_image(self)
520 521 522
    end

    def services
523
      Gitlab::Ci::Build::Image.from_services(self)
524 525
    end

526
    def artifacts
527
      [options[:artifacts]]
528 529 530
    end

    def cache
M
Matija Čupić 已提交
531 532 533 534
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
535
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
536
      end
M
Matija Čupić 已提交
537 538

      [cache]
539 540
    end

541
    def credentials
542
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
543 544
    end

T
Tomasz Maczukin 已提交
545
    def dependencies
546 547
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
548 549
      depended_jobs = depends_on_builds

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

552 553
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
554 555 556
      end
    end

557 558 559 560
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

561
    def validates_dependencies!
562 563
      dependencies.each do |dependency|
        raise MissingDependenciesError unless dependency.valid_dependency?
564
      end
565 566
    end

S
Shinya Maeda 已提交
567 568 569 570 571 572 573
    def valid_dependency?
      return false if artifacts_expired?
      return false if erased?

      true
    end

574 575 576 577
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
578 579
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
580 581 582
      trace
    end

583
    def serializable_hash(options = {})
J
James Lopez 已提交
584
      super(options).merge(when: read_attribute(:when))
585 586
    end

587 588
    private

L
Lin Jen-Shin 已提交
589
    def update_artifacts_size
K
Kamil Trzcinski 已提交
590
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
591 592
    end

593
    def erase_trace!
594
      trace.erase!
595 596 597
    end

    def update_erased!(user = nil)
598
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
599 600
    end

601
    def unscoped_project
K
Kamil Trzciński 已提交
602
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
603 604
    end

605 606
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

607 608
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
609
        break variables unless persisted?
610 611

        variables
612
          .concat(pipeline.persisted_variables)
613 614 615 616 617 618 619
          .append(key: 'CI_JOB_ID', value: id.to_s)
          .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)
620
          .concat(deploy_token_variables)
621 622 623
      end
    end

624
    def predefined_variables
625 626 627
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
628
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
629 630
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
631
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
632 633 634 635 636 637 638 639 640 641
        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
642 643 644
    end

    def legacy_variables
645 646 647 648 649 650 651 652 653 654 655
      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
656
    end
657

658 659
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
660
        break variables unless persisted? && persisted_environment.present?
661 662 663 664 665 666 667 668 669 670

        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

671 672
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
673 674
        break variables unless gitlab_deploy_token

675
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
676
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
677 678 679
      end
    end

680
    def environment_url
681
      options&.dig(:environment, :url) || persisted_environment&.external_url
682 683
    end

684 685
    def build_attributes_from_config
      return {} unless pipeline.config_processor
686

687 688
      pipeline.config_processor.build_attributes(name)
    end
689

690 691 692
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
693

694 695
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
696
    end
697

698 699 700 701 702 703
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
704
    end
D
Douwe Maan 已提交
705 706
  end
end