build.rb 15.2 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

12 13 14 15 16 17 18 19
    # 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 已提交
20
    serialize :options
21
    serialize :yaml_variables
D
Douwe Maan 已提交
22 23

    validates :coverage, numericality: true, allow_blank: true
K
Kamil Trzcinski 已提交
24
    validates_presence_of :ref
D
Douwe Maan 已提交
25 26

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

K
Kamil Trzcinski 已提交
34
    mount_uploader :artifacts_file, ArtifactUploader
35
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
36

D
Douwe Maan 已提交
37 38
    acts_as_taggable

39 40
    add_authentication_token_field :token

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

K
Kamil Trzcinski 已提交
45
    after_create :execute_hooks
D
Douwe Maan 已提交
46 47 48 49 50 51 52 53

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

      def create_from(build)
        new_build = build.dup
K
Kamil Trzcinski 已提交
54
        new_build.status = 'pending'
D
Douwe Maan 已提交
55
        new_build.runner_id = nil
K
Kamil Trzcinski 已提交
56
        new_build.trigger_request_id = nil
57
        new_build.token = nil
D
Douwe Maan 已提交
58 59 60
        new_build.save
      end

61
      def retry(build, user = nil)
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
        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,
79
          status_event: 'enqueue'
80
        )
81 82 83 84 85

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

86
        build.pipeline.mark_as_processable_after_stage(build.stage_idx)
D
Douwe Maan 已提交
87 88 89 90
        new_build
      end
    end

91
    state_machine :status do
92
      after_transition pending: :running do |build|
93 94 95
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
96 97
      end

98
      after_transition any => [:success, :failed, :canceled] do |build|
99
        build.run_after_commit do
100
          BuildFinishedWorker.perform_async(id)
101
        end
D
Douwe Maan 已提交
102
      end
103

104
      after_transition any => [:success] do |build|
105 106
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
107 108
        end
      end
D
Douwe Maan 已提交
109 110
    end

111
    def detailed_status(current_user)
112 113 114
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
115 116
    end

117 118 119 120
    def manual?
      self.when == 'manual'
    end

121
    def other_actions
122
      pipeline.manual_actions.where.not(name: name)
123 124
    end

125
    def playable?
126
      project.builds_enabled? && commands.present? && manual? && skipped?
127 128 129
    end

    def play(current_user = nil)
130
      # Try to queue a current build
131
      if self.enqueue
K
Kamil Trzcinski 已提交
132 133
        self.update(user: current_user)
        self
134 135 136 137 138 139
      else
        # Otherwise we need to create a duplicate
        Ci::Build.retry(self, current_user)
      end
    end

K
Kamil Trzcinski 已提交
140 141 142 143
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
144
    def retryable?
145
      project.builds_enabled? && commands.present? &&
146
        (success? || failed? || canceled?)
K
Kamil Trzcinski 已提交
147 148 149
    end

    def retried?
150
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
151 152
    end

153
    def expanded_environment_name
154
      ExpandVariables.expand(environment, simple_variables) if environment
155 156
    end

157 158 159 160
    def has_environment?
      self.environment.present?
    end

161
    def starts_environment?
162
      has_environment? && self.environment_action == 'start'
163 164 165
    end

    def stops_environment?
166
      has_environment? && self.environment_action == 'stop'
167 168 169
    end

    def environment_action
170
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
171 172 173 174
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
175
    end
176

177
    def last_deployment
178
      deployments.last
179 180
    end

181 182
    def depends_on_builds
      # Get builds of the same type
183
      latest_builds = self.pipeline.builds.latest
184 185 186 187 188

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

189 190
    def trace_html(**args)
      trace_with_state(**args)[:html] || ''
191 192
    end

193
    def trace_with_state(state: nil, last_lines: nil)
L
Lin Jen-Shin 已提交
194
      trace_ansi = trace(last_lines: last_lines)
195 196
      if trace_ansi.present?
        Ci::Ansi2html.convert(trace_ansi, state)
L
Lin Jen-Shin 已提交
197 198 199
      else
        {}
      end
D
Douwe Maan 已提交
200 201 202
    end

    def timeout
K
Kamil Trzcinski 已提交
203
      project.build_timeout
D
Douwe Maan 已提交
204 205
    end

N
Nick Thomas 已提交
206 207 208 209 210 211 212 213 214 215 216
    # 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

217 218
    # Variables whose value does not depend on other variables
    def simple_variables
219 220 221 222 223 224
      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
225
      variables += user_variables
226 227
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
228
      variables
D
Douwe Maan 已提交
229 230
    end

231 232 233 234 235 236 237
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
      variables += persisted_environment.predefined_variables if persisted_environment.present?
      variables
    end

238 239
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
240
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
241 242 243
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
244
        merge_request.commits_sha.include?(pipeline.sha)
245 246 247
      end
    end

D
Douwe Maan 已提交
248
    def project_id
249
      pipeline.project_id
D
Douwe Maan 已提交
250 251 252 253 254 255 256
    end

    def project_name
      project.name
    end

    def repo_url
K
Kamil Trzcinski 已提交
257
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
258 259 260
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
261 262 263
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
264
      project.build_allow_git_fetch
D
Douwe Maan 已提交
265 266 267
    end

    def update_coverage
268
      return unless project
K
Kamil Trzcinski 已提交
269 270 271
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
D
Douwe Maan 已提交
272 273 274 275 276 277 278 279

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

    def extract_coverage(text, regex)
      begin
J
Jared Szechy 已提交
280 281
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
D
Douwe Maan 已提交
282 283 284 285 286
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
G
Guilherme Garnier 已提交
287
      rescue
D
Douwe Maan 已提交
288 289 290 291 292
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

293
    def has_trace_file?
T
Tomasz Maczukin 已提交
294
      File.exist?(path_to_trace) || has_old_trace_file?
295 296
    end

297 298
    def has_trace?
      raw_trace.present?
299 300
    end

301
    def raw_trace(last_lines: nil)
T
Tomasz Maczukin 已提交
302
      if File.exist?(trace_file_path)
303 304
        Gitlab::Ci::TraceReader.new(trace_file_path).
          read(last_lines: last_lines)
D
Douwe Maan 已提交
305 306 307 308 309
      else
        # backward compatibility
        read_attribute :trace
      end
    end
310

T
Tomasz Maczukin 已提交
311 312 313 314 315 316 317 318
    ##
    # 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

319
    def trace(last_lines: nil)
320
      hide_secrets(raw_trace(last_lines: last_lines))
321
    end
D
Douwe Maan 已提交
322

T
Tomasz Maczukin 已提交
323
    def trace_length
324
      if raw_trace
325
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
326
      else
327
        0
T
Tomasz Maczukin 已提交
328 329 330
      end
    end

D
Douwe Maan 已提交
331
    def trace=(trace)
332
      recreate_trace_dir
333
      trace = hide_secrets(trace)
334 335 336 337
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
338
      unless Dir.exist?(dir_to_trace)
339
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
340
      end
341 342
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
343

344
    def append_trace(trace_part, offset)
345
      recreate_trace_dir
346
      touch if needs_touch?
347

348 349
      trace_part = hide_secrets(trace_part)

350
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
351
      File.open(path_to_trace, 'ab') do |f|
352 353
        f.write(trace_part)
      end
D
Douwe Maan 已提交
354 355
    end

356 357 358 359
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

360 361 362 363 364 365 366 367
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

D
Douwe Maan 已提交
368 369
    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
370
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
371 372 373 374 375 376 377 378 379
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

380 381 382
    ##
    # Deprecated
    #
383 384 385
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
386 387 388 389 390 391 392 393 394 395 396
    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
    #
397 398 399
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
400 401 402 403
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    ##
    # 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 已提交
429
    def valid_token?(token)
430
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
431 432
    end

433 434 435 436
    def has_tags?
      tag_list.any?
    end

437
    def any_runners_online?
438
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
439 440
    end

K
Kamil Trzcinski 已提交
441
    def stuck?
442 443 444
      pending? && !any_runners_online?
    end

445
    def execute_hooks
446
      return unless project
447
      build_data = Gitlab::DataBuilder::Build.build(self)
K
Kamil Trzcinski 已提交
448 449
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
J
Josh Frye 已提交
450
      project.running_or_pending_build_count(force: true)
451 452
    end

453
    def artifacts?
454
      !artifacts_expired? && artifacts_file.exists?
455 456
    end

457
    def artifacts_metadata?
458
      artifacts? && artifacts_metadata.exists?
459 460
    end

461
    def artifacts_metadata_entry(path, **options)
462 463 464 465 466 467
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
468 469
    end

470 471 472
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
473
      save
474 475
    end

476 477 478
    def erase(opts = {})
      return false unless erasable?

479
      erase_artifacts!
480 481 482 483 484 485 486 487 488 489 490 491
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

492
    def artifacts_expired?
493
      artifacts_expire_at && artifacts_expire_at < Time.now
494 495
    end

496 497 498 499 500
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
501 502 503 504
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
505 506
    end

507
    def keep_artifacts!
508 509 510
      self.update(artifacts_expire_at: nil)
    end

511 512
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
513 514
    end

515 516
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
517 518
    end

519 520 521 522 523 524 525 526 527
    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

528
    def credentials
529
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
530 531
    end

532 533
    private

L
Lin Jen-Shin 已提交
534
    def update_artifacts_size
535 536
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
537 538
                            else
                              nil
539
                            end
L
Lin Jen-Shin 已提交
540 541
    end

542 543 544 545 546
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
547
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
548 549
    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
D
Douwe Maan 已提交
586 587
  end
end