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

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

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

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

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

K
Kamil Trzcinski 已提交
24
    mount_uploader :artifacts_file, ArtifactUploader
25
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
26

D
Douwe Maan 已提交
27 28
    acts_as_taggable

29 30
    add_authentication_token_field :token

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

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

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

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

51
      def retry(build, user = nil)
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        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,
69
          status_event: 'enqueue'
70
        )
71
        MergeRequests::AddTodoWhenBuildFailsService.new(build.project, nil).close(new_build)
72
        build.pipeline.mark_as_processable_after_stage(build.stage_idx)
D
Douwe Maan 已提交
73 74 75 76
        new_build
      end
    end

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

84
      after_transition any => [:success, :failed, :canceled] do |build|
85
        build.run_after_commit do
86
          BuildCoverageWorker.perform_async(id)
87 88
          BuildHooksWorker.perform_async(id)
        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 99 100 101
    def manual?
      self.when == 'manual'
    end

102
    def other_actions
103
      pipeline.manual_actions.where.not(name: name)
104 105
    end

106
    def playable?
107
      project.builds_enabled? && commands.present? && manual? && skipped?
108 109 110
    end

    def play(current_user = nil)
111
      # Try to queue a current build
112
      if self.enqueue
K
Kamil Trzcinski 已提交
113 114
        self.update(user: current_user)
        self
115 116 117 118 119 120
      else
        # Otherwise we need to create a duplicate
        Ci::Build.retry(self, current_user)
      end
    end

K
Kamil Trzcinski 已提交
121
    def retryable?
122
      project.builds_enabled? && commands.present? && complete?
K
Kamil Trzcinski 已提交
123 124 125
    end

    def retried?
126
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
127 128
    end

129 130
    def depends_on_builds
      # Get builds of the same type
131
      latest_builds = self.pipeline.builds.latest
132 133 134 135 136

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

D
Douwe Maan 已提交
137
    def trace_html
K
Kamil Trzcinski 已提交
138
      trace_with_state[:html] || ''
139 140 141 142 143
    end

    def trace_with_state(state = nil)
      trace_with_state = Ci::Ansi2html::convert(trace, state) if trace.present?
      trace_with_state || {}
D
Douwe Maan 已提交
144 145 146
    end

    def timeout
K
Kamil Trzcinski 已提交
147
      project.build_timeout
D
Douwe Maan 已提交
148 149 150
    end

    def variables
151 152 153 154 155 156
      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
157
      variables += user_variables
158 159
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
160
      variables
D
Douwe Maan 已提交
161 162
    end

163 164
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
165
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
166 167 168
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
169
        merge_request.commits.any? { |ci| ci.id == pipeline.sha }
170 171 172
      end
    end

D
Douwe Maan 已提交
173
    def project_id
174
      pipeline.project_id
D
Douwe Maan 已提交
175 176 177 178 179 180 181
    end

    def project_name
      project.name
    end

    def repo_url
K
Kamil Trzcinski 已提交
182
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
183 184 185
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
186 187 188
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
189
      project.build_allow_git_fetch
D
Douwe Maan 已提交
190 191 192
    end

    def update_coverage
193
      return unless project
K
Kamil Trzcinski 已提交
194 195 196
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
D
Douwe Maan 已提交
197 198 199 200 201 202 203 204

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

    def extract_coverage(text, regex)
      begin
J
Jared Szechy 已提交
205 206
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
D
Douwe Maan 已提交
207 208 209 210 211
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
G
Guilherme Garnier 已提交
212
      rescue
D
Douwe Maan 已提交
213 214 215 216 217
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

218
    def has_trace_file?
T
Tomasz Maczukin 已提交
219
      File.exist?(path_to_trace) || has_old_trace_file?
220 221
    end

222 223
    def has_trace?
      raw_trace.present?
224 225
    end

226
    def raw_trace
T
Tomasz Maczukin 已提交
227 228
      if File.exist?(trace_file_path)
        File.read(trace_file_path)
D
Douwe Maan 已提交
229 230 231 232 233
      else
        # backward compatibility
        read_attribute :trace
      end
    end
234

T
Tomasz Maczukin 已提交
235 236 237 238 239 240 241 242
    ##
    # 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

243
    def trace
244
      hide_secrets(raw_trace)
245
    end
D
Douwe Maan 已提交
246

T
Tomasz Maczukin 已提交
247
    def trace_length
248
      if raw_trace
249
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
250
      else
251
        0
T
Tomasz Maczukin 已提交
252 253 254
      end
    end

D
Douwe Maan 已提交
255
    def trace=(trace)
256
      recreate_trace_dir
257
      trace = hide_secrets(trace)
258 259 260 261
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
262
      unless Dir.exist?(dir_to_trace)
263
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
264
      end
265 266
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
267

268
    def append_trace(trace_part, offset)
269 270
      recreate_trace_dir

271 272
      trace_part = hide_secrets(trace_part)

273
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
274
      File.open(path_to_trace, 'ab') do |f|
275 276
        f.write(trace_part)
      end
D
Douwe Maan 已提交
277 278
    end

279 280 281 282 283 284 285 286
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

D
Douwe Maan 已提交
287 288
    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
289
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
290 291 292 293 294 295 296 297 298
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

299 300 301
    ##
    # Deprecated
    #
302 303 304
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
305 306 307 308 309 310 311 312 313 314 315
    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
    #
316 317 318
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
319 320 321 322
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    ##
    # 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 已提交
348
    def valid_token?(token)
349
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
350 351
    end

352 353 354 355
    def has_tags?
      tag_list.any?
    end

356
    def any_runners_online?
357
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
358 359
    end

K
Kamil Trzcinski 已提交
360
    def stuck?
361 362 363
      pending? && !any_runners_online?
    end

364
    def execute_hooks
365
      return unless project
366
      build_data = Gitlab::DataBuilder::Build.build(self)
K
Kamil Trzcinski 已提交
367 368
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
J
Josh Frye 已提交
369
      project.running_or_pending_build_count(force: true)
370 371
    end

372
    def artifacts?
373
      !artifacts_expired? && artifacts_file.exists?
374 375
    end

376
    def artifacts_metadata?
377
      artifacts? && artifacts_metadata.exists?
378 379
    end

380
    def artifacts_metadata_entry(path, **options)
381 382 383 384 385 386
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
387 388
    end

389 390 391
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
392
      save
393 394
    end

395 396 397
    def erase(opts = {})
      return false unless erasable?

398
      erase_artifacts!
399 400 401 402 403 404 405 406 407 408 409 410
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

411
    def artifacts_expired?
412
      artifacts_expire_at && artifacts_expire_at < Time.now
413 414
    end

415 416 417 418 419
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
420 421 422 423
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
424 425
    end

426
    def keep_artifacts!
427 428 429
      self.update(artifacts_expire_at: nil)
    end

430 431
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
432 433
    end

434 435
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
436 437
    end

438 439 440 441 442 443 444 445 446
    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

447 448
    private

L
Lin Jen-Shin 已提交
449
    def update_artifacts_size
450 451
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
452 453
                            else
                              nil
454
                            end
L
Lin Jen-Shin 已提交
455 456
    end

457 458 459 460 461
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
462
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
463 464
    end

465
    def predefined_variables
466 467 468 469 470 471 472 473 474 475 476 477 478 479
      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 }
      ]
480 481
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
482
      variables << { key: 'CI_BUILD_MANUAL', value: 'true', public: true } if manual?
483 484
      variables
    end
485 486 487

    def build_attributes_from_config
      return {} unless pipeline.config_processor
488

489 490
      pipeline.config_processor.build_attributes(name)
    end
491 492

    def hide_secrets(trace)
493 494 495 496 497
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
498 499
      trace
    end
D
Douwe Maan 已提交
500 501
  end
end