Read about our upcoming Code of Conduct on this issue

build.rb 13.1 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
5

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

    serialize :options
11
    serialize :yaml_variables
Douwe Maan's avatar
Douwe Maan committed
12
13

    validates :coverage, numericality: true, allow_blank: true
Kamil Trzcinski's avatar
Kamil Trzcinski committed
14
    validates_presence_of :ref
Douwe Maan's avatar
Douwe Maan committed
15
16

    scope :unstarted, ->() { where(runner_id: nil) }
Kamil Trzcinski's avatar
Kamil Trzcinski committed
17
    scope :ignore_failures, ->() { where(allow_failure: false) }
Lin Jen-Shin's avatar
Lin Jen-Shin committed
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 }
Douwe Maan's avatar
Douwe Maan committed
23

Kamil Trzcinski's avatar
Kamil Trzcinski committed
24
    mount_uploader :artifacts_file, ArtifactUploader
25
    mount_uploader :artifacts_metadata, ArtifactUploader
Kamil Trzcinski's avatar
Kamil Trzcinski committed
26

Douwe Maan's avatar
Douwe Maan committed
27
28
    acts_as_taggable

29
30
    add_authentication_token_field :token

31
    before_save :update_artifacts_size, if: :artifacts_file_changed?
32
    before_save :ensure_token
Grzegorz Bizon's avatar
Grzegorz Bizon committed
33
34
    before_destroy { project }

Kamil Trzcinski's avatar
Kamil Trzcinski committed
35
    after_create :execute_hooks
Douwe Maan's avatar
Douwe Maan committed
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
Kamil Trzcinski's avatar
Kamil Trzcinski committed
44
        new_build.status = 'pending'
Douwe Maan's avatar
Douwe Maan committed
45
        new_build.runner_id = nil
Kamil Trzcinski's avatar
Kamil Trzcinski committed
46
        new_build.trigger_request_id = nil
47
        new_build.token = nil
Douwe Maan's avatar
Douwe Maan committed
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)
Douwe Maan's avatar
Douwe Maan committed
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
          BuildFinishedWorker.perform_async(id)
87
        end
Douwe Maan's avatar
Douwe Maan committed
88
      end
89

90
      after_transition any => [:success] do |build|
91
92
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
93
94
        end
      end
Douwe Maan's avatar
Douwe Maan committed
95
96
    end

97
98
99
100
    def manual?
      self.when == 'manual'
    end

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

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

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

Kamil Trzcinski's avatar
Kamil Trzcinski committed
120
    def retryable?
121
      project.builds_enabled? && commands.present? && complete?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
122
123
124
    end

    def retried?
125
      !self.pipeline.statuses.latest.include?(self)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
126
127
    end

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

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

136
137
    def trace_html(**args)
      trace_with_state(**args)[:html] || ''
138
139
    end

140
    def trace_with_state(state: nil, last_lines: nil)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
141
      trace_ansi = trace(last_lines: last_lines)
142
143
      if trace_ansi.present?
        Ci::Ansi2html.convert(trace_ansi, state)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
144
145
146
      else
        {}
      end
Douwe Maan's avatar
Douwe Maan committed
147
148
149
    end

    def timeout
150
      project.build_timeout
Douwe Maan's avatar
Douwe Maan committed
151
152
153
    end

    def variables
154
155
156
157
158
159
      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
160
      variables += user_variables
161
162
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
163
      variables
Douwe Maan's avatar
Douwe Maan committed
164
165
    end

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

      merge_requests.find do |merge_request|
172
        merge_request.commits.any? { |ci| ci.id == pipeline.sha }
173
174
175
      end
    end

Douwe Maan's avatar
Douwe Maan committed
176
    def project_id
177
      pipeline.project_id
Douwe Maan's avatar
Douwe Maan committed
178
179
180
181
182
183
184
    end

    def project_name
      project.name
    end

    def repo_url
Kamil Trzcinski's avatar
Kamil Trzcinski committed
185
      auth = "gitlab-ci-token:#{ensure_token!}@"
186
187
188
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
Douwe Maan's avatar
Douwe Maan committed
189
190
191
    end

    def allow_git_fetch
192
      project.build_allow_git_fetch
Douwe Maan's avatar
Douwe Maan committed
193
194
195
    end

    def update_coverage
196
      return unless project
197
198
199
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
Douwe Maan's avatar
Douwe Maan committed
200
201
202
203
204
205
206
207

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

    def extract_coverage(text, regex)
      begin
Jared Szechy's avatar
Jared Szechy committed
208
209
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
Douwe Maan's avatar
Douwe Maan committed
210
211
212
213
214
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
215
      rescue
Douwe Maan's avatar
Douwe Maan committed
216
217
218
219
220
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

221
    def has_trace_file?
Tomasz Maczukin's avatar
Tomasz Maczukin committed
222
      File.exist?(path_to_trace) || has_old_trace_file?
223
224
    end

225
226
    def has_trace?
      raw_trace.present?
227
228
    end

229
    def raw_trace(last_lines: nil)
Tomasz Maczukin's avatar
Tomasz Maczukin committed
230
      if File.exist?(trace_file_path)
231
232
        Gitlab::Ci::TraceReader.new(trace_file_path).
          read(last_lines: last_lines)
Douwe Maan's avatar
Douwe Maan committed
233
234
235
236
237
      else
        # backward compatibility
        read_attribute :trace
      end
    end
238

Tomasz Maczukin's avatar
Tomasz Maczukin committed
239
240
241
242
243
244
245
246
    ##
    # 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

247
    def trace(last_lines: nil)
248
      hide_secrets(raw_trace(last_lines: last_lines))
249
    end
Douwe Maan's avatar
Douwe Maan committed
250

Tomasz Maczukin's avatar
Tomasz Maczukin committed
251
    def trace_length
252
      if raw_trace
253
        raw_trace.bytesize
Tomasz Maczukin's avatar
Tomasz Maczukin committed
254
      else
255
        0
Tomasz Maczukin's avatar
Tomasz Maczukin committed
256
257
258
      end
    end

Douwe Maan's avatar
Douwe Maan committed
259
    def trace=(trace)
260
      recreate_trace_dir
261
      trace = hide_secrets(trace)
262
263
264
265
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
266
      unless Dir.exist?(dir_to_trace)
267
        FileUtils.mkdir_p(dir_to_trace)
Douwe Maan's avatar
Douwe Maan committed
268
      end
269
270
    end
    private :recreate_trace_dir
Douwe Maan's avatar
Douwe Maan committed
271

272
    def append_trace(trace_part, offset)
273
274
      recreate_trace_dir

275
276
      trace_part = hide_secrets(trace_part)

277
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
278
      File.open(path_to_trace, 'ab') do |f|
279
280
        f.write(trace_part)
      end
Douwe Maan's avatar
Douwe Maan committed
281
282
    end

283
284
285
286
287
288
289
290
    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
291
292
    def dir_to_trace
      File.join(
Valery Sizov's avatar
Valery Sizov committed
293
        Settings.gitlab_ci.builds_path,
Douwe Maan's avatar
Douwe Maan committed
294
295
296
297
298
299
300
301
302
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

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

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    ##
    # 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
352
    def valid_token?(token)
353
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
354
355
    end

356
357
358
359
    def has_tags?
      tag_list.any?
    end

360
    def any_runners_online?
361
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
362
363
    end

Kamil Trzcinski's avatar
Kamil Trzcinski committed
364
    def stuck?
365
366
367
      pending? && !any_runners_online?
    end

368
    def execute_hooks
369
      return unless project
370
      build_data = Gitlab::DataBuilder::Build.build(self)
371
372
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
Josh Frye's avatar
Josh Frye committed
373
      project.running_or_pending_build_count(force: true)
374
375
    end

376
    def artifacts?
377
      !artifacts_expired? && artifacts_file.exists?
378
379
    end

380
    def artifacts_metadata?
381
      artifacts? && artifacts_metadata.exists?
382
383
    end

384
    def artifacts_metadata_entry(path, **options)
385
386
387
388
389
390
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
391
392
    end

393
394
395
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
396
      save
397
398
    end

399
400
401
    def erase(opts = {})
      return false unless erasable?

402
      erase_artifacts!
403
404
405
406
407
408
409
410
411
412
413
414
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

415
    def artifacts_expired?
416
      artifacts_expire_at && artifacts_expire_at < Time.now
417
418
    end

419
420
421
422
423
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
424
425
426
427
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
428
429
    end

430
    def keep_artifacts!
431
432
433
      self.update(artifacts_expire_at: nil)
    end

434
435
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
436
437
    end

438
439
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
440
441
    end

442
443
444
445
446
447
448
449
450
    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

451
452
    private

453
    def update_artifacts_size
454
455
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
456
457
                            else
                              nil
458
                            end
459
460
    end

461
462
463
464
465
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
466
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
467
468
    end

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

    def build_attributes_from_config
      return {} unless pipeline.config_processor
492

493
494
      pipeline.config_processor.build_attributes(name)
    end
495
496

    def hide_secrets(trace)
497
498
499
500
501
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
502
503
      trace
    end
Douwe Maan's avatar
Douwe Maan committed
504
505
  end
end