build.rb 14.1 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
3
    include TokenAuthenticatable
4
    include AfterCommitQueue
5

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

10 11
    has_many :deployments, as: :deployable

D
Douwe Maan 已提交
12
    serialize :options
13
    serialize :yaml_variables
D
Douwe Maan 已提交
14 15

    validates :coverage, numericality: true, allow_blank: true
K
Kamil Trzcinski 已提交
16
    validates_presence_of :ref
D
Douwe Maan 已提交
17 18

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

K
Kamil Trzcinski 已提交
26
    mount_uploader :artifacts_file, ArtifactUploader
27
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
28

D
Douwe Maan 已提交
29 30
    acts_as_taggable

31 32
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
33
    before_save :update_artifacts_size, if: :artifacts_file_changed?
34
    before_save :ensure_token
G
Grzegorz Bizon 已提交
35 36
    before_destroy { project }

K
Kamil Trzcinski 已提交
37
    after_create :execute_hooks
D
Douwe Maan 已提交
38 39 40 41 42 43 44 45

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

      def create_from(build)
        new_build = build.dup
K
Kamil Trzcinski 已提交
46
        new_build.status = 'pending'
D
Douwe Maan 已提交
47
        new_build.runner_id = nil
K
Kamil Trzcinski 已提交
48
        new_build.trigger_request_id = nil
49
        new_build.token = nil
D
Douwe Maan 已提交
50 51 52
        new_build.save
      end

53
      def retry(build, user = nil)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        new_build = Ci::Build.create(
          ref: build.ref,
          tag: build.tag,
          options: build.options,
          commands: build.commands,
          tag_list: build.tag_list,
          project: build.project,
          pipeline: build.pipeline,
          name: build.name,
          allow_failure: build.allow_failure,
          stage: build.stage,
          stage_idx: build.stage_idx,
          trigger_request: build.trigger_request,
          yaml_variables: build.yaml_variables,
          when: build.when,
          user: user,
          environment: build.environment,
71
          status_event: 'enqueue'
72
        )
73 74 75 76 77

        MergeRequests::AddTodoWhenBuildFailsService
          .new(build.project, nil)
          .close(new_build)

78
        build.pipeline.mark_as_processable_after_stage(build.stage_idx)
D
Douwe Maan 已提交
79 80 81 82
        new_build
      end
    end

83
    state_machine :status do
84
      after_transition pending: :running do |build|
85 86 87
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
88 89
      end

90
      after_transition any => [:success, :failed, :canceled] do |build|
91
        build.run_after_commit do
92
          BuildFinishedWorker.perform_async(id)
93
        end
D
Douwe Maan 已提交
94
      end
95

96
      after_transition any => [:success] do |build|
97 98
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
99 100
        end
      end
D
Douwe Maan 已提交
101 102
    end

K
Kamil Trzcinski 已提交
103 104 105 106
    def detailed_status
      Gitlab::Ci::Status::Build::Factory.new(self).fabricate!
    end

107 108 109 110
    def manual?
      self.when == 'manual'
    end

111
    def other_actions
112
      pipeline.manual_actions.where.not(name: name)
113 114
    end

115
    def playable?
116
      project.builds_enabled? && commands.present? && manual? && skipped?
117 118 119
    end

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

K
Kamil Trzcinski 已提交
130
    def retryable?
131
      project.builds_enabled? && commands.present? && complete?
K
Kamil Trzcinski 已提交
132 133 134
    end

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

138 139 140 141
    def expanded_environment_name
      ExpandVariables.expand(environment, variables) if environment
    end

142 143 144 145
    def has_environment?
      self.environment.present?
    end

146
    def starts_environment?
147
      has_environment? && self.environment_action == 'start'
148 149 150
    end

    def stops_environment?
151
      has_environment? && self.environment_action == 'stop'
152 153 154 155 156 157 158 159
    end

    def environment_action
      self.options.fetch(:environment, {}).fetch(:action, 'start')
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
160
    end
161

162
    def last_deployment
163
      deployments.last
164 165
    end

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 191
    end

    def variables
192 193 194 195 196 197
      variables = predefined_variables
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
      variables += yaml_variables
198
      variables += user_variables
199 200
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
201
      variables
D
Douwe Maan 已提交
202 203
    end

204 205
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
206
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
207 208 209
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
210
        merge_request.commits_sha.include?(pipeline.sha)
211 212 213
      end
    end

D
Douwe Maan 已提交
214
    def project_id
215
      pipeline.project_id
D
Douwe Maan 已提交
216 217 218 219 220 221 222
    end

    def project_name
      project.name
    end

    def repo_url
K
Kamil Trzcinski 已提交
223
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
224 225 226
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
227 228 229
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
230
      project.build_allow_git_fetch
D
Douwe Maan 已提交
231 232 233
    end

    def update_coverage
234
      return unless project
K
Kamil Trzcinski 已提交
235 236 237
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
D
Douwe Maan 已提交
238 239 240 241 242 243 244 245

      if coverage.is_a? Numeric
        update_attributes(coverage: coverage)
      end
    end

    def extract_coverage(text, regex)
      begin
J
Jared Szechy 已提交
246 247
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
D
Douwe Maan 已提交
248 249 250 251 252
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
G
Guilherme Garnier 已提交
253
      rescue
D
Douwe Maan 已提交
254 255 256 257 258
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

259
    def has_trace_file?
T
Tomasz Maczukin 已提交
260
      File.exist?(path_to_trace) || has_old_trace_file?
261 262
    end

263 264
    def has_trace?
      raw_trace.present?
265 266
    end

267
    def raw_trace(last_lines: nil)
T
Tomasz Maczukin 已提交
268
      if File.exist?(trace_file_path)
269 270
        Gitlab::Ci::TraceReader.new(trace_file_path).
          read(last_lines: last_lines)
D
Douwe Maan 已提交
271 272 273 274 275
      else
        # backward compatibility
        read_attribute :trace
      end
    end
276

T
Tomasz Maczukin 已提交
277 278 279 280 281 282 283 284
    ##
    # 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

285
    def trace(last_lines: nil)
286
      hide_secrets(raw_trace(last_lines: last_lines))
287
    end
D
Douwe Maan 已提交
288

T
Tomasz Maczukin 已提交
289
    def trace_length
290
      if raw_trace
291
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
292
      else
293
        0
T
Tomasz Maczukin 已提交
294 295 296
      end
    end

D
Douwe Maan 已提交
297
    def trace=(trace)
298
      recreate_trace_dir
299
      trace = hide_secrets(trace)
300 301 302 303
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
304
      unless Dir.exist?(dir_to_trace)
305
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
306
      end
307 308
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
309

310
    def append_trace(trace_part, offset)
311
      recreate_trace_dir
312
      touch if needs_touch?
313

314 315
      trace_part = hide_secrets(trace_part)

316
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
317
      File.open(path_to_trace, 'ab') do |f|
318 319
        f.write(trace_part)
      end
D
Douwe Maan 已提交
320 321
    end

322 323 324 325
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

326 327 328 329 330 331 332 333
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

D
Douwe Maan 已提交
334 335
    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
336
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
337 338 339 340 341 342 343 344 345
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

346 347 348
    ##
    # Deprecated
    #
349 350 351
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
352 353 354 355 356 357 358 359 360 361 362
    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
    #
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
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

370 371 372 373 374 375 376 377 378 379 380 381 382 383 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
      old = File.join(created_at.utc.strftime('%Y_%m'),
                      project.ci_id.to_s,
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
      return old if project.ci_id && File.directory?(old_store)

      File.join(
        created_at.utc.strftime('%Y_%m'),
        project.id.to_s,
        id.to_s
      )
    end

L
Lin Jen-Shin 已提交
395
    def valid_token?(token)
396
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
397 398
    end

399 400 401 402
    def has_tags?
      tag_list.any?
    end

403
    def any_runners_online?
404
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
405 406
    end

K
Kamil Trzcinski 已提交
407
    def stuck?
408 409 410
      pending? && !any_runners_online?
    end

411
    def execute_hooks
412
      return unless project
413
      build_data = Gitlab::DataBuilder::Build.build(self)
K
Kamil Trzcinski 已提交
414 415
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
J
Josh Frye 已提交
416
      project.running_or_pending_build_count(force: true)
417 418
    end

419
    def artifacts?
420
      !artifacts_expired? && artifacts_file.exists?
421 422
    end

423
    def artifacts_metadata?
424
      artifacts? && artifacts_metadata.exists?
425 426
    end

427
    def artifacts_metadata_entry(path, **options)
428 429 430 431 432 433
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
434 435
    end

436 437 438
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
439
      save
440 441
    end

442 443 444
    def erase(opts = {})
      return false unless erasable?

445
      erase_artifacts!
446 447 448 449 450 451 452 453 454 455 456 457
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

458
    def artifacts_expired?
459
      artifacts_expire_at && artifacts_expire_at < Time.now
460 461
    end

462 463 464 465 466
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
467 468 469 470
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
471 472
    end

473
    def keep_artifacts!
474 475 476
      self.update(artifacts_expire_at: nil)
    end

477 478
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
479 480
    end

481 482
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
483 484
    end

485 486 487 488 489 490 491 492 493
    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

494
    def credentials
495
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
496 497
    end

498 499
    private

L
Lin Jen-Shin 已提交
500
    def update_artifacts_size
501 502
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
503 504
                            else
                              nil
505
                            end
L
Lin Jen-Shin 已提交
506 507
    end

508 509 510 511 512
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
513
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
514 515
    end

516
    def predefined_variables
517 518 519 520 521 522 523 524 525 526 527 528 529 530
      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 },
        { 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 }
      ]
531 532
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
533
      variables << { key: 'CI_BUILD_MANUAL', value: 'true', public: true } if manual?
534 535
      variables
    end
536 537 538

    def build_attributes_from_config
      return {} unless pipeline.config_processor
539

540 541
      pipeline.config_processor.build_attributes(name)
    end
542 543

    def hide_secrets(trace)
544 545 546 547 548
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
549 550
      trace
    end
D
Douwe Maan 已提交
551 552
  end
end