build.rb 26.2 KB
Newer Older
1
2
# frozen_string_literal: true

Douwe Maan's avatar
Douwe Maan committed
3
module Ci
Kamil Trzcinski's avatar
Kamil Trzcinski committed
4
  class Build < CommitStatus
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
5
    prepend ArtifactMigratable
6
    include TokenAuthenticatable
7
    include AfterCommitQueue
8
    include ObjectStorage::BackgroundMove
Rémy Coutable's avatar
Rémy Coutable committed
9
    include Presentable
Shinya Maeda's avatar
Shinya Maeda committed
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'
Douwe Maan's avatar
Douwe Maan committed
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
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'
35
36
37
38
    has_one :runner_session, class_name: 'Ci::BuildRunnerSession', validate: true, inverse_of: :build

    accepts_nested_attributes_for :runner_session

Tomasz Maczukin's avatar
Tomasz Maczukin committed
39
    delegate :timeout, to: :metadata, prefix: true, allow_nil: true
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
Tomasz Maczukin's avatar
Tomasz Maczukin committed
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
Douwe Maan's avatar
Douwe Maan committed
58

Douwe Maan's avatar
Douwe Maan committed
59
60
    delegate :name, to: :project, prefix: true

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

    scope :unstarted, ->() { where(runner_id: nil) }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
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

83
    scope :with_test_reports, ->() do
84
85
      with_existing_job_artifacts(Ci::JobArtifact.test_reports)
        .eager_load_job_artifacts
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
96
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + %i[manual]) }
    scope :scheduled_actions, ->() { where(when: :delayed, status: COMPLETED_STATUSES + %i[scheduled]) }
97
    scope :ref_protected, -> { where(protected: true) }
98
    scope :with_live_trace, -> { where('EXISTS (?)', Ci::BuildTraceChunk.where('ci_builds.id = ci_build_trace_chunks.build_id').select(1)) }
99

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    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

119
120
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
Kamil Trzcinski's avatar
Kamil Trzcinski committed
121

Douwe Maan's avatar
Douwe Maan committed
122
123
    acts_as_taggable

124
125
    add_authentication_token_field :token

126
    before_save :update_artifacts_size, if: :artifacts_file_changed?
127
    before_save :ensure_token
128
    before_destroy { unscoped_project }
Grzegorz Bizon's avatar
Grzegorz Bizon committed
129

130
    before_create :ensure_metadata
131
    after_create unless: :importing? do |build|
132
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
133
134
    end

135
136
    after_save :update_project_statistics_after_save, if: :artifacts_size_changed?
    after_destroy :update_project_statistics_after_destroy, unless: :project_destroyed?
Douwe Maan's avatar
Douwe Maan committed
137
138

    class << self
139
140
141
142
143
144
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

Douwe Maan's avatar
Douwe Maan committed
145
146
147
148
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

149
      def retry(build, current_user)
150
        # rubocop: disable CodeReuse/ServiceClass
151
152
153
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
154
        # rubocop: enable CodeReuse/ServiceClass
Douwe Maan's avatar
Douwe Maan committed
155
156
157
      end
    end

158
    state_machine :status do
159
160
      event :actionize do
        transition created: :manual
Kamil Trzcinski's avatar
Kamil Trzcinski committed
161
162
      end

163
164
165
166
167
168
169
170
      event :schedule do
        transition created: :scheduled
      end

      event :unschedule do
        transition scheduled: :manual
      end

171
      event :enqueue_scheduled do
172
173
        transition scheduled: :pending, if: ->(build) do
          build.scheduled_at && build.scheduled_at < Time.now
174
        end
175
176
177
      end

      before_transition scheduled: any do |build|
178
179
180
181
        build.scheduled_at = nil
      end

      before_transition created: :scheduled do |build|
Shinya Maeda's avatar
Shinya Maeda committed
182
        build.scheduled_at = build.options_scheduled_at
183
184
185
186
187
188
      end

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

191
192
      after_transition any => [:pending] do |build|
        build.run_after_commit do
Kim "BKC" Carlbäcker's avatar
linting    
Kim "BKC" Carlbäcker committed
193
          BuildQueueWorker.perform_async(id)
194
195
196
        end
      end

197
      after_transition pending: :running do |build|
198
199
200
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
201
202
      end

203
      after_transition any => [:success, :failed, :canceled] do |build|
204
        build.run_after_commit do
205
          BuildFinishedWorker.perform_async(id)
206
        end
Douwe Maan's avatar
Douwe Maan committed
207
      end
208

209
      after_transition any => [:success] do |build|
210
211
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
212
          PagesWorker.perform_async(:deploy, id) if build.pages_generator?
213
214
        end
      end
215

216
      before_transition any => [:failed] do |build|
217
        next unless build.project
218
        next if build.retries_max.zero?
219

220
        if build.retries_count < build.retries_max
221
222
223
224
225
          begin
            Ci::Build.retry(build, build.user)
          rescue Gitlab::Access::AccessDeniedError => ex
            Rails.logger.error "Unable to auto-retry job #{build.id}: #{ex}"
          end
226
227
        end
      end
228

229
      after_transition pending: :running do |build|
230
        build.ensure_metadata.update_timeout_state
231
      end
232
233
234
235

      after_transition running: any do |build|
        Ci::BuildRunnerSession.where(build: build).delete_all
      end
Douwe Maan's avatar
Douwe Maan committed
236
237
    end

238
    def ensure_metadata
Tomasz Maczukin's avatar
Tomasz Maczukin committed
239
      metadata || build_metadata(project: project)
Douwe Maan's avatar
Douwe Maan committed
240
241
    end

242
    def detailed_status(current_user)
243
244
245
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
Kamil Trzcinski's avatar
Kamil Trzcinski committed
246
247
    end

248
    def other_actions
249
      pipeline.manual_actions.where.not(name: name)
250
251
    end

252
253
254
255
256
    def pages_generator?
      Gitlab.config.pages.enabled &&
        self.name == 'pages'
    end

257
    def playable?
258
      action? && (manual? || scheduled? || retryable?)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
259
260
    end

Shinya Maeda's avatar
Shinya Maeda committed
261
    def schedulable?
262
      Feature.enabled?('ci_enable_scheduled_build', default_enabled: true) &&
263
        self.when == 'delayed' && options[:start_in].present?
Shinya Maeda's avatar
Shinya Maeda committed
264
265
    end

Shinya Maeda's avatar
Shinya Maeda committed
266
    def options_scheduled_at
Shinya Maeda's avatar
Shinya Maeda committed
267
      ChronicDuration.parse(options[:start_in])&.seconds&.from_now
Kamil Trzcinski's avatar
Kamil Trzcinski committed
268
269
    end

270
    def action?
271
      %w[manual delayed].include?(self.when)
272
273
    end

274
    # rubocop: disable CodeReuse/ServiceClass
275
    def play(current_user)
276
277
278
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
279
    end
280
    # rubocop: enable CodeReuse/ServiceClass
281

Kamil Trzcinski's avatar
Kamil Trzcinski committed
282
    def cancelable?
Jacopo's avatar
Jacopo committed
283
      active? || created?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
284
285
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
286
    def retryable?
287
      success? || failed? || canceled?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
288
    end
289
290
291
292
293
294
295
296

    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
297

298
299
    def latest?
      !retried?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
300
301
    end

302
    def expanded_environment_name
303
304
305
      return unless has_environment?

      strong_memoize(:expanded_environment_name) do
306
307
        ExpandVariables.expand(environment, simple_variables)
      end
308
309
    end

310
    def has_environment?
311
      environment.present?
312
313
    end

314
    def starts_environment?
315
      has_environment? && self.environment_action == 'start'
316
317
318
    end

    def stops_environment?
319
      has_environment? && self.environment_action == 'stop'
320
321
322
    end

    def environment_action
323
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
324
325
326
327
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
328
    end
329

330
331
    def depends_on_builds
      # Get builds of the same type
332
      latest_builds = self.pipeline.builds.latest
333
334
335
336
337

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

338
    def triggered_by?(current_user)
Shinya Maeda's avatar
Shinya Maeda committed
339
340
341
      user == current_user
    end

Nick Thomas's avatar
Nick Thomas committed
342
343
344
345
346
347
    # 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
Shinya Maeda's avatar
Shinya Maeda committed
348
    #   * First/Last Character is not a hyphen
Nick Thomas's avatar
Nick Thomas committed
349
    def ref_slug
vanadium23's avatar
vanadium23 committed
350
      Gitlab::Utils.slugify(ref.to_s)
Nick Thomas's avatar
Nick Thomas committed
351
352
    end

353
    ##
354
    # Variables in the environment name scope.
355
    #
356
357
    def scoped_variables(environment: expanded_environment_name)
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
358
359
360
361
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
362
        variables.concat(project.deployment_variables(environment: environment)) if environment
363
364
        variables.concat(yaml_variables)
        variables.concat(user_variables)
365
366
        variables.concat(secret_group_variables)
        variables.concat(secret_project_variables(environment: environment))
367
368
369
370
        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
371
    end
372

373
374
375
376
    ##
    # Variables that do not depend on the environment name.
    #
    def simple_variables
377
378
379
      strong_memoize(:simple_variables) do
        scoped_variables(environment: nil).to_runner_variables
      end
380
381
382
383
384
385
    end

    ##
    # All variables, including persisted environment variables.
    #
    def variables
386
387
388
      Gitlab::Ci::Variables::Collection.new
        .concat(persisted_variables)
        .concat(scoped_variables)
389
390
391
392
        .concat(persisted_environment_variables)
        .to_runner_variables
    end

393
394
395
396
397
    ##
    # 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
398
      scoped_variables.to_hash
399
400
    end

401
402
403
404
    def features
      { trace_sections: true }
    end

405
    def merge_request
Z.J. van de Weg's avatar
Z.J. van de Weg committed
406
      return @merge_request if defined?(@merge_request)
Z.J. van de Weg's avatar
Z.J. van de Weg committed
407

408
409
      @merge_request ||=
        begin
410
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
411
412
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z.J. van de Weg's avatar
Z.J. van de Weg committed
413
            .reorder(iid: :desc)
414
415

          merge_requests.find do |merge_request|
416
            merge_request.commit_shas.include?(pipeline.sha)
417
418
          end
        end
419
420
    end

Douwe Maan's avatar
Douwe Maan committed
421
    def repo_url
Kamil Trzcinski's avatar
Kamil Trzcinski committed
422
      auth = "gitlab-ci-token:#{ensure_token!}@"
423
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
424
425
        prefix + auth
      end
Douwe Maan's avatar
Douwe Maan committed
426
427
428
    end

    def allow_git_fetch
429
      project.build_allow_git_fetch
Douwe Maan's avatar
Douwe Maan committed
430
431
432
    end

    def update_coverage
433
      coverage = trace.extract_coverage(coverage_regex)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
434
      update(coverage: coverage) if coverage.present?
Douwe Maan's avatar
Douwe Maan committed
435
436
    end

437
    # rubocop: disable CodeReuse/ServiceClass
438
    def parse_trace_sections!
439
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
440
    end
441
    # rubocop: enable CodeReuse/ServiceClass
442

443
444
    def trace
      Gitlab::Ci::Trace.new(self)
445
446
    end

447
    def has_trace?
448
      trace.exist?
Tomasz Maczukin's avatar
Tomasz Maczukin committed
449
450
    end

451
452
    def has_job_artifacts?
      job_artifacts.any?
453
454
    end

Shinya Maeda's avatar
Shinya Maeda committed
455
456
457
458
    def has_old_trace?
      old_trace.present?
    end

459
460
    def trace=(data)
      raise NotImplementedError
Tomasz Maczukin's avatar
Tomasz Maczukin committed
461
462
    end

463
464
    def old_trace
      read_attribute(:trace)
465
466
    end

467
    def erase_old_trace!
468
      return unless has_old_trace?
Shinya Maeda's avatar
Shinya Maeda committed
469

470
      update_column(:trace, nil)
Douwe Maan's avatar
Douwe Maan committed
471
472
    end

473
474
475
476
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
477
    def valid_token?(token)
478
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
479
480
    end

481
482
483
484
    def has_tags?
      tag_list.any?
    end

485
    def any_runners_online?
486
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
487
488
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
489
    def stuck?
490
491
492
      pending? && !any_runners_online?
    end

493
    def execute_hooks
494
      return unless project
495

496
      build_data = Gitlab::DataBuilder::Build.build(self)
497
498
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
499
500
    end

501
502
503
504
    def browsable_artifacts?
      artifacts_metadata?
    end

505
    def artifacts_metadata_entry(path, **options)
506
      artifacts_metadata.open do |metadata_stream|
507
        metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
508
          metadata_stream,
509
510
          path,
          **options)
511

512
513
        metadata.to_entry
      end
514
515
    end

516
517
518
519
    # and use that for `ExpireBuildInstanceArtifactsWorker`?
    def erase_erasable_artifacts!
      job_artifacts.erasable.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
520
521
    end

522
523
524
    def erase(opts = {})
      return false unless erasable?

525
526
      job_artifacts.destroy_all # rubocop: disable DestroyAll
      erase_old_artifacts!
527
528
529
530
531
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
532
      complete? && (artifacts? || has_job_artifacts? || has_trace?)
533
534
535
536
537
538
    end

    def erased?
      !self.erased_at.nil?
    end

539
    def artifacts_expired?
540
      artifacts_expire_at && artifacts_expire_at < Time.now
541
542
    end

543
544
545
546
547
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
548
549
      self.artifacts_expire_at =
        if value
550
          ChronicDuration.parse(value)&.seconds&.from_now
551
        end
552
553
    end

554
    def has_expiring_artifacts?
Z.J. van de Weg's avatar
Z.J. van de Weg committed
555
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
556
557
    end

558
    def keep_artifacts!
559
      self.update(artifacts_expire_at: nil)
560
      self.job_artifacts.update_all(expire_at: nil)
561
562
    end

563
564
565
566
567
568
569
    def artifacts_file_for_type(type)
      file = job_artifacts.find_by(file_type: Ci::JobArtifact.file_types[type])&.file
      # TODO: to be removed once legacy artifacts is removed
      file ||= legacy_artifacts_file if type == :archive
      file
    end

570
    def coverage_regex
571
      super || project.try(:build_coverage_regex)
572
573
    end

574
575
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
576
577
    end

578
579
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
580
581
    end

582
    def user_variables
583
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
584
        break variables if user.blank?
585

586
587
588
589
590
        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
591
592
    end

593
594
595
596
597
598
599
    def secret_group_variables
      return [] unless project.group

      project.group.secret_variables_for(ref, project)
    end

    def secret_project_variables(environment: persisted_environment)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
600
601
602
      project.secret_variables_for(ref: ref, environment: environment)
    end

603
    def steps
Tomasz Maczukin's avatar
Tomasz Maczukin committed
604
605
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
606
607
608
    end

    def image
609
      Gitlab::Ci::Build::Image.from_image(self)
610
611
612
    end

    def services
613
      Gitlab::Ci::Build::Image.from_services(self)
614
615
616
    end

    def cache
Matija Čupić's avatar
Matija Čupić committed
617
618
619
620
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
621
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
622
      end
Matija Čupić's avatar
Matija Čupić committed
623
624

      [cache]
625
626
    end

627
    def credentials
628
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
629
630
    end

631
    def dependencies
632
633
      return [] if empty_dependencies?

634
635
      depended_jobs = depends_on_builds

636
      return depended_jobs unless options[:dependencies].present?
637

638
639
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
640
641
642
      end
    end

643
644
645
646
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

Kamil Trzciński's avatar
Kamil Trzciński committed
647
    def has_valid_build_dependencies?
Kamil Trzciński's avatar
Kamil Trzciński committed
648
      return true if Feature.enabled?('ci_disable_validates_dependencies')
649

Kamil Trzciński's avatar
Kamil Trzciński committed
650
      dependencies.all?(&:valid_dependency?)
651
652
    end

Kamil Trzciński's avatar
Kamil Trzciński committed
653
    def valid_dependency?
Shinya Maeda's avatar
Shinya Maeda committed
654
655
656
657
658
659
      return false if artifacts_expired?
      return false if erased?

      true
    end

660
661
662
663
664
665
666
667
    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

668
    def supported_runner?(features)
669
      runner_required_feature_names.all? do |feature_name|
Kamil Trzciński's avatar
Kamil Trzciński committed
670
        features&.dig(feature_name)
671
672
673
      end
    end

674
    def publishes_artifacts_reports?
675
      options&.dig(:artifacts, :reports)&.any?
676
677
    end

678
679
680
681
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
682
683
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
684
685
686
      trace
    end

687
    def serializable_hash(options = {})
James Lopez's avatar
James Lopez committed
688
      super(options).merge(when: read_attribute(:when))
689
690
    end

691
692
693
694
    def has_terminal?
      running? && runner_session_url.present?
    end

695
696
    def collect_test_reports!(test_reports)
      test_reports.get_suite(group_name).tap do |test_suite|
697
698
        each_report(Ci::JobArtifact::TEST_REPORT_FILE_TYPES) do |file_type, blob|
          Gitlab::Ci::Parsers::Test.fabricate!(file_type).parse!(blob, test_suite)
699
700
701
702
        end
      end
    end

703
704
705
706
707
708
709
710
711
712
713
714
715
    # 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

716
717
    private

718
719
720
721
722
723
724
    def erase_old_artifacts!
      # TODO: To be removed once we get rid of
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

725
726
727
728
729
730
731
732
733
734
    def successful_deployment_status
      if success? && last_deployment&.last?
        return :last
      elsif success? && last_deployment.present?
        return :out_of_date
      end

      :creating
    end

735
736
737
738
    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
739
740
741
742
        end
      end
    end

743
744
745
746
747
    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

748
    def update_artifacts_size
Kamil Trzcinski's avatar
Kamil Trzcinski committed
749
      self.artifacts_size = legacy_artifacts_file&.size
750
751
    end

752
    def erase_trace!
753
      trace.erase!
754
755
756
    end

    def update_erased!(user = nil)
757
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
758
759
    end

760
    def unscoped_project
Kamil Trzciński's avatar
Kamil Trzciński committed
761
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
762
763
    end

764
765
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

766
767
    def persisted_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
768
        break variables unless persisted?
769
770

        variables
771
          .concat(pipeline.persisted_variables)
772
          .append(key: 'CI_JOB_ID', value: id.to_s)
Kamil Trzciński's avatar
Kamil Trzciński committed
773
          .append(key: 'CI_JOB_URL', value: Gitlab::Routing.url_helpers.project_job_url(project, self))
774
775
776
777
778
779
          .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)
780
          .concat(deploy_token_variables)
781
782
783
      end
    end

784
    def predefined_variables
785
786
787
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
788
        variables.append(key: 'GITLAB_FEATURES', value: project.licensed_features.join(','))
789
790
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
791
792
793
        variables.append(key: 'CI_SERVER_VERSION_MAJOR', value: gitlab_version_info.major.to_s)
        variables.append(key: 'CI_SERVER_VERSION_MINOR', value: gitlab_version_info.minor.to_s)
        variables.append(key: 'CI_SERVER_VERSION_PATCH', value: gitlab_version_info.patch.to_s)
794
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab.revision)
795
796
797
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_COMMIT_SHA', value: sha)
798
        variables.append(key: 'CI_COMMIT_BEFORE_SHA', value: before_sha)
799
800
801
802
803
        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?
804
        variables.append(key: "CI_NODE_INDEX", value: self.options[:instance].to_s) if self.options&.include?(:instance)
805
        variables.append(key: "CI_NODE_TOTAL", value: (self.options&.dig(:parallel) || 1).to_s)
806
807
        variables.concat(legacy_variables)
      end
808
809
    end

810
811
812
813
    def gitlab_version_info
      @gitlab_version_info ||= Gitlab::VersionInfo.parse(Gitlab::VERSION)
    end

814
    def legacy_variables
815
816
817
818
819
820
821
822
823
824
825
      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
826
    end
827

828
829
    def persisted_environment_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
830
        break variables unless persisted? && persisted_environment.present?
831
832
833
834
835
836
837
838
839
840

        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

841
842
    def deploy_token_variables
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
843
844
        break variables unless gitlab_deploy_token

845
        variables.append(key: 'CI_DEPLOY_USER', value: gitlab_deploy_token.username)
846
        variables.append(key: 'CI_DEPLOY_PASSWORD', value: gitlab_deploy_token.token, public: false)
847
848
849
      end
    end

850
    def environment_url
851
      options&.dig(:environment, :url) || persisted_environment&.external_url
852
853
    end

854
855
    def build_attributes_from_config
      return {} unless pipeline.config_processor
856

857
858
      pipeline.config_processor.build_attributes(name)
    end
859

860
861
862
    def update_project_statistics_after_save
      update_project_statistics(read_attribute(:artifacts_size).to_i - artifacts_size_was.to_i)
    end
863

864
865
    def update_project_statistics_after_destroy
      update_project_statistics(-artifacts_size)
866
    end
867

868
869
870
871
872
873
    def update_project_statistics(difference)
      ProjectStatistics.increment_statistic(project_id, :build_artifacts_size, difference)
    end

    def project_destroyed?
      project.pending_delete?
874
    end
Douwe Maan's avatar
Douwe Maan committed
875
876
  end
end