Read about our upcoming Code of Conduct on this issue

build.rb 15.8 KB
Newer Older
Douwe Maan's avatar
Douwe Maan committed
1
module Ci
Kamil Trzcinski's avatar
Kamil Trzcinski committed
2
  class Build < CommitStatus
3
    include TokenAuthenticatable
4
    include AfterCommitQueue
Rémy Coutable's avatar
Rémy Coutable committed
5
    include Presentable
6

7
8
    belongs_to :runner
    belongs_to :trigger_request
9
    belongs_to :erased_by, class_name: 'User'
Douwe Maan's avatar
Douwe Maan committed
10

11
12
    has_many :deployments, as: :deployable

13
14
15
16
17
18
19
20
    # 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

Douwe Maan's avatar
Douwe Maan committed
21
    serialize :options
22
    serialize :yaml_variables, Gitlab::Serialize::Ci::Variables
Douwe Maan's avatar
Douwe Maan committed
23
24

    validates :coverage, numericality: true, allow_blank: true
Kamil Trzcinski's avatar
Kamil Trzcinski committed
25
    validates_presence_of :ref
Douwe Maan's avatar
Douwe Maan committed
26
27

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

Kamil Trzcinski's avatar
Kamil Trzcinski committed
35
    mount_uploader :artifacts_file, ArtifactUploader
36
    mount_uploader :artifacts_metadata, ArtifactUploader
Kamil Trzcinski's avatar
Kamil Trzcinski committed
37

Douwe Maan's avatar
Douwe Maan committed
38
39
    acts_as_taggable

40
41
    add_authentication_token_field :token

42
    before_save :update_artifacts_size, if: :artifacts_file_changed?
43
    before_save :ensure_token
Grzegorz Bizon's avatar
Grzegorz Bizon committed
44
45
    before_destroy { project }

Kamil Trzcinski's avatar
Kamil Trzcinski committed
46
    after_create :execute_hooks
Markus Koller's avatar
Markus Koller committed
47
48
    after_save :update_project_statistics, if: :artifacts_size_changed?
    after_destroy :update_project_statistics
Douwe Maan's avatar
Douwe Maan committed
49
50
51
52
53
54
55
56

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

      def create_from(build)
        new_build = build.dup
Kamil Trzcinski's avatar
Kamil Trzcinski committed
57
        new_build.status = 'pending'
Douwe Maan's avatar
Douwe Maan committed
58
        new_build.runner_id = nil
Kamil Trzcinski's avatar
Kamil Trzcinski committed
59
        new_build.trigger_request_id = nil
60
        new_build.token = nil
Douwe Maan's avatar
Douwe Maan committed
61
62
63
        new_build.save
      end

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

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

89
        build.pipeline.mark_as_processable_after_stage(build.stage_idx)
Douwe Maan's avatar
Douwe Maan committed
90
91
92
93
        new_build
      end
    end

94
    state_machine :status do
95
96
      after_transition any => [:pending] do |build|
        build.run_after_commit do
Kim "BKC" Carlbäcker's avatar
linting    
Kim "BKC" Carlbäcker committed
97
          BuildQueueWorker.perform_async(id)
98
99
100
        end
      end

101
      after_transition pending: :running do |build|
102
103
104
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
105
106
      end

107
      after_transition any => [:success, :failed, :canceled] do |build|
108
        build.run_after_commit do
109
          BuildFinishedWorker.perform_async(id)
110
        end
Douwe Maan's avatar
Douwe Maan committed
111
      end
112

113
      after_transition any => [:success] do |build|
114
115
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
116
117
        end
      end
Douwe Maan's avatar
Douwe Maan committed
118
119
    end

120
    def detailed_status(current_user)
121
122
123
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
Kamil Trzcinski's avatar
Kamil Trzcinski committed
124
125
    end

126
127
128
129
    def manual?
      self.when == 'manual'
    end

130
    def other_actions
131
      pipeline.manual_actions.where.not(name: name)
132
133
    end

134
    def playable?
135
      project.builds_enabled? && commands.present? && manual? && skipped?
136
137
138
    end

    def play(current_user = nil)
139
      # Try to queue a current build
140
      if self.enqueue
Kamil Trzcinski's avatar
Kamil Trzcinski committed
141
142
        self.update(user: current_user)
        self
143
144
145
146
147
148
      else
        # Otherwise we need to create a duplicate
        Ci::Build.retry(self, current_user)
      end
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
149
150
151
152
    def cancelable?
      active?
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
153
    def retryable?
154
      project.builds_enabled? && commands.present? &&
155
        (success? || failed? || canceled?)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
156
157
158
    end

    def retried?
159
      !self.pipeline.statuses.latest.include?(self)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
160
161
    end

162
    def expanded_environment_name
163
      ExpandVariables.expand(environment, simple_variables) if environment
164
165
    end

166
    def has_environment?
167
      environment.present?
168
169
    end

170
    def starts_environment?
171
      has_environment? && self.environment_action == 'start'
172
173
174
    end

    def stops_environment?
175
      has_environment? && self.environment_action == 'stop'
176
177
178
    end

    def environment_action
179
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
180
181
182
183
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
184
    end
185

186
    def last_deployment
187
      deployments.last
188
189
    end

190
191
    def depends_on_builds
      # Get builds of the same type
192
      latest_builds = self.pipeline.builds.latest
193
194
195
196
197

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

198
199
    def trace_html(**args)
      trace_with_state(**args)[:html] || ''
200
201
    end

202
    def trace_with_state(state: nil, last_lines: nil)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
203
      trace_ansi = trace(last_lines: last_lines)
204
205
      if trace_ansi.present?
        Ci::Ansi2html.convert(trace_ansi, state)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
206
207
208
      else
        {}
      end
Douwe Maan's avatar
Douwe Maan committed
209
210
211
    end

    def timeout
212
      project.build_timeout
Douwe Maan's avatar
Douwe Maan committed
213
214
    end

Nick Thomas's avatar
Nick Thomas committed
215
216
217
218
219
220
221
222
223
224
225
    # 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

226
227
    # Variables whose value does not depend on other variables
    def simple_variables
228
229
230
231
232
      variables = predefined_variables
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
233
      variables += project.deployment_variables if has_environment?
234
      variables += yaml_variables
235
      variables += user_variables
236
237
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
238
      variables
Douwe Maan's avatar
Douwe Maan committed
239
240
    end

241
242
243
244
245
246
247
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
      variables += persisted_environment.predefined_variables if persisted_environment.present?
      variables
    end

248
249
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
250
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
251
252
253
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
254
        merge_request.commits_sha.include?(pipeline.sha)
255
256
257
      end
    end

Douwe Maan's avatar
Douwe Maan committed
258
    def project_id
Kamil Trzcinski's avatar
Kamil Trzcinski committed
259
      gl_project_id
Douwe Maan's avatar
Douwe Maan committed
260
261
262
263
264
265
266
    end

    def project_name
      project.name
    end

    def repo_url
Kamil Trzcinski's avatar
Kamil Trzcinski committed
267
      auth = "gitlab-ci-token:#{ensure_token!}@"
268
269
270
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
Douwe Maan's avatar
Douwe Maan committed
271
272
273
    end

    def allow_git_fetch
274
      project.build_allow_git_fetch
Douwe Maan's avatar
Douwe Maan committed
275
276
277
    end

    def update_coverage
278
      return unless project
279
280
281
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
Douwe Maan's avatar
Douwe Maan committed
282
283
284
285
286
287
288
289

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

    def extract_coverage(text, regex)
      begin
Jared Szechy's avatar
Jared Szechy committed
290
291
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
Douwe Maan's avatar
Douwe Maan committed
292
293
294
295
296
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
297
      rescue
Douwe Maan's avatar
Douwe Maan committed
298
299
300
301
302
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

303
    def has_trace_file?
Tomasz Maczukin's avatar
Tomasz Maczukin committed
304
      File.exist?(path_to_trace) || has_old_trace_file?
305
306
    end

307
308
    def has_trace?
      raw_trace.present?
309
310
    end

311
    def raw_trace(last_lines: nil)
Tomasz Maczukin's avatar
Tomasz Maczukin committed
312
      if File.exist?(trace_file_path)
313
314
        Gitlab::Ci::TraceReader.new(trace_file_path).
          read(last_lines: last_lines)
Douwe Maan's avatar
Douwe Maan committed
315
316
317
318
319
      else
        # backward compatibility
        read_attribute :trace
      end
    end
320

Tomasz Maczukin's avatar
Tomasz Maczukin committed
321
322
323
324
325
326
327
328
    ##
    # 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

329
    def trace(last_lines: nil)
330
      hide_secrets(raw_trace(last_lines: last_lines))
331
    end
Douwe Maan's avatar
Douwe Maan committed
332

Tomasz Maczukin's avatar
Tomasz Maczukin committed
333
    def trace_length
334
      if raw_trace
335
        raw_trace.bytesize
Tomasz Maczukin's avatar
Tomasz Maczukin committed
336
      else
337
        0
Tomasz Maczukin's avatar
Tomasz Maczukin committed
338
339
340
      end
    end

Douwe Maan's avatar
Douwe Maan committed
341
    def trace=(trace)
342
      recreate_trace_dir
343
      trace = hide_secrets(trace)
344
345
346
347
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
348
      unless Dir.exist?(dir_to_trace)
349
        FileUtils.mkdir_p(dir_to_trace)
Douwe Maan's avatar
Douwe Maan committed
350
      end
351
352
    end
    private :recreate_trace_dir
Douwe Maan's avatar
Douwe Maan committed
353

354
    def append_trace(trace_part, offset)
355
      recreate_trace_dir
356
      touch if needs_touch?
357

358
359
      trace_part = hide_secrets(trace_part)

360
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
361
      File.open(path_to_trace, 'ab') do |f|
362
363
        f.write(trace_part)
      end
Douwe Maan's avatar
Douwe Maan committed
364
365
    end

366
367
368
369
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

370
371
372
373
374
375
376
377
    def trace_file_path
      if has_old_trace_file?
        old_path_to_trace
      else
        path_to_trace
      end
    end

Douwe Maan's avatar
Douwe Maan committed
378
379
    def dir_to_trace
      File.join(
Valery Sizov's avatar
Valery Sizov committed
380
        Settings.gitlab_ci.builds_path,
Douwe Maan's avatar
Douwe Maan committed
381
382
383
384
385
386
387
388
389
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

390
391
392
    ##
    # Deprecated
    #
393
394
395
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
396
397
398
399
400
401
402
403
404
405
406
    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
    #
407
408
409
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
410
411
412
413
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
    ##
    # 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

Lin Jen-Shin's avatar
Lin Jen-Shin committed
439
    def valid_token?(token)
440
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
441
442
    end

443
444
445
446
    def has_tags?
      tag_list.any?
    end

447
    def any_runners_online?
448
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
449
450
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
451
    def stuck?
452
453
454
      pending? && !any_runners_online?
    end

455
    def execute_hooks
456
      return unless project
457
      build_data = Gitlab::DataBuilder::Build.build(self)
458
459
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
460
      UpdatePagesService.new(build_data).execute
Josh Frye's avatar
Josh Frye committed
461
      project.running_or_pending_build_count(force: true)
462
463
    end

464
    def artifacts?
465
      !artifacts_expired? && artifacts_file.exists?
466
467
    end

468
    def artifacts_metadata?
469
      artifacts? && artifacts_metadata.exists?
470
471
    end

472
    def artifacts_metadata_entry(path, **options)
473
474
475
476
477
478
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
479
480
    end

481
482
483
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
484
      save
485
486
    end

487
488
489
    def erase(opts = {})
      return false unless erasable?

490
      erase_artifacts!
491
492
493
494
495
496
497
498
499
500
501
502
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

503
    def artifacts_expired?
504
      artifacts_expire_at && artifacts_expire_at < Time.now
505
506
    end

507
508
509
510
511
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
512
513
514
515
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
516
517
    end

518
519
520
521
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

522
    def keep_artifacts!
523
524
525
      self.update(artifacts_expire_at: nil)
    end

526
527
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
528
529
    end

530
531
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
532
533
    end

534
535
536
537
538
539
540
541
542
    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

543
    def credentials
544
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
545
546
    end

547
548
    private

549
    def update_artifacts_size
550
551
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
552
553
                            else
                              nil
554
                            end
555
556
    end

557
558
559
560
561
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
562
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
563
564
    end

565
    def predefined_variables
566
567
568
569
570
571
572
573
      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 },
Nick Thomas's avatar
Nick Thomas committed
574
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
575
576
577
578
579
580
        { 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 }
      ]
581
582
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
583
      variables << { key: 'CI_BUILD_MANUAL', value: 'true', public: true } if manual?
584
585
      variables
    end
586
587
588

    def build_attributes_from_config
      return {} unless pipeline.config_processor
589

590
591
      pipeline.config_processor.build_attributes(name)
    end
592
593

    def hide_secrets(trace)
594
595
596
597
598
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
599
600
      trace
    end
Markus Koller's avatar
Markus Koller committed
601
602
603
604

    def update_project_statistics
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
Douwe Maan's avatar
Douwe Maan committed
605
606
  end
end