build.rb 15.6 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 25

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

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

K
Kamil Trzcinski 已提交
36
    mount_uploader :artifacts_file, ArtifactUploader
37
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
38

D
Douwe Maan 已提交
39 40
    acts_as_taggable

41 42
    add_authentication_token_field :token

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

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

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

      def create_from(build)
        new_build = build.dup
K
Kamil Trzcinski 已提交
58
        new_build.status = 'pending'
D
Douwe Maan 已提交
59
        new_build.runner_id = nil
K
Kamil Trzcinski 已提交
60
        new_build.trigger_request_id = nil
61
        new_build.token = nil
D
Douwe Maan 已提交
62 63 64
        new_build.save
      end

65
      def retry(build, current_user)
66 67 68
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
69 70 71
      end
    end

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

79
      after_transition pending: :running do |build|
80 81 82
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
83 84
      end

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

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

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

104 105 106 107
    def manual?
      self.when == 'manual'
    end

108
    def other_actions
109
      pipeline.manual_actions.where.not(name: name)
110 111
    end

112
    def playable?
113
      project.builds_enabled? && commands.present? && manual? && skipped?
114 115
    end

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

K
Kamil Trzcinski 已提交
127 128 129 130
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
131
    def retryable?
132
      project.builds_enabled? && commands.present? &&
133
        (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
134 135 136
    end

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

140
    def expanded_environment_name
141
      ExpandVariables.expand(environment, simple_variables) if environment
142 143
    end

144
    def has_environment?
145
      environment.present?
146 147
    end

148
    def starts_environment?
149
      has_environment? && self.environment_action == 'start'
150 151 152
    end

    def stops_environment?
153
      has_environment? && self.environment_action == 'stop'
154 155 156
    end

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

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
162
    end
163

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

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

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

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

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

N
Nick Thomas 已提交
189 190 191 192 193 194 195 196 197 198 199
    # 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

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

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

222
    def merge_request
223 224 225
      merge_requests = MergeRequest.includes(:merge_request_diff)
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
                                   .reorder(iid: :asc)
226 227

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

D
Douwe Maan 已提交
232
    def project_id
K
Kamil Trzcinski 已提交
233
      gl_project_id
D
Douwe Maan 已提交
234 235
    end

D
Douwe Maan 已提交
236
    delegate :name, to: :project, prefix: true
D
Douwe Maan 已提交
237 238

    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 487 488
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        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 credentials
521
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
522 523
    end

524 525
    private

L
Lin Jen-Shin 已提交
526
    def update_artifacts_size
527 528
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
529 530
                            else
                              nil
531
                            end
L
Lin Jen-Shin 已提交
532 533
    end

534 535 536 537 538
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
539
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
540 541
    end

542 543 544 545
    def unscoped_project
      @unscoped_project ||= Project.unscoped.find_by(id: gl_project_id)
    end

546
    def predefined_variables
547 548 549 550 551 552 553 554
      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 已提交
555
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
556 557 558 559 560 561
        { 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 }
      ]
562 563
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
564
      variables << { key: 'CI_BUILD_MANUAL', value: 'true', public: true } if manual?
565 566
      variables
    end
567 568 569

    def build_attributes_from_config
      return {} unless pipeline.config_processor
570

571 572
      pipeline.config_processor.build_attributes(name)
    end
573 574

    def hide_secrets(trace)
575 576 577 578 579
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
580 581
      trace
    end
M
Markus Koller 已提交
582 583

    def update_project_statistics
584 585
      return unless project

M
Markus Koller 已提交
586 587
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
588 589
  end
end