build.rb 12.0 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
D
Douwe Maan 已提交
3 4
    belongs_to :runner, class_name: 'Ci::Runner'
    belongs_to :trigger_request, class_name: 'Ci::TriggerRequest'
5
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
6 7

    serialize :options
8
    serialize :yaml_variables
D
Douwe Maan 已提交
9 10

    validates :coverage, numericality: true, allow_blank: true
K
Kamil Trzcinski 已提交
11
    validates_presence_of :ref
D
Douwe Maan 已提交
12 13

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
14
    scope :ignore_failures, ->() { where(allow_failure: false) }
15
    scope :with_artifacts, ->() { where.not(artifacts_file: nil) }
16
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
17
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
18
    scope :manual_actions, ->() { where(when: :manual) }
D
Douwe Maan 已提交
19

K
Kamil Trzcinski 已提交
20
    mount_uploader :artifacts_file, ArtifactUploader
21
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
22

D
Douwe Maan 已提交
23 24
    acts_as_taggable

L
Lin Jen-Shin 已提交
25
    before_save :update_artifacts_size, if: :artifacts_file_changed?
G
Grzegorz Bizon 已提交
26 27
    before_destroy { project }

K
Kamil Trzcinski 已提交
28
    after_create :execute_hooks
D
Douwe Maan 已提交
29 30 31 32 33 34 35 36

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

      def create_from(build)
        new_build = build.dup
K
Kamil Trzcinski 已提交
37
        new_build.status = 'pending'
D
Douwe Maan 已提交
38
        new_build.runner_id = nil
K
Kamil Trzcinski 已提交
39
        new_build.trigger_request_id = nil
D
Douwe Maan 已提交
40 41 42
        new_build.save
      end

43
      def retry(build, user = nil)
K
Kamil Trzcinski 已提交
44
        new_build = Ci::Build.new(status: 'pending')
K
Kamil Trzcinski 已提交
45 46
        new_build.ref = build.ref
        new_build.tag = build.tag
D
Douwe Maan 已提交
47 48 49
        new_build.options = build.options
        new_build.commands = build.commands
        new_build.tag_list = build.tag_list
50 51
        new_build.project = build.project
        new_build.pipeline = build.pipeline
D
Douwe Maan 已提交
52 53 54
        new_build.name = build.name
        new_build.allow_failure = build.allow_failure
        new_build.stage = build.stage
K
Kamil Trzcinski 已提交
55
        new_build.stage_idx = build.stage_idx
D
Douwe Maan 已提交
56
        new_build.trigger_request = build.trigger_request
57 58
        new_build.yaml_variables = build.yaml_variables
        new_build.when = build.when
59
        new_build.user = user
60
        new_build.environment = build.environment
D
Douwe Maan 已提交
61
        new_build.save
62
        MergeRequests::AddTodoWhenBuildFailsService.new(build.project, nil).close(new_build)
D
Douwe Maan 已提交
63 64 65 66 67
        new_build
      end
    end

    state_machine :status, initial: :pending do
68
      after_transition pending: :running do |build|
69 70 71
        build.execute_hooks
      end

72 73 74
      # We use around_transition to create builds for next stage as soon as possible, before the `after_*` is executed
      around_transition any => [:success, :failed, :canceled] do |build, block|
        block.call
75
        build.pipeline.create_next_builds(build) if build.pipeline
76
      end
77

78
      after_transition any => [:success, :failed, :canceled] do |build|
K
Kamil Trzcinski 已提交
79
        build.update_coverage
80
        build.execute_hooks
D
Douwe Maan 已提交
81
      end
82

83
      after_transition any => [:success] do |build|
84
        if build.environment.present?
85 86
          service = CreateDeploymentService.new(build.project, build.user,
                                                environment: build.environment,
K
Kamil Trzcinski 已提交
87 88
                                                sha: build.sha,
                                                ref: build.ref,
89 90
                                                tag: build.tag)
          service.execute(build)
91 92
        end
      end
D
Douwe Maan 已提交
93 94
    end

95 96 97 98
    def manual?
      self.when == 'manual'
    end

99 100 101 102
    def other_actions
      pipeline.manual_actions.where.not(id: self)
    end

103 104 105 106 107
    def playable?
      project.builds_enabled? && commands.present? && manual?
    end

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

K
Kamil Trzcinski 已提交
118
    def retryable?
119
      project.builds_enabled? && commands.present? && complete?
K
Kamil Trzcinski 已提交
120 121 122
    end

    def retried?
123
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
124 125
    end

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

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

D
Douwe Maan 已提交
134
    def trace_html
K
Kamil Trzcinski 已提交
135
      trace_with_state[:html] || ''
136 137 138 139 140
    end

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

    def timeout
K
Kamil Trzcinski 已提交
144
      project.build_timeout
D
Douwe Maan 已提交
145 146 147
    end

    def variables
148
      predefined_variables + yaml_variables + project_variables + trigger_variables
D
Douwe Maan 已提交
149 150
    end

151 152
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
153
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
154 155 156
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
157
        merge_request.commits.any? { |ci| ci.id == pipeline.sha }
158 159 160
      end
    end

D
Douwe Maan 已提交
161
    def project_id
162
      pipeline.project_id
D
Douwe Maan 已提交
163 164 165 166 167 168 169
    end

    def project_name
      project.name
    end

    def repo_url
K
Kamil Trzcinski 已提交
170 171 172 173
      auth = "gitlab-ci-token:#{token}@"
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
174 175 176
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
177
      project.build_allow_git_fetch
D
Douwe Maan 已提交
178 179 180
    end

    def update_coverage
181
      return unless project
K
Kamil Trzcinski 已提交
182 183 184
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
D
Douwe Maan 已提交
185 186 187 188 189 190 191 192

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

    def extract_coverage(text, regex)
      begin
J
Jared Szechy 已提交
193 194
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
D
Douwe Maan 已提交
195 196 197 198 199
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
G
Guilherme Garnier 已提交
200
      rescue
D
Douwe Maan 已提交
201 202 203 204 205
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

206 207
    def has_trace?
      raw_trace.present?
208 209
    end

210
    def raw_trace
211
      if File.file?(path_to_trace)
D
Douwe Maan 已提交
212
        File.read(path_to_trace)
213
      elsif project.ci_id && File.file?(old_path_to_trace)
214 215
        # Temporary fix for build trace data integrity
        File.read(old_path_to_trace)
D
Douwe Maan 已提交
216 217 218 219 220
      else
        # backward compatibility
        read_attribute :trace
      end
    end
221 222 223

    def trace
      trace = raw_trace
224
      if project && trace.present? && project.runners_token.present?
K
Kamil Trzcinski 已提交
225
        trace.gsub(project.runners_token, 'xxxxxx')
226 227 228 229
      else
        trace
      end
    end
D
Douwe Maan 已提交
230

T
Tomasz Maczukin 已提交
231
    def trace_length
232
      if raw_trace
233
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
234
      else
235
        0
T
Tomasz Maczukin 已提交
236 237 238
      end
    end

D
Douwe Maan 已提交
239
    def trace=(trace)
240 241 242 243 244
      recreate_trace_dir
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
245
      unless Dir.exist?(dir_to_trace)
246
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
247
      end
248 249
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
250

251
    def append_trace(trace_part, offset)
252 253
      recreate_trace_dir

254
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
255
      File.open(path_to_trace, 'ab') do |f|
256 257
        f.write(trace_part)
      end
D
Douwe Maan 已提交
258 259 260 261
    end

    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
262
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
263 264 265 266 267 268 269 270 271
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

272 273 274
    ##
    # Deprecated
    #
275 276 277
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
278 279 280 281 282 283 284 285 286 287 288
    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
    #
289 290 291
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
292 293 294 295
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    ##
    # 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

K
Kamil Trzcinski 已提交
321
    def token
K
Kamil Trzcinski 已提交
322
      project.runners_token
K
Kamil Trzcinski 已提交
323 324
    end

325
    def valid_token?(token)
K
Kamil Trzcinski 已提交
326
      project.valid_runners_token? token
K
Kamil Trzcinski 已提交
327 328
    end

329 330 331 332
    def has_tags?
      tag_list.any?
    end

333
    def any_runners_online?
334
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
335 336
    end

K
Kamil Trzcinski 已提交
337
    def stuck?
338 339 340
      pending? && !any_runners_online?
    end

341
    def execute_hooks
342
      return unless project
343
      build_data = Gitlab::BuildDataBuilder.build(self)
K
Kamil Trzcinski 已提交
344 345
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
J
Josh Frye 已提交
346
      project.running_or_pending_build_count(force: true)
347 348
    end

349
    def artifacts?
350
      !artifacts_expired? && artifacts_file.exists?
351 352
    end

353
    def artifacts_metadata?
354
      artifacts? && artifacts_metadata.exists?
355 356
    end

357
    def artifacts_metadata_entry(path, **options)
358 359 360 361 362 363
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
364 365
    end

366 367 368
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
369
      save
370 371
    end

372 373 374
    def erase(opts = {})
      return false unless erasable?

375
      erase_artifacts!
376 377 378 379 380 381 382 383 384 385 386 387
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

388
    def artifacts_expired?
389
      artifacts_expire_at && artifacts_expire_at < Time.now
390 391
    end

392 393 394 395 396
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
397 398 399 400
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
401 402
    end

403
    def keep_artifacts!
404 405 406
      self.update(artifacts_expire_at: nil)
    end

407 408 409 410 411 412 413 414
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
    end

    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
    end

415 416
    private

L
Lin Jen-Shin 已提交
417
    def update_artifacts_size
418 419
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
420 421
                            else
                              nil
422
                            end
L
Lin Jen-Shin 已提交
423 424
    end

425 426 427 428 429
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
430
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
431 432
    end

D
Douwe Maan 已提交
433
    def project_variables
434
      project.variables.map do |variable|
D
Douwe Maan 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447
        { key: variable.key, value: variable.value, public: false }
      end
    end

    def trigger_variables
      if trigger_request && trigger_request.variables
        trigger_request.variables.map do |key, value|
          { key: key, value: value, public: false }
        end
      else
        []
      end
    end
448 449 450

    def predefined_variables
      variables = []
451
      variables << { key: :CI_BUILD_TAG, value: ref, public: true } if tag?
452 453 454 455 456
      variables << { key: :CI_BUILD_NAME, value: name, public: true }
      variables << { key: :CI_BUILD_STAGE, value: stage, public: true }
      variables << { key: :CI_BUILD_TRIGGERED, value: 'true', public: true } if trigger_request
      variables
    end
457 458 459 460 461

    def build_attributes_from_config
      return {} unless pipeline.config_processor
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
462 463
  end
end