build.rb 12.3 KB
Newer Older
1
module Ci
2
  class Build < CommitStatus
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'
6 7

    serialize :options
8
    serialize :yaml_variables
9 10

    validates :coverage, numericality: true, allow_blank: true
11
    validates_presence_of :ref
12 13

    scope :unstarted, ->() { where(runner_id: nil) }
14
    scope :ignore_failures, ->() { where(allow_failure: false) }
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 }
20

21
    mount_uploader :artifacts_file, ArtifactUploader
22
    mount_uploader :artifacts_metadata, ArtifactUploader
23

24 25
    acts_as_taggable

26
    before_save :update_artifacts_size, if: :artifacts_file_changed?
27 28
    before_destroy { project }

29
    after_create :execute_hooks
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
38
        new_build.status = 'pending'
39
        new_build.runner_id = nil
40
        new_build.trigger_request_id = nil
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 66 67 68
        new_build
      end
    end

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

74
      after_transition any => [:success, :failed, :canceled] do |build|
75
        build.update_coverage
76
        build.execute_hooks
77
      end
78

79
      after_transition any => [:success] do |build|
80
        if build.environment.present?
81 82
          service = CreateDeploymentService.new(build.project, build.user,
                                                environment: build.environment,
83 84
                                                sha: build.sha,
                                                ref: build.ref,
85 86
                                                tag: build.tag)
          service.execute(build)
87 88
        end
      end
89 90
    end

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

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

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

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

Kamil Trzcinski's avatar
Kamil Trzcinski committed
114
    def retryable?
115
      project.builds_enabled? && commands.present? && complete?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
116 117 118
    end

    def retried?
119
      !self.pipeline.statuses.latest.include?(self)
120 121
    end

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

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

130
    def trace_html
Kamil Trzcinski's avatar
Kamil Trzcinski committed
131
      trace_with_state[:html] || ''
132 133 134 135 136
    end

    def trace_with_state(state = nil)
      trace_with_state = Ci::Ansi2html::convert(trace, state) if trace.present?
      trace_with_state || {}
137 138 139
    end

    def timeout
140
      project.build_timeout
141 142 143
    end

    def variables
144 145 146 147 148 149 150 151
      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
152
      variables
153 154
    end

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

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

165
    def project_id
166
      pipeline.project_id
167 168 169 170 171 172 173
    end

    def project_name
      project.name
    end

    def repo_url
174 175 176 177
      auth = "gitlab-ci-token:#{token}@"
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
178 179 180
    end

    def allow_git_fetch
181
      project.build_allow_git_fetch
182 183 184
    end

    def update_coverage
185
      return unless project
186 187 188
      coverage_regex = project.build_coverage_regex
      return unless coverage_regex
      coverage = extract_coverage(trace, coverage_regex)
189 190 191 192 193 194 195 196

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

    def extract_coverage(text, regex)
      begin
Jared Szechy's avatar
Jared Szechy committed
197 198
        matches = text.scan(Regexp.new(regex)).last
        matches = matches.last if matches.kind_of?(Array)
199 200 201 202 203
        coverage = matches.gsub(/\d+(\.\d+)?/).first

        if coverage.present?
          coverage.to_f
        end
204
      rescue
205 206 207 208 209
        # if bad regex or something goes wrong we dont want to interrupt transition
        # so we just silentrly ignore error for now
      end
    end

210 211
    def has_trace?
      raw_trace.present?
212 213
    end

214
    def raw_trace
215
      if File.file?(path_to_trace)
216
        File.read(path_to_trace)
217
      elsif project.ci_id && File.file?(old_path_to_trace)
218 219
        # Temporary fix for build trace data integrity
        File.read(old_path_to_trace)
220 221 222 223 224
      else
        # backward compatibility
        read_attribute :trace
      end
    end
225 226 227

    def trace
      trace = raw_trace
228
      if project && trace.present? && project.runners_token.present?
Kamil Trzcinski's avatar
Kamil Trzcinski committed
229
        trace.gsub(project.runners_token, 'xxxxxx')
230 231 232 233
      else
        trace
      end
    end
234

Tomasz Maczukin's avatar
Tomasz Maczukin committed
235
    def trace_length
236
      if raw_trace
237
        raw_trace.bytesize
Tomasz Maczukin's avatar
Tomasz Maczukin committed
238
      else
239
        0
Tomasz Maczukin's avatar
Tomasz Maczukin committed
240 241 242
      end
    end

243
    def trace=(trace)
244 245 246 247 248
      recreate_trace_dir
      File.write(path_to_trace, trace)
    end

    def recreate_trace_dir
249
      unless Dir.exist?(dir_to_trace)
250
        FileUtils.mkdir_p(dir_to_trace)
251
      end
252 253
    end
    private :recreate_trace_dir
254

255
    def append_trace(trace_part, offset)
256 257
      recreate_trace_dir

258
      File.truncate(path_to_trace, offset) if File.exist?(path_to_trace)
259
      File.open(path_to_trace, 'ab') do |f|
260 261
        f.write(trace_part)
      end
262 263 264 265
    end

    def dir_to_trace
      File.join(
Valery Sizov's avatar
Valery Sizov committed
266
        Settings.gitlab_ci.builds_path,
267 268 269 270 271 272 273 274 275
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

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

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    ##
    # 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

325
    def token
Kamil Trzcinski's avatar
Kamil Trzcinski committed
326
      project.runners_token
327 328
    end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
329 330
    def valid_token?(token)
      project.valid_runners_token?(token)
331 332
    end

333 334 335 336
    def has_tags?
      tag_list.any?
    end

337
    def any_runners_online?
338
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
339 340
    end

341
    def stuck?
342 343 344
      pending? && !any_runners_online?
    end

345
    def execute_hooks
346
      return unless project
347
      build_data = Gitlab::DataBuilder::Build.build(self)
348 349
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
Josh Frye's avatar
Josh Frye committed
350
      project.running_or_pending_build_count(force: true)
351 352
    end

353
    def artifacts?
354
      !artifacts_expired? && artifacts_file.exists?
355 356
    end

357
    def artifacts_metadata?
358
      artifacts? && artifacts_metadata.exists?
359 360
    end

361
    def artifacts_metadata_entry(path, **options)
362 363 364 365 366 367
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
368 369
    end

370 371 372
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
373
      save
374 375
    end

376 377 378
    def erase(opts = {})
      return false unless erasable?

379
      erase_artifacts!
380 381 382 383 384 385 386 387 388 389 390 391
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

392
    def artifacts_expired?
393
      artifacts_expire_at && artifacts_expire_at < Time.now
394 395
    end

396 397 398 399 400
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
401 402 403 404
      self.artifacts_expire_at =
        if value
          Time.now + ChronicDuration.parse(value)
        end
405 406
    end

407
    def keep_artifacts!
408 409 410
      self.update(artifacts_expire_at: nil)
    end

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

415 416
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
417 418 419 420
    end

    private

421
    def update_artifacts_size
422 423
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
424 425
                            else
                              nil
426
                            end
427 428
    end

429 430 431 432 433
    def erase_trace!
      self.trace = nil
    end

    def update_erased!(user = nil)
434
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
435 436
    end

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

    def build_attributes_from_config
      return {} unless pipeline.config_processor
459

460 461
      pipeline.config_processor.build_attributes(name)
    end
462 463
  end
end