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

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

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

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

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

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

D
Douwe Maan 已提交
26 27
    acts_as_taggable

28 29
    add_authentication_token_field :token

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

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

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

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

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

75
    state_machine :status do
76
      after_transition pending: :running do |build|
77 78 79
        build.execute_hooks
      end

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

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

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

    def retried?
125
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
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

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

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

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

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

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

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

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

    def project_name
      project.name
    end

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

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

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

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

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

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

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

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

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

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

242 243
    def trace
      trace = raw_trace
244
      if project && trace.present? && project.runners_token.present?
K
Kamil Trzcinski 已提交
245
        trace.gsub(project.runners_token, 'xxxxxx')
246 247 248 249
      else
        trace
      end
    end
D
Douwe Maan 已提交
250

T
Tomasz Maczukin 已提交
251
    def trace_length
252
      if raw_trace
253
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
254
      else
255
        0
T
Tomasz Maczukin 已提交
256 257 258
      end
    end

D
Douwe Maan 已提交
259
    def trace=(trace)
260 261 262 263 264
      recreate_trace_dir
      File.write(path_to_trace, trace)
    end

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

271
    def append_trace(trace_part, offset)
272 273
      recreate_trace_dir

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

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

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

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

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

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

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

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

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

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

373
    def artifacts?
374
      !artifacts_expired? && self[:artifacts_file].present?
375 376
    end

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

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

      metadata.to_entry
388 389
    end

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

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

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

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

    def erased?
      !self.erased_at.nil?
    end

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

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

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

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

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

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

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

448 449
    private

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

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

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

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

    def build_attributes_from_config
      return {} unless pipeline.config_processor
489

490 491
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
492 493
  end
end