build.rb 15.5 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
K
Kamil Trzcinski 已提交
66
      event :block do
67
        transition created: :blocked
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? && manual? &&
        (skipped? || blocked?)
K
Kamil Trzcinski 已提交
108 109
    end

110 111 112 113 114 115 116 117 118 119
    def manual?
      self.when == 'manual'
    end

    def barrier?
      manual? && !allow_failure?
    end

    def has_commands?
      commands.present?
120 121
    end

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

K
Kamil Trzcinski 已提交
133 134 135 136
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
137
    def retryable?
138
      project.builds_enabled? && has_commands? &&
139
        (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
140 141 142
    end

    def retried?
143
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
144 145
    end

146
    def expanded_environment_name
147
      ExpandVariables.expand(environment, simple_variables) if environment
148 149
    end

150
    def has_environment?
151
      environment.present?
152 153
    end

154
    def starts_environment?
155
      has_environment? && self.environment_action == 'start'
156 157 158
    end

    def stops_environment?
159
      has_environment? && self.environment_action == 'stop'
160 161 162
    end

    def environment_action
163
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
164 165 166 167
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
168
    end
169

170 171
    def depends_on_builds
      # Get builds of the same type
172
      latest_builds = self.pipeline.builds.latest
173 174 175 176 177

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

178 179
    def trace_html(**args)
      trace_with_state(**args)[:html] || ''
180 181
    end

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

    def timeout
K
Kamil Trzcinski 已提交
192
      project.build_timeout
D
Douwe Maan 已提交
193 194
    end

N
Nick Thomas 已提交
195 196 197 198 199 200 201 202 203 204 205
    # 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

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

221 222 223 224 225 226 227
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
      variables += persisted_environment.predefined_variables if persisted_environment.present?
      variables
    end

228 229
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
230
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
231 232 233
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
234
        merge_request.commits_sha.include?(pipeline.sha)
235 236 237
      end
    end

D
Douwe Maan 已提交
238
    def project_id
K
Kamil Trzcinski 已提交
239
      gl_project_id
D
Douwe Maan 已提交
240 241 242
    end

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
250
      project.build_allow_git_fetch
D
Douwe Maan 已提交
251 252 253
    end

    def update_coverage
K
Kamil Trzcinski 已提交
254
      coverage = extract_coverage(trace, coverage_regex)
255
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
256 257 258
    end

    def extract_coverage(text, regex)
259
      return unless regex
D
Douwe Maan 已提交
260

261
      matches = text.scan(Regexp.new(regex)).last
D
Douwe Maan 已提交
262
      matches = matches.last if matches.is_a?(Array)
263 264 265 266
      coverage = matches.gsub(/\d+(\.\d+)?/).first

      if coverage.present?
        coverage.to_f
D
Douwe Maan 已提交
267
      end
268 269 270
    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 已提交
271 272
    end

273
    def has_trace_file?
T
Tomasz Maczukin 已提交
274
      File.exist?(path_to_trace) || has_old_trace_file?
275 276
    end

277 278
    def has_trace?
      raw_trace.present?
279 280
    end

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

T
Tomasz Maczukin 已提交
291 292 293 294 295 296 297 298
    ##
    # 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

299
    def trace(last_lines: nil)
300
      hide_secrets(raw_trace(last_lines: last_lines))
301
    end
D
Douwe Maan 已提交
302

T
Tomasz Maczukin 已提交
303
    def trace_length
304
      if raw_trace
305
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
306
      else
307
        0
T
Tomasz Maczukin 已提交
308 309 310
      end
    end

D
Douwe Maan 已提交
311
    def trace=(trace)
312
      recreate_trace_dir
313
      trace = hide_secrets(trace)
314 315 316 317
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
318
      unless Dir.exist?(dir_to_trace)
319
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
320
      end
321 322
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
323

324
    def append_trace(trace_part, offset)
325
      recreate_trace_dir
326
      touch if needs_touch?
327

328 329
      trace_part = hide_secrets(trace_part)

330
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
331
      File.open(path_to_trace, 'ab') do |f|
332 333
        f.write(trace_part)
      end
D
Douwe Maan 已提交
334 335
    end

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

340 341 342 343 344 345 346 347
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

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

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

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

384 385 386 387 388 389 390 391 392 393 394
    ##
    # 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
395 396 397 398 399 400 401
      # 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

402
      old = File.join(created_at.utc.strftime('%Y_%m'),
403
                      the_project.ci_id.to_s,
404 405 406
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
407
      return old if the_project.ci_id && File.directory?(old_store)
408 409 410

      File.join(
        created_at.utc.strftime('%Y_%m'),
411
        the_project.id.to_s,
412 413 414 415
        id.to_s
      )
    end

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

420 421 422 423
    def has_tags?
      tag_list.any?
    end

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

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

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

441
    def artifacts?
442
      !artifacts_expired? && artifacts_file.exists?
443 444
    end

445
    def artifacts_metadata?
446
      artifacts? && artifacts_metadata.exists?
447 448
    end

449
    def artifacts_metadata_entry(path, **options)
450 451 452 453 454 455
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
456 457
    end

458 459 460
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
461
      save
462 463
    end

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

467
      erase_artifacts!
468 469 470 471 472 473 474 475 476 477 478 479
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

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

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

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

495 496 497 498
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

499
    def keep_artifacts!
500 501 502
      self.update(artifacts_expire_at: nil)
    end

503
    def coverage_regex
504
      super || project.try(:build_coverage_regex)
505 506
    end

507 508
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
509 510
    end

511 512
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
513 514
    end

515 516 517 518 519 520 521 522 523
    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

524
    def credentials
525
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
526 527
    end

528 529
    private

L
Lin Jen-Shin 已提交
530
    def update_artifacts_size
531 532
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
533 534
                            else
                              nil
535
                            end
L
Lin Jen-Shin 已提交
536 537
    end

538 539 540 541 542
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
543
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
544 545
    end

546 547 548 549
    def unscoped_project
      @unscoped_project ||= Project.unscoped.find_by(id: gl_project_id)
    end

550
    def predefined_variables
551 552 553 554 555 556 557 558
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
        { 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 已提交
559
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
560 561 562 563 564 565
        { key: 'CI_BUILD_NAME', value: name, public: true },
        { key: 'CI_BUILD_STAGE', value: stage, public: true },
        { 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 }
      ]
566 567
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
568
      variables << { key: 'CI_BUILD_MANUAL', value: 'true', public: true } if manual?
569 570
      variables
    end
571 572 573

    def build_attributes_from_config
      return {} unless pipeline.config_processor
574

575 576
      pipeline.config_processor.build_attributes(name)
    end
577 578

    def hide_secrets(trace)
579 580 581 582 583
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
584 585
      trace
    end
M
Markus Koller 已提交
586 587

    def update_project_statistics
588 589
      return unless project

M
Markus Koller 已提交
590 591
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
592 593
  end
end