build.rb 16.9 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 18 19 20 21
    # 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,
        project_id: gl_project_id
      )
    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)
226
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
227 228 229
                                   .reorder(iid: :asc)

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

D
Douwe Maan 已提交
234
    def project_id
K
Kamil Trzcinski 已提交
235
      gl_project_id
D
Douwe Maan 已提交
236 237 238
    end

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
246
      project.build_allow_git_fetch
D
Douwe Maan 已提交
247 248 249
    end

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

    def extract_coverage(text, regex)
255
      return unless regex
D
Douwe Maan 已提交
256

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

      if coverage.present?
        coverage.to_f
D
Douwe Maan 已提交
263
      end
264 265 266
    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 已提交
267 268
    end

269
    def has_trace_file?
T
Tomasz Maczukin 已提交
270
      File.exist?(path_to_trace) || has_old_trace_file?
271 272
    end

273 274
    def has_trace?
      raw_trace.present?
275 276
    end

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

T
Tomasz Maczukin 已提交
287 288 289 290 291 292 293 294
    ##
    # 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

295
    def trace(last_lines: nil)
296
      hide_secrets(raw_trace(last_lines: last_lines))
297
    end
D
Douwe Maan 已提交
298

T
Tomasz Maczukin 已提交
299
    def trace_length
300
      if raw_trace
301
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
302
      else
303
        0
T
Tomasz Maczukin 已提交
304 305 306
      end
    end

D
Douwe Maan 已提交
307
    def trace=(trace)
308
      recreate_trace_dir
309
      trace = hide_secrets(trace)
310 311 312 313
      File.write(path_to_trace, trace)
    end

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

320
    def append_trace(trace_part, offset)
321
      recreate_trace_dir
322
      touch if needs_touch?
323

324 325
      trace_part = hide_secrets(trace_part)

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

332 333 334 335
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

336 337 338 339 340 341 342 343
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

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

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

356 357 358
    ##
    # Deprecated
    #
359 360 361
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
362 363 364 365 366 367 368 369 370 371 372
    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
    #
373 374 375
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
376 377 378 379
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

380 381 382 383 384 385 386 387 388 389 390
    ##
    # 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
391 392 393 394 395 396 397
      # 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

398
      old = File.join(created_at.utc.strftime('%Y_%m'),
399
                      the_project.ci_id.to_s,
400 401 402
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
403
      return old if the_project.ci_id && File.directory?(old_store)
404 405 406

      File.join(
        created_at.utc.strftime('%Y_%m'),
407
        the_project.id.to_s,
408 409 410 411
        id.to_s
      )
    end

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

416 417 418 419
    def has_tags?
      tag_list.any?
    end

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

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

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

437
    def artifacts?
438
      !artifacts_expired? && artifacts_file.exists?
439 440
    end

441
    def artifacts_metadata?
442
      artifacts? && artifacts_metadata.exists?
443 444
    end

445
    def artifacts_metadata_entry(path, **options)
446 447 448 449 450 451
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
452 453
    end

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

460 461 462
    def erase(opts = {})
      return false unless erasable?

463
      erase_artifacts!
464 465 466 467 468 469 470 471 472 473 474 475
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

476
    def artifacts_expired?
477
      artifacts_expire_at && artifacts_expire_at < Time.now
478 479
    end

480 481 482 483 484
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

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

491 492 493 494
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

495
    def keep_artifacts!
496 497 498
      self.update(artifacts_expire_at: nil)
    end

499
    def coverage_regex
500
      super || project.try(:build_coverage_regex)
501 502
    end

503 504
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
505 506
    end

507 508
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
509 510
    end

511 512 513 514 515 516 517 518 519
    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

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

    def image
526
      Gitlab::Ci::Build::Image.from_image(self)
527 528 529
    end

    def services
530
      Gitlab::Ci::Build::Image.from_services(self)
531 532 533
    end

    def artifacts
534
      [options[:artifacts]]
535 536 537
    end

    def cache
538
      [options[:cache]]
539 540
    end

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

545 546
    private

L
Lin Jen-Shin 已提交
547
    def update_artifacts_size
548 549
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
550 551
                            else
                              nil
552
                            end
L
Lin Jen-Shin 已提交
553 554
    end

555 556 557 558 559
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
560
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
561 562
    end

563 564 565 566
    def unscoped_project
      @unscoped_project ||= Project.unscoped.find_by(id: gl_project_id)
    end

567 568
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

569
    def predefined_variables
570 571 572
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
573 574 575 576 577 578 579
        { 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 已提交
580
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        { 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 = [
596 597 598 599 600
        { 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 已提交
601
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
602
        { key: 'CI_BUILD_NAME', value: name, public: true },
603
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
604
      ]
605 606 607 608

      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?
609 610
      variables
    end
611 612 613

    def build_attributes_from_config
      return {} unless pipeline.config_processor
614

615 616
      pipeline.config_processor.build_attributes(name)
    end
617 618

    def hide_secrets(trace)
619 620 621 622 623
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
624 625
      trace
    end
M
Markus Koller 已提交
626 627

    def update_project_statistics
628 629
      return unless project

M
Markus Koller 已提交
630 631
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
632 633
  end
end