build.rb 18.1 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
R
Rémy Coutable 已提交
6
    include Presentable
S
Shinya Maeda 已提交
7
    include Importable
8

9 10
    MissingDependenciesError = Class.new(StandardError)

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
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
19
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
20

Z
Zeger-Jan van de Weg 已提交
21
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
22 23
    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 已提交
24
    has_one :job_artifacts_trace, -> { where(file_type: Ci::JobArtifact.file_types[:trace]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
25

26 27 28 29
    # The "environment" field for builds is a String, and is the unexpanded name
    def persisted_environment
      @persisted_environment ||= Environment.find_by(
        name: expanded_environment_name,
K
Kamil Trzciński 已提交
30
        project: project
31 32 33
      )
    end

34 35
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
36

D
Douwe Maan 已提交
37 38
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
39
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
40
    validates :ref, presence: true
D
Douwe Maan 已提交
41 42

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
43
    scope :ignore_failures, ->() { where(allow_failure: false) }
44
    scope :with_artifacts, ->() do
45 46
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id'))
47
    end
48 49
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
50
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
51
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
52
    scope :ref_protected, -> { where(protected: true) }
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    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

73 74
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
75

D
Douwe Maan 已提交
76 77
    acts_as_taggable

78 79
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
80
    before_save :update_artifacts_size, if: :artifacts_file_changed?
81
    before_save :ensure_token
82
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
83

84
    after_create unless: :importing? do |build|
85
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
86 87
    end

88 89
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy
D
Douwe Maan 已提交
90 91

    class << self
92 93 94 95 96 97
      # 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 已提交
98 99 100 101
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

102
      def retry(build, current_user)
103 104 105
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
106 107 108
      end
    end

109
    state_machine :status do
110 111
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
112 113
      end

114 115
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
116
          BuildQueueWorker.perform_async(id)
117 118 119
        end
      end

120
      after_transition pending: :running do |build|
121 122 123
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
124 125
      end

126
      after_transition any => [:success, :failed, :canceled] do |build|
127
        build.run_after_commit do
128
          BuildFinishedWorker.perform_async(id)
129
        end
D
Douwe Maan 已提交
130
      end
131

132
      after_transition any => [:success] do |build|
133 134
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
135 136
        end
      end
137

138
      before_transition any => [:failed] do |build|
139
        next unless build.project
140
        next if build.retries_max.zero?
141

142 143
        if build.retries_count < build.retries_max
          Ci::Build.retry(build, build.user)
144 145
        end
      end
146 147

      before_transition any => [:running] do |build|
148
        build.validates_dependencies! unless Feature.enabled?('ci_disable_validates_dependencies')
149
      end
D
Douwe Maan 已提交
150 151
    end

152
    def detailed_status(current_user)
153 154 155
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
156 157
    end

158
    def other_actions
159
      pipeline.manual_actions.where.not(name: name)
160 161
    end

162
    def playable?
163
      action? && (manual? || complete?)
K
Kamil Trzcinski 已提交
164 165
    end

166
    def action?
167 168 169
      self.when == 'manual'
    end

170
    def play(current_user)
171 172 173
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
174 175
    end

K
Kamil Trzcinski 已提交
176 177 178 179
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
180
    def retryable?
181
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
182
    end
183 184 185 186 187 188 189 190

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

192 193
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
194 195
    end

196
    def expanded_environment_name
197
      ExpandVariables.expand(environment, simple_variables) if environment
198 199
    end

200
    def has_environment?
201
      environment.present?
202 203
    end

204
    def starts_environment?
205
      has_environment? && self.environment_action == 'start'
206 207 208
    end

    def stops_environment?
209
      has_environment? && self.environment_action == 'stop'
210 211 212
    end

    def environment_action
213
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
214 215 216 217
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
218
    end
219

220 221
    def depends_on_builds
      # Get builds of the same type
222
      latest_builds = self.pipeline.builds.latest
223 224 225 226 227

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

D
Douwe Maan 已提交
228
    def timeout
K
Kamil Trzcinski 已提交
229
      project.build_timeout
D
Douwe Maan 已提交
230 231
    end

232
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
233 234 235
      user == current_user
    end

N
Nick Thomas 已提交
236 237 238 239 240 241
    # 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 已提交
242
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
243
    def ref_slug
V
vanadium23 已提交
244
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
245 246
    end

247
    # Variables whose value does not depend on environment
248
    def simple_variables
L
Lin Jen-Shin 已提交
249 250 251 252 253 254
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
255 256 257 258 259
      collection = Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.concat(predefined_variables)
        variables.concat(project.predefined_variables)
        variables.concat(pipeline.predefined_variables)
        variables.concat(runner.predefined_variables) if runner
260
        variables.concat(project.deployment_variables(environment: environment)) if has_environment?
261 262
        variables.concat(yaml_variables)
        variables.concat(user_variables)
263
        variables.concat(project.group.secret_variables_for(ref, project)) if project.group
264 265 266 267 268 269 270 271
        variables.concat(secret_variables(environment: environment))
        variables.concat(trigger_request.user_variables) if trigger_request
        variables.concat(pipeline.variables)
        variables.concat(pipeline.pipeline_schedule.job_variables) if pipeline.pipeline_schedule
        variables.concat(persisted_environment_variables) if environment
      end

      collection.to_runner_variables
272 273
    end

274 275 276 277
    def features
      { trace_sections: true }
    end

278
    def merge_request
Z
Z.J. van de Weg 已提交
279
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
280

281 282
      @merge_request ||=
        begin
283
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
284 285
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
286
            .reorder(iid: :desc)
287 288

          merge_requests.find do |merge_request|
289
            merge_request.commit_shas.include?(pipeline.sha)
290 291
          end
        end
292 293
    end

D
Douwe Maan 已提交
294
    def repo_url
K
Kamil Trzcinski 已提交
295
      auth = "gitlab-ci-token:#{ensure_token!}@"
296
      project.http_url_to_repo.sub(%r{^https?://}) do |prefix|
K
Kamil Trzcinski 已提交
297 298
        prefix + auth
      end
D
Douwe Maan 已提交
299 300 301
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
302
      project.build_allow_git_fetch
D
Douwe Maan 已提交
303 304 305
    end

    def update_coverage
306
      coverage = trace.extract_coverage(coverage_regex)
307
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
308 309
    end

310
    def parse_trace_sections!
311
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
312 313
    end

314 315
    def trace
      Gitlab::Ci::Trace.new(self)
316 317
    end

318
    def has_trace?
319
      trace.exist?
T
Tomasz Maczukin 已提交
320 321
    end

322 323
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
324 325
    end

326 327
    def old_trace
      read_attribute(:trace)
328 329
    end

330 331 332
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
333 334
    end

335 336 337 338
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
339
    def valid_token?(token)
340
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
341 342
    end

343 344 345 346
    def has_tags?
      tag_list.any?
    end

347
    def any_runners_online?
348
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
349 350
    end

K
Kamil Trzcinski 已提交
351
    def stuck?
352 353 354
      pending? && !any_runners_online?
    end

355
    def execute_hooks
356
      return unless project
357

358
      build_data = Gitlab::DataBuilder::Build.build(self)
359 360
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
361
      PagesService.new(build_data).execute
J
Josh Frye 已提交
362
      project.running_or_pending_build_count(force: true)
363 364
    end

365
    def artifacts_metadata_entry(path, **options)
366 367 368 369 370 371
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
372 373
    end

374 375 376
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
377
      save
378 379
    end

380 381 382
    def erase(opts = {})
      return false unless erasable?

383
      erase_artifacts!
384 385 386 387 388 389 390 391 392 393 394 395
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

396
    def artifacts_expired?
397
      artifacts_expire_at && artifacts_expire_at < Time.now
398 399
    end

400 401 402 403 404
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
405 406
      self.artifacts_expire_at =
        if value
407
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
408
        end
409 410
    end

411
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
412
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
413 414
    end

415
    def keep_artifacts!
416
      self.update(artifacts_expire_at: nil)
417
      self.job_artifacts.update_all(expire_at: nil)
418 419
    end

420
    def coverage_regex
421
      super || project.try(:build_coverage_regex)
422 423
    end

424 425
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
426 427
    end

428 429
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
430 431
    end

432
    def user_variables
433 434
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        return variables if user.blank?
435

436 437 438 439 440
        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
441 442
    end

L
Lin Jen-Shin 已提交
443 444 445 446 447
    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

448
    def steps
T
Tomasz Maczukin 已提交
449 450
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
451 452 453
    end

    def image
454
      Gitlab::Ci::Build::Image.from_image(self)
455 456 457
    end

    def services
458
      Gitlab::Ci::Build::Image.from_services(self)
459 460
    end

461
    def artifacts
462
      [options[:artifacts]]
463 464 465
    end

    def cache
M
Matija Čupić 已提交
466 467 468 469
      cache = options[:cache]

      if cache && project.jobs_cache_index
        cache = cache.merge(
470
          key: "#{cache[:key]}-#{project.jobs_cache_index}")
471
      end
M
Matija Čupić 已提交
472 473

      [cache]
474 475
    end

476
    def credentials
477
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
478 479
    end

T
Tomasz Maczukin 已提交
480
    def dependencies
481 482
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
483 484
      depended_jobs = depends_on_builds

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

487 488
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
489 490 491
      end
    end

492 493 494 495
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

496
    def validates_dependencies!
497 498
      dependencies.each do |dependency|
        raise MissingDependenciesError unless dependency.valid_dependency?
499
      end
500 501
    end

S
Shinya Maeda 已提交
502 503 504 505 506 507 508
    def valid_dependency?
      return false if artifacts_expired?
      return false if erased?

      true
    end

509 510 511 512
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
513 514
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
515 516 517
      trace
    end

518
    def serializable_hash(options = {})
J
James Lopez 已提交
519
      super(options).merge(when: read_attribute(:when))
520 521
    end

522 523
    private

L
Lin Jen-Shin 已提交
524
    def update_artifacts_size
K
Kamil Trzcinski 已提交
525
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
526 527
    end

528
    def erase_trace!
529
      trace.erase!
530 531 532
    end

    def update_erased!(user = nil)
533
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
534 535
    end

536
    def unscoped_project
K
Kamil Trzciński 已提交
537
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
538 539
    end

540 541
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

542
    def predefined_variables
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI', value: 'true')
        variables.append(key: 'GITLAB_CI', value: 'true')
        variables.append(key: 'GITLAB_FEATURES', value: project.namespace.features.join(','))
        variables.append(key: 'CI_SERVER_NAME', value: 'GitLab')
        variables.append(key: 'CI_SERVER_VERSION', value: Gitlab::VERSION)
        variables.append(key: 'CI_SERVER_REVISION', value: Gitlab::REVISION)
        variables.append(key: 'CI_JOB_ID', value: id.to_s)
        variables.append(key: 'CI_JOB_NAME', value: name)
        variables.append(key: 'CI_JOB_STAGE', value: stage)
        variables.append(key: 'CI_JOB_TOKEN', value: token, public: false)
        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_REGISTRY_USER', value: CI_REGISTRY_USER)
        variables.append(key: 'CI_REGISTRY_PASSWORD', value: token, public: false)
        variables.append(key: 'CI_REPOSITORY_URL', value: repo_url, public: false)
        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
565 566
    end

567
    def persisted_environment_variables
568 569
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        return variables unless persisted_environment
L
Lin Jen-Shin 已提交
570

571
        variables.concat(persisted_environment.predefined_variables)
L
Lin Jen-Shin 已提交
572

573 574 575 576 577
        # 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
578 579
    end

580
    def legacy_variables
581 582 583 584 585 586 587 588 589 590 591 592 593
      Gitlab::Ci::Variables::Collection.new.tap do |variables|
        variables.append(key: 'CI_BUILD_ID', value: id.to_s)
        variables.append(key: 'CI_BUILD_TOKEN', value: token, public: false)
        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
594
    end
595

596
    def environment_url
597
      options&.dig(:environment, :url) || persisted_environment&.external_url
598 599
    end

600 601
    def build_attributes_from_config
      return {} unless pipeline.config_processor
602

603 604
      pipeline.config_processor.build_attributes(name)
    end
605

606 607 608 609 610
    def update_project_statistics
      return unless project

      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
611 612 613 614 615 616

    def update_project_statistics_after_save
      if previous_changes.include?('artifacts_size')
        update_project_statistics
      end
    end
D
Douwe Maan 已提交
617 618
  end
end