build.rb 17.2 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
3
    include TokenAuthenticatable
4
    include AfterCommitQueue
R
Rémy Coutable 已提交
5
    include Presentable
6

7 8
    belongs_to :runner
    belongs_to :trigger_request
9
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
10

11
    has_many :deployments, as: :deployable
12
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
13

14 15 16 17
    # 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 已提交
18
        project: project
19 20 21
      )
    end

D
Douwe Maan 已提交
22
    serialize :options
23
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables
D
Douwe Maan 已提交
24

D
Douwe Maan 已提交
25 26
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
27
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
28
    validates :ref, presence: true
D
Douwe Maan 已提交
29 30

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
31
    scope :ignore_failures, ->() { where(allow_failure: false) }
L
Lin Jen-Shin 已提交
32
    scope :with_artifacts, ->() { where.not(artifacts_file: [nil, '']) }
33
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
34
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
35
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
36
    scope :manual_actions, ->() { where(when: :manual).relevant }
D
Douwe Maan 已提交
37

K
Kamil Trzcinski 已提交
38
    mount_uploader :artifacts_file, ArtifactUploader
39
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
40

D
Douwe Maan 已提交
41 42
    acts_as_taggable

43 44
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
45
    before_save :update_artifacts_size, if: :artifacts_file_changed?
46
    before_save :ensure_token
47
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
48

K
Kamil Trzcinski 已提交
49
    after_create :execute_hooks
M
Markus Koller 已提交
50 51
    after_save :update_project_statistics, if: :artifacts_size_changed?
    after_destroy :update_project_statistics
D
Douwe Maan 已提交
52 53 54 55 56 57

    class << self
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

58
      def retry(build, current_user)
59 60 61
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
62 63 64
      end
    end

65
    state_machine :status do
66 67
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
68 69
      end

70 71
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
72
          BuildQueueWorker.perform_async(id)
73 74 75
        end
      end

76
      after_transition pending: :running do |build|
77 78 79
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
80 81
      end

82
      after_transition any => [:success, :failed, :canceled] do |build|
83
        build.run_after_commit do
84
          BuildFinishedWorker.perform_async(id)
85
        end
D
Douwe Maan 已提交
86
      end
87

88
      after_transition any => [:success] do |build|
89 90
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
91 92
        end
      end
D
Douwe Maan 已提交
93 94
    end

95
    def detailed_status(current_user)
96 97 98
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
99 100
    end

101
    def other_actions
102
      pipeline.manual_actions.where.not(name: name)
103 104
    end

105
    def playable?
106 107
      project.builds_enabled? && has_commands? &&
        action? && manual?
K
Kamil Trzcinski 已提交
108 109
    end

110
    def action?
111 112 113 114 115
      self.when == 'manual'
    end

    def has_commands?
      commands.present?
116 117
    end

118
    def play(current_user)
119
      # Try to queue a current build
120
      if self.enqueue
K
Kamil Trzcinski 已提交
121 122
        self.update(user: current_user)
        self
123 124 125 126 127 128
      else
        # Otherwise we need to create a duplicate
        Ci::Build.retry(self, current_user)
      end
    end

K
Kamil Trzcinski 已提交
129 130 131 132
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
133
    def retryable?
134
      project.builds_enabled? && has_commands? &&
135
        (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
136 137 138
    end

    def retried?
139
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
140 141
    end

142
    def expanded_environment_name
143
      ExpandVariables.expand(environment, simple_variables) if environment
144 145
    end

146
    def has_environment?
147
      environment.present?
148 149
    end

150
    def starts_environment?
151
      has_environment? && self.environment_action == 'start'
152 153 154
    end

    def stops_environment?
155
      has_environment? && self.environment_action == 'stop'
156 157 158
    end

    def environment_action
159
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
160 161 162 163
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
164
    end
165

166 167
    def depends_on_builds
      # Get builds of the same type
168
      latest_builds = self.pipeline.builds.latest
169 170 171 172 173

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

174 175
    def trace_html(**args)
      trace_with_state(**args)[:html] || ''
176 177
    end

178
    def trace_with_state(state: nil, last_lines: nil)
L
Lin Jen-Shin 已提交
179
      trace_ansi = trace(last_lines: last_lines)
180 181
      if trace_ansi.present?
        Ci::Ansi2html.convert(trace_ansi, state)
L
Lin Jen-Shin 已提交
182 183 184
      else
        {}
      end
D
Douwe Maan 已提交
185 186 187
    end

    def timeout
K
Kamil Trzcinski 已提交
188
      project.build_timeout
D
Douwe Maan 已提交
189 190
    end

N
Nick Thomas 已提交
191 192 193 194 195 196 197 198 199 200 201
    # 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
    def ref_slug
      slugified = ref.to_s.downcase
      slugified.gsub(/[^a-z0-9]/, '-')[0..62]
    end

202 203
    # Variables whose value does not depend on other variables
    def simple_variables
204 205 206 207 208
      variables = predefined_variables
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
209
      variables += project.deployment_variables if has_environment?
210
      variables += yaml_variables
211
      variables += user_variables
212 213
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
214
      variables
D
Douwe Maan 已提交
215 216
    end

217 218 219 220 221 222 223
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
      variables += persisted_environment.predefined_variables if persisted_environment.present?
      variables
    end

224 225
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
K
Kamil Trzciński 已提交
226 227
                                   .where(source_branch: ref,
                                          source_project: pipeline.project)
228 229 230
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
231
        merge_request.commits_sha.include?(pipeline.sha)
232 233 234
      end
    end

D
Douwe Maan 已提交
235
    def repo_url
K
Kamil Trzcinski 已提交
236
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
237 238 239
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
240 241 242
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
243
      project.build_allow_git_fetch
D
Douwe Maan 已提交
244 245 246
    end

    def update_coverage
K
Kamil Trzcinski 已提交
247
      coverage = extract_coverage(trace, coverage_regex)
248
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
249 250 251
    end

    def extract_coverage(text, regex)
252
      return unless regex
D
Douwe Maan 已提交
253

254
      matches = text.scan(Regexp.new(regex)).last
D
Douwe Maan 已提交
255
      matches = matches.last if matches.is_a?(Array)
256 257 258 259
      coverage = matches.gsub(/\d+(\.\d+)?/).first

      if coverage.present?
        coverage.to_f
D
Douwe Maan 已提交
260
      end
261 262 263
    rescue
      # if bad regex or something goes wrong we dont want to interrupt transition
      # so we just silentrly ignore error for now
D
Douwe Maan 已提交
264 265
    end

266
    def has_trace_file?
T
Tomasz Maczukin 已提交
267
      File.exist?(path_to_trace) || has_old_trace_file?
268 269
    end

270 271
    def has_trace?
      raw_trace.present?
272 273
    end

274
    def raw_trace(last_lines: nil)
T
Tomasz Maczukin 已提交
275
      if File.exist?(trace_file_path)
276 277
        Gitlab::Ci::TraceReader.new(trace_file_path).
          read(last_lines: last_lines)
D
Douwe Maan 已提交
278 279 280 281 282
      else
        # backward compatibility
        read_attribute :trace
      end
    end
283

T
Tomasz Maczukin 已提交
284 285 286 287 288 289 290 291
    ##
    # Deprecated
    #
    # This is a hotfix for CI build data integrity, see #4246
    def has_old_trace_file?
      project.ci_id && File.exist?(old_path_to_trace)
    end

292
    def trace(last_lines: nil)
293
      hide_secrets(raw_trace(last_lines: last_lines))
294
    end
D
Douwe Maan 已提交
295

T
Tomasz Maczukin 已提交
296
    def trace_length
297
      if raw_trace
298
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
299
      else
300
        0
T
Tomasz Maczukin 已提交
301 302 303
      end
    end

D
Douwe Maan 已提交
304
    def trace=(trace)
305
      recreate_trace_dir
306
      trace = hide_secrets(trace)
307 308 309 310
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
311
      unless Dir.exist?(dir_to_trace)
312
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
313
      end
314 315
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
316

317
    def append_trace(trace_part, offset)
318
      recreate_trace_dir
319
      touch if needs_touch?
320

321 322
      trace_part = hide_secrets(trace_part)

323
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
324
      File.open(path_to_trace, 'ab') do |f|
325 326
        f.write(trace_part)
      end
D
Douwe Maan 已提交
327 328
    end

329 330 331 332
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

333 334 335 336 337 338 339 340
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

D
Douwe Maan 已提交
341 342
    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
343
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
344 345 346 347 348 349 350 351 352
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

    def path_to_trace
      "#{dir_to_trace}/#{id}.log"
    end

353 354 355
    ##
    # Deprecated
    #
356 357 358
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
359 360 361 362 363 364 365 366 367 368 369
    def old_dir_to_trace
      File.join(
        Settings.gitlab_ci.builds_path,
        created_at.utc.strftime("%Y_%m"),
        project.ci_id.to_s
      )
    end

    ##
    # Deprecated
    #
370 371 372
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
373 374 375 376
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

377 378 379 380 381 382 383 384 385 386 387
    ##
    # Deprecated
    #
    # This contains a hotfix for CI build data integrity, see #4246
    #
    # This method is used by `ArtifactUploader` to create a store_dir.
    # Warning: Uploader uses it after AND before file has been stored.
    #
    # This method returns old path to artifacts only if it already exists.
    #
    def artifacts_path
388 389 390 391 392 393 394
      # We need the project even if it's soft deleted, because whenever
      # we're really deleting the project, we'll also delete the builds,
      # and in order to delete the builds, we need to know where to find
      # the artifacts, which is depending on the data of the project.
      # We need to retain the project in this case.
      the_project = project || unscoped_project

395
      old = File.join(created_at.utc.strftime('%Y_%m'),
396
                      the_project.ci_id.to_s,
397 398 399
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
400
      return old if the_project.ci_id && File.directory?(old_store)
401 402 403

      File.join(
        created_at.utc.strftime('%Y_%m'),
404
        the_project.id.to_s,
405 406 407 408
        id.to_s
      )
    end

L
Lin Jen-Shin 已提交
409
    def valid_token?(token)
410
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
411 412
    end

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

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

K
Kamil Trzcinski 已提交
421
    def stuck?
422 423 424
      pending? && !any_runners_online?
    end

425
    def execute_hooks
426
      return unless project
427
      build_data = Gitlab::DataBuilder::Build.build(self)
K
Kamil Trzcinski 已提交
428 429
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
430
      PagesService.new(build_data).execute
J
Josh Frye 已提交
431
      project.running_or_pending_build_count(force: true)
432 433
    end

434
    def artifacts?
435
      !artifacts_expired? && artifacts_file.exists?
436 437
    end

438
    def artifacts_metadata?
439
      artifacts? && artifacts_metadata.exists?
440 441
    end

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

      metadata.to_entry
449 450
    end

451 452 453
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
454
      save
455 456
    end

457 458 459
    def erase(opts = {})
      return false unless erasable?

460
      erase_artifacts!
461 462 463 464 465 466 467 468 469 470 471 472
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

473
    def artifacts_expired?
474
      artifacts_expire_at && artifacts_expire_at < Time.now
475 476
    end

477 478 479 480 481
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
482 483
      self.artifacts_expire_at =
        if value
484
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
485
        end
486 487
    end

488 489 490 491
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

492
    def keep_artifacts!
493 494 495
      self.update(artifacts_expire_at: nil)
    end

496
    def coverage_regex
497
      super || project.try(:build_coverage_regex)
498 499
    end

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

504 505
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
506 507
    end

508 509 510 511 512 513 514 515 516
    def user_variables
      return [] if user.blank?

      [
        { key: 'GITLAB_USER_ID', value: user.id.to_s, public: true },
        { key: 'GITLAB_USER_EMAIL', value: user.email, public: true }
      ]
    end

517
    def steps
T
Tomasz Maczukin 已提交
518 519
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
520 521 522
    end

    def image
523
      Gitlab::Ci::Build::Image.from_image(self)
524 525 526
    end

    def services
527
      Gitlab::Ci::Build::Image.from_services(self)
528 529 530
    end

    def artifacts
531
      [options[:artifacts]]
532 533 534
    end

    def cache
535
      [options[:cache]]
536 537
    end

538
    def credentials
539
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
540 541
    end

T
Tomasz Maczukin 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    def dependencies
      depended_jobs = depends_on_builds

      return depended_jobs unless options[:dependencies] && !options[:dependencies].empty?

      selected = []
      depended_jobs.each do |job|
        options[:dependencies].each do |job_name|
          selected << job if job.name == job_name
        end
      end

      selected
    end

557 558
    private

L
Lin Jen-Shin 已提交
559
    def update_artifacts_size
560 561
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
562 563
                            else
                              nil
564
                            end
L
Lin Jen-Shin 已提交
565 566
    end

567 568 569 570 571
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
572
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
573 574
    end

575
    def unscoped_project
K
Kamil Trzciński 已提交
576
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
577 578
    end

579 580
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

581
    def predefined_variables
582 583 584
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
585 586 587 588 589 590 591
        { key: 'CI_SERVER_NAME', value: 'GitLab', public: true },
        { key: 'CI_SERVER_VERSION', value: Gitlab::VERSION, public: true },
        { key: 'CI_SERVER_REVISION', value: Gitlab::REVISION, public: true },
        { key: 'CI_JOB_ID', value: id.to_s, public: true },
        { key: 'CI_JOB_NAME', value: name, public: true },
        { key: 'CI_JOB_STAGE', value: stage, public: true },
        { key: 'CI_JOB_TOKEN', value: token, public: false },
Z
Z.J. van de Weg 已提交
592
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        { key: 'CI_COMMIT_REF_NAME', value: ref, public: true },
        { key: 'CI_COMMIT_REF_SLUG', value: ref_slug, public: true },
        { key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER, public: true },
        { key: 'CI_REGISTRY_PASSWORD', value: token, public: false },
        { key: 'CI_REPOSITORY_URL', value: repo_url, public: false }
      ]

      variables << { key: "CI_COMMIT_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_PIPELINE_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_JOB_MANUAL", value: 'true', public: true } if action?
      variables.concat(legacy_variables)
    end

    def legacy_variables
      variables = [
608 609 610 611 612
        { key: 'CI_BUILD_ID', value: id.to_s, public: true },
        { key: 'CI_BUILD_TOKEN', value: token, public: false },
        { key: 'CI_BUILD_REF', value: sha, public: true },
        { key: 'CI_BUILD_BEFORE_SHA', value: before_sha, public: true },
        { key: 'CI_BUILD_REF_NAME', value: ref, public: true },
N
Nick Thomas 已提交
613
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
614
        { key: 'CI_BUILD_NAME', value: name, public: true },
615
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
616
      ]
617 618 619 620

      variables << { key: "CI_BUILD_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_BUILD_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_BUILD_MANUAL", value: 'true', public: true } if action?
621 622
      variables
    end
623 624 625

    def build_attributes_from_config
      return {} unless pipeline.config_processor
626

627 628
      pipeline.config_processor.build_attributes(name)
    end
629 630

    def hide_secrets(trace)
631 632 633 634 635
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
636 637
      trace
    end
M
Markus Koller 已提交
638 639

    def update_project_statistics
640 641
      return unless project

M
Markus Koller 已提交
642 643
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
644 645
  end
end