build.rb 21.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
    belongs_to :project, inverse_of: :builds
12 13
    belongs_to :runner
    belongs_to :trigger_request
14
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
15

16
    has_many :deployments, as: :deployable
17

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

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

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

    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
31

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

    accepts_nested_attributes_for :runner_session

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

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

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

53 54
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
55

D
Douwe Maan 已提交
56 57
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
58
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
59
    validates :ref, presence: true
D
Douwe Maan 已提交
60 61

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

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

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

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

99 100
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
101

D
Douwe Maan 已提交
102 103
    acts_as_taggable

104 105
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
106
    before_save :update_artifacts_size, if: :artifacts_file_changed?
107
    before_save :ensure_token
108
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
109

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

115 116
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
D
Douwe Maan 已提交
117 118

    class << self
119 120 121 122 123 124
      # 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 已提交
125 126 127 128
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

129
      def retry(build, current_user)
130 131 132
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
133 134 135
      end
    end

136
    state_machine :status do
137 138
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
139 140
      end

141 142
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
143
          BuildQueueWorker.perform_async(id)
144 145 146
        end
      end

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

153
      after_transition any => [:success, :failed, :canceled] do |build|
154
        build.run_after_commit do
155
          BuildFinishedWorker.perform_async(id)
156
        end
D
Douwe Maan 已提交
157
      end
158

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

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

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

179
      after_transition pending: :running do |build|
180
        build.ensure_metadata.update_timeout_state
T
Tomasz Maczukin 已提交
181
      end
F
Francisco Javier López 已提交
182 183 184 185

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

188
    def ensure_metadata
T
Tomasz Maczukin 已提交
189
      metadata || build_metadata(project: project)
D
Douwe Maan 已提交
190 191
    end

192
    def detailed_status(current_user)
193 194 195
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
196 197
    end

198
    def other_actions
199
      pipeline.manual_actions.where.not(name: name)
200 201
    end

202 203 204 205 206
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

207
    def playable?
208
      action? && (manual? || retryable?)
K
Kamil Trzcinski 已提交
209 210
    end

211
    def action?
212 213 214
      self.when == 'manual'
    end

215
    def play(current_user)
216 217 218
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
219 220
    end

K
Kamil Trzcinski 已提交
221 222 223 224
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
225
    def retryable?
226
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
227
    end
228 229 230 231 232 233 234 235

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

237 238
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
239 240
    end

241
    def expanded_environment_name
242 243 244
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
245 246
        ExpandVariables.expand(environment, simple_variables)
      end
247 248
    end

249
    def has_environment?
250
      environment.present?
251 252
    end

253
    def starts_environment?
254
      has_environment? && self.environment_action == 'start'
255 256 257
    end

    def stops_environment?
258
      has_environment? && self.environment_action == 'stop'
259 260 261
    end

    def environment_action
262
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
263 264 265 266
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
267
    end
268

269 270
    def depends_on_builds
      # Get builds of the same type
271
      latest_builds = self.pipeline.builds.latest
272 273 274 275 276

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

277
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
278 279 280
      user == current_user
    end

N
Nick Thomas 已提交
281 282 283 284 285 286
    # 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 已提交
287
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
288
    def ref_slug
V
vanadium23 已提交
289
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
290 291
    end

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

312 313 314 315
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
316 317 318
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
319 320 321 322 323 324
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
325 326 327
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
328 329 330 331
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

332 333 334 335 336
    ##
    # 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
337
      scoped_variables.to_hash
338 339
    end

340 341 342 343
    def features
      { trace_sections: true }
    end

344
    def merge_request
Z
Z.J. van de Weg 已提交
345
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
346

347 348
      @merge_request ||=
        begin
349
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
350 351
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
352
            .reorder(iid: :desc)
353 354

          merge_requests.find do |merge_request|
355
            merge_request.commit_shas.include?(pipeline.sha)
356 357
          end
        end
358 359
    end

D
Douwe Maan 已提交
360
    def repo_url
K
Kamil Trzcinski 已提交
361
      auth = "gitlab-ci-token:#{ensure_token!}@"
362
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
363 364
        prefix + auth
      end
D
Douwe Maan 已提交
365 366 367
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
368
      project.build_allow_git_fetch
D
Douwe Maan 已提交
369 370 371
    end

    def update_coverage
372
      coverage = trace.extract_coverage(coverage_regex)
L
Lin Jen-Shin 已提交
373
      update(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
374 375
    end

376
    def parse_trace_sections!
377
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
378 379
    end

380 381
    def trace
      Gitlab::Ci::Trace.new(self)
382 383
    end

384
    def has_trace?
385
      trace.exist?
T
Tomasz Maczukin 已提交
386 387
    end

S
Shinya Maeda 已提交
388 389 390 391
    def has_test_reports?
      job_artifacts.test_reports.any?
    end

S
Shinya Maeda 已提交
392 393 394 395
    def has_old_trace?
      old_trace.present?
    end

396 397
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
398 399
    end

400 401
    def old_trace
      read_attribute(:trace)
402 403
    end

404
    def erase_old_trace!
405
      return unless has_old_trace?
S
Shinya Maeda 已提交
406

407
      update_column(:trace, nil)
D
Douwe Maan 已提交
408 409
    end

410 411 412 413
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
414
    def valid_token?(token)
415
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
416 417
    end

418 419 420 421
    def has_tags?
      tag_list.any?
    end

422
    def any_runners_online?
423
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
424 425
    end

K
Kamil Trzcinski 已提交
426
    def stuck?
427 428 429
      pending? && !any_runners_online?
    end

430
    def execute_hooks
431
      return unless project
432

433
      build_data = Gitlab::DataBuilder::Build.build(self)
434 435
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
436 437
    end

438 439 440 441
    def browsable_artifacts?
      artifacts_metadata?
    end

442
    def artifacts_metadata_entry(path, **options)
443
      artifacts_metadata.open do |metadata_stream|
444
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
445
          metadata_stream,
446 447
          path,
          **options)
448

449 450
        metadata.to_entry
      end
451 452
    end

453 454 455
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
456
      save
457 458
    end

S
Shinya Maeda 已提交
459
    def erase_test_reports!
S
Shinya Maeda 已提交
460 461
      # TODO: Use fast_destroy_all in the context of https://gitlab.com/gitlab-org/gitlab-ce/issues/35240
      job_artifacts_junit&.destroy
S
Shinya Maeda 已提交
462 463
    end

464 465 466
    def erase(opts = {})
      return false unless erasable?

467
      erase_artifacts!
S
Shinya Maeda 已提交
468
      erase_test_reports!
469 470 471 472 473
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
S
Shinya Maeda 已提交
474
      complete? && (artifacts? || has_test_reports? || has_trace?)
475 476 477 478 479 480
    end

    def erased?
      !self.erased_at.nil?
    end

481
    def artifacts_expired?
482
      artifacts_expire_at && artifacts_expire_at < Time.now
483 484
    end

485 486 487 488 489
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
490 491
      self.artifacts_expire_at =
        if value
492
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
493
        end
494 495
    end

496
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
497
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
498 499
    end

500
    def keep_artifacts!
501
      self.update(artifacts_expire_at: nil)
502
      self.job_artifacts.update_all(expire_at: nil)
503 504
    end

505
    def coverage_regex
506
      super || project.try(:build_coverage_regex)
507 508
    end

509 510
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
511 512
    end

513 514
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
515 516
    end

517
    def user_variables
518
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
519
        break variables if user.blank?
520

521 522 523 524 525
        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
526 527
    end

528 529 530 531 532 533 534
    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 已提交
535 536 537
      project.secret_variables_for(ref: ref, environment: environment)
    end

538
    def steps
T
Tomasz Maczukin 已提交
539 540
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
541 542 543
    end

    def image
544
      Gitlab::Ci::Build::Image.from_image(self)
545 546 547
    end

    def services
548
      Gitlab::Ci::Build::Image.from_services(self)
549 550 551
    end

    def cache
M
Matija Čupić 已提交
552 553 554 555
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
556
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
557
      end
M
Matija Čupić 已提交
558 559

      [cache]
560 561
    end

562
    def credentials
563
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
564 565
    end

T
Tomasz Maczukin 已提交
566
    def dependencies
567 568
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
569 570
      depended_jobs = depends_on_builds

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

573 574
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
575 576 577
      end
    end

578 579 580 581
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

K
Kamil Trzciński 已提交
582
    def has_valid_build_dependencies?
K
Kamil Trzciński 已提交
583
      return true if Feature.enabled?('ci_disable_validates_dependencies')
584

K
Kamil Trzciński 已提交
585
      dependencies.all?(&:valid_dependency?)
586 587
    end

K
Kamil Trzciński 已提交
588
    def valid_dependency?
S
Shinya Maeda 已提交
589 590 591 592 593 594
      return false if artifacts_expired?
      return false if erased?

      true
    end

595 596 597 598 599 600 601 602
    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

603
    def supported_runner?(features)
604
      runner_required_feature_names.all? do |feature_name|
K
Kamil Trzciński 已提交
605
        features&.dig(feature_name)
606 607 608
      end
    end

609
    def publishes_artifacts_reports?
610
      options&.dig(:artifacts, :reports)&.any?
611 612
    end

613 614 615 616
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
617 618
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
619 620 621
      trace
    end

622
    def serializable_hash(options = {})
J
James Lopez 已提交
623
      super(options).merge(when: read_attribute(:when))
624 625
    end

F
Francisco Javier López 已提交
626 627 628 629
    def has_terminal?
      running? && runner_session_url.present?
    end

630 631
    private

L
Lin Jen-Shin 已提交
632
    def update_artifacts_size
K
Kamil Trzcinski 已提交
633
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
634 635
    end

636
    def erase_trace!
637
      trace.erase!
638 639 640
    end

    def update_erased!(user = nil)
641
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
642 643
    end

644
    def unscoped_project
K
Kamil Trzciński 已提交
645
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
646 647
    end

648 649
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

650 651
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
652
        break variables unless persisted?
653 654

        variables
655
          .concat(pipeline.persisted_variables)
656
          .append(key: 'CI_JOB_ID', value: id.to_s)
K
Kamil Trzciński 已提交
657
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
658 659 660 661 662 663
          .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)
664
          .concat(deploy_token_variables)
665 666 667
      end
    end

668
    def predefined_variables
669 670 671
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
672
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
673 674
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
675
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
676 677 678
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
679
        variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
680 681 682 683 684 685 686
        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
687 688 689
    end

    def legacy_variables
690 691 692 693 694 695 696 697 698 699 700
      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
701
    end
702

703 704
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
705
        break variables unless persisted? && persisted_environment.present?
706 707 708 709 710 711 712 713 714 715

        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

716 717
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
718 719
        break variables unless gitlab_deploy_token

720
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
721
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
722 723 724
      end
    end

725
    def environment_url
726
      options&.dig(:environment, :url) || persisted_environment&.external_url
727 728
    end

729 730
    def build_attributes_from_config
      return {} unless pipeline.config_processor
731

732 733
      pipeline.config_processor.build_attributes(name)
    end
734

735 736 737
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
738

739 740
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
741
    end
742

743 744 745 746 747 748
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
749
    end
D
Douwe Maan 已提交
750 751
  end
end