build.rb 12.5 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) }
L
Lin Jen-Shin 已提交
15
    scope :with_artifacts, ->() { where.not(artifacts_file: [nil, '']) }
16
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
17
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
18
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
19
    scope :manual_actions, ->() { where(when: :manual).relevant }
D
Douwe Maan 已提交
20

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

D
Douwe Maan 已提交
24 25
    acts_as_taggable

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

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

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

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

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

70
    state_machine :status do
71
      after_transition pending: :running do |build|
72 73 74
        build.execute_hooks
      end

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

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

92 93 94 95
    def manual?
      self.when == 'manual'
    end

96
    def other_actions
97
      pipeline.manual_actions.where.not(name: name)
98 99
    end

100
    def playable?
101
      project.builds_enabled? && commands.present? && manual? && skipped?
102 103 104
    end

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

K
Kamil Trzcinski 已提交
115
    def retryable?
116
      project.builds_enabled? && commands.present? && complete?
K
Kamil Trzcinski 已提交
117 118 119
    end

    def retried?
120
      !self.pipeline.statuses.latest.include?(self)
K
Kamil Trzcinski 已提交
121 122
    end

123 124
    def depends_on_builds
      # Get builds of the same type
125
      latest_builds = self.pipeline.builds.latest
126 127 128 129 130

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

D
Douwe Maan 已提交
131
    def trace_html
K
Kamil Trzcinski 已提交
132
      trace_with_state[:html] || ''
133 134 135 136 137
    end

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

    def timeout
K
Kamil Trzcinski 已提交
141
      project.build_timeout
D
Douwe Maan 已提交
142 143 144
    end

    def variables
145 146 147 148 149 150 151 152
      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
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
153
      variables
D
Douwe Maan 已提交
154 155
    end

156 157
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
158
                                   .where(source_branch: ref, source_project_id: pipeline.gl_project_id)
159 160 161
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
162
        merge_request.commits.any? { |ci| ci.id == pipeline.sha }
163 164 165
      end
    end

D
Douwe Maan 已提交
166
    def project_id
167
      pipeline.project_id
D
Douwe Maan 已提交
168 169 170 171 172 173 174
    end

    def project_name
      project.name
    end

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
182
      project.build_allow_git_fetch
D
Douwe Maan 已提交
183 184 185
    end

    def update_coverage
186
      return unless project
K
Kamil Trzcinski 已提交
187 188 189
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
D
Douwe Maan 已提交
190 191 192 193 194 195 196 197

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

    def extract_coverage(text, regex)
      begin
J
Jared Szechy 已提交
198 199
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
D
Douwe Maan 已提交
200 201 202 203 204
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
G
Guilherme Garnier 已提交
205
      rescue
D
Douwe Maan 已提交
206 207 208 209 210
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

211 212 213 214
    def has_trace_file?
      File.exist?(path_to_trace) || (project.ci_id && File.exist?(old_path_to_trace))
    end

215 216
    def has_trace?
      raw_trace.present?
217 218
    end

219
    def raw_trace
220
      if File.file?(path_to_trace)
D
Douwe Maan 已提交
221
        File.read(path_to_trace)
222
      elsif project.ci_id && File.file?(old_path_to_trace)
223 224
        # Temporary fix for build trace data integrity
        File.read(old_path_to_trace)
D
Douwe Maan 已提交
225 226 227 228 229
      else
        # backward compatibility
        read_attribute :trace
      end
    end
230 231 232

    def trace
      trace = raw_trace
233
      if project && trace.present? && project.runners_token.present?
K
Kamil Trzcinski 已提交
234
        trace.gsub(project.runners_token, 'xxxxxx')
235 236 237 238
      else
        trace
      end
    end
D
Douwe Maan 已提交
239

T
Tomasz Maczukin 已提交
240
    def trace_length
241
      if raw_trace
242
        raw_trace.bytesize
T
Tomasz Maczukin 已提交
243
      else
244
        0
T
Tomasz Maczukin 已提交
245 246 247
      end
    end

D
Douwe Maan 已提交
248
    def trace=(trace)
249 250 251 252 253
      recreate_trace_dir
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
254
      unless Dir.exist?(dir_to_trace)
255
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
256
      end
257 258
    end
    private :recreate_trace_dir
D
Douwe Maan 已提交
259

260
    def append_trace(trace_part, offset)
261 262
      recreate_trace_dir

263
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
264
      File.open(path_to_trace, 'ab') do |f|
265 266
        f.write(trace_part)
      end
D
Douwe Maan 已提交
267 268 269 270
    end

    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
271
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
272 273 274 275 276 277 278 279 280
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

281 282 283
    ##
    # Deprecated
    #
284 285 286
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
287 288 289 290 291 292 293 294 295 296 297
    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
    #
298 299 300
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
301 302 303 304
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    ##
    # 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 已提交
330
    def token
K
Kamil Trzcinski 已提交
331
      project.runners_token
K
Kamil Trzcinski 已提交
332 333
    end

L
Lin Jen-Shin 已提交
334 335
    def valid_token?(token)
      project.valid_runners_token?(token)
K
Kamil Trzcinski 已提交
336 337
    end

338 339 340 341
    def has_tags?
      tag_list.any?
    end

342
    def any_runners_online?
343
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
344 345
    end

K
Kamil Trzcinski 已提交
346
    def stuck?
347 348 349
      pending? && !any_runners_online?
    end

350
    def execute_hooks
351
      return unless project
352
      build_data = Gitlab::DataBuilder::Build.build(self)
K
Kamil Trzcinski 已提交
353 354
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
J
Josh Frye 已提交
355
      project.running_or_pending_build_count(force: true)
356 357
    end

358
    def artifacts?
359
      !artifacts_expired? && self[:artifacts_file].present?
360 361
    end

362
    def artifacts_metadata?
363
      artifacts? && artifacts_metadata.exists?
364 365
    end

366
    def artifacts_metadata_entry(path, **options)
367 368 369 370 371 372
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
373 374
    end

375 376 377
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
378
      save
379 380
    end

381 382 383
    def erase(opts = {})
      return false unless erasable?

384
      erase_artifacts!
385 386 387 388 389 390 391 392 393 394 395 396
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

397
    def artifacts_expired?
398
      artifacts_expire_at && artifacts_expire_at < Time.now
399 400
    end

401 402 403 404 405
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
406 407 408 409
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
410 411
    end

412
    def keep_artifacts!
413 414 415
      self.update(artifacts_expire_at: nil)
    end

416 417
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
418 419
    end

420 421
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
422 423 424 425
    end

    private

L
Lin Jen-Shin 已提交
426
    def update_artifacts_size
427 428
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
429 430
                            else
                              nil
431
                            end
L
Lin Jen-Shin 已提交
432 433
    end

434 435 436 437 438
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
439
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
440 441
    end

442
    def predefined_variables
443 444 445 446 447 448 449 450 451 452 453 454 455 456
      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 }
      ]
457 458
      variables << { key: 'CI_BUILD_TAG', value: ref, public: true } if tag?
      variables << { key: 'CI_BUILD_TRIGGERED', value: 'true', public: true } if trigger_request
459 460
      variables
    end
461 462 463

    def build_attributes_from_config
      return {} unless pipeline.config_processor
464

465 466
      pipeline.config_processor.build_attributes(name)
    end
D
Douwe Maan 已提交
467 468
  end
end