build.rb 10.5 KB
Newer Older
D
Douwe Maan 已提交
1 2
# == Schema Information
#
D
Dmitriy Zaporozhets 已提交
3
# Table name: ci_builds
D
Douwe Maan 已提交
4 5 6 7 8 9 10 11 12 13 14
#
#  id                 :integer          not null, primary key
#  project_id         :integer
#  status             :string(255)
#  finished_at        :datetime
#  trace              :text
#  created_at         :datetime
#  updated_at         :datetime
#  started_at         :datetime
#  runner_id          :integer
#  coverage           :float
D
Dmitriy Zaporozhets 已提交
15
#  commit_id          :integer
D
Douwe Maan 已提交
16 17 18
#  commands           :text
#  job_id             :integer
#  name               :string(255)
D
Dmitriy Zaporozhets 已提交
19
#  deploy             :boolean          default(FALSE)
D
Douwe Maan 已提交
20 21 22 23
#  options            :text
#  allow_failure      :boolean          default(FALSE), not null
#  stage              :string(255)
#  trigger_request_id :integer
D
Dmitriy Zaporozhets 已提交
24 25 26 27 28 29 30 31
#  stage_idx          :integer
#  tag                :boolean
#  ref                :string(255)
#  user_id            :integer
#  type               :string(255)
#  target_url         :string(255)
#  description        :string(255)
#  artifacts_file     :text
S
Stan Hu 已提交
32
#  gl_project_id      :integer
33
#  artifacts_metadata :text
34 35 36
#  erased             :boolean          default(FALSE)
#  erased_by_id       :integer
#  erased_at          :datetime
D
Douwe Maan 已提交
37 38 39
#

module Ci
K
Kamil Trzcinski 已提交
40
  class Build < CommitStatus
41
    include Gitlab::Application.routes.url_helpers
42 43
    include Eraseable

D
Douwe Maan 已提交
44 45 46 47 48 49 50 51
    LAZY_ATTRIBUTES = ['trace']

    belongs_to :runner, class_name: 'Ci::Runner'
    belongs_to :trigger_request, class_name: 'Ci::TriggerRequest'

    serialize :options

    validates :coverage, numericality: true, allow_blank: true
K
Kamil Trzcinski 已提交
52
    validates_presence_of :ref
D
Douwe Maan 已提交
53 54

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
55
    scope :ignore_failures, ->() { where(allow_failure: false) }
K
Kamil Trzcinski 已提交
56
    scope :similar, ->(build) { where(ref: build.ref, tag: build.tag, trigger_request_id: build.trigger_request_id) }
D
Douwe Maan 已提交
57

K
Kamil Trzcinski 已提交
58
    mount_uploader :artifacts_file, ArtifactUploader
59
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
60

D
Douwe Maan 已提交
61 62 63 64 65
    acts_as_taggable

    # To prevent db load megabytes of data from trace
    default_scope -> { select(Ci::Build.columns_without_lazy) }

G
Grzegorz Bizon 已提交
66 67
    before_destroy { project }

D
Douwe Maan 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    class << self
      def columns_without_lazy
        (column_names - LAZY_ATTRIBUTES).map do |column_name|
          "#{table_name}.#{column_name}"
        end
      end

      def last_month
        where('created_at > ?', Date.today - 1.month)
      end

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

      def create_from(build)
        new_build = build.dup
K
Kamil Trzcinski 已提交
85
        new_build.status = 'pending'
D
Douwe Maan 已提交
86
        new_build.runner_id = nil
K
Kamil Trzcinski 已提交
87
        new_build.trigger_request_id = nil
D
Douwe Maan 已提交
88 89 90 91
        new_build.save
      end

      def retry(build)
K
Kamil Trzcinski 已提交
92
        new_build = Ci::Build.new(status: 'pending')
K
Kamil Trzcinski 已提交
93 94
        new_build.ref = build.ref
        new_build.tag = build.tag
D
Douwe Maan 已提交
95 96 97
        new_build.options = build.options
        new_build.commands = build.commands
        new_build.tag_list = build.tag_list
K
Kamil Trzcinski 已提交
98
        new_build.gl_project_id = build.gl_project_id
D
Douwe Maan 已提交
99 100 101 102
        new_build.commit_id = build.commit_id
        new_build.name = build.name
        new_build.allow_failure = build.allow_failure
        new_build.stage = build.stage
K
Kamil Trzcinski 已提交
103
        new_build.stage_idx = build.stage_idx
D
Douwe Maan 已提交
104 105 106 107 108 109 110
        new_build.trigger_request = build.trigger_request
        new_build.save
        new_build
      end
    end

    state_machine :status, initial: :pending do
111 112 113 114
      after_transition pending: :running do |build, transition|
        build.execute_hooks
      end

D
Douwe Maan 已提交
115
      after_transition any => [:success, :failed, :canceled] do |build, transition|
K
Kamil Trzcinski 已提交
116
        return unless build.project
117

K
Kamil Trzcinski 已提交
118
        build.update_coverage
119 120
        build.commit.create_next_builds(build)
        build.execute_hooks
D
Douwe Maan 已提交
121 122 123
      end
    end

K
Kamil Trzcinski 已提交
124 125
    def ignored?
      failed? && allow_failure?
K
Kamil Trzcinski 已提交
126 127
    end

K
Kamil Trzcinski 已提交
128
    def retryable?
K
Kamil Trzcinski 已提交
129
      project.builds_enabled? && commands.present?
K
Kamil Trzcinski 已提交
130 131 132 133 134 135
    end

    def retried?
      !self.commit.latest_builds_for_ref(self.ref).include?(self)
    end

136 137 138 139 140 141 142 143
    def depends_on_builds
      # Get builds of the same type
      latest_builds = self.commit.builds.similar(self).latest

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

D
Douwe Maan 已提交
144 145
    def trace_html
      html = Ci::Ansi2html::convert(trace) if trace.present?
G
Guilherme Garnier 已提交
146
      html || ''
D
Douwe Maan 已提交
147 148 149
    end

    def timeout
K
Kamil Trzcinski 已提交
150
      project.build_timeout
D
Douwe Maan 已提交
151 152 153
    end

    def variables
154
      predefined_variables + yaml_variables + project_variables + trigger_variables
D
Douwe Maan 已提交
155 156
    end

157 158 159 160 161 162 163 164 165 166
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
                                   .where(source_branch: ref, source_project_id: commit.gl_project_id)
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
        merge_request.commits.any? { |ci| ci.id == commit.sha }
      end
    end

D
Douwe Maan 已提交
167
    def project_id
K
Kamil Trzcinski 已提交
168
      commit.project.id
D
Douwe Maan 已提交
169 170 171 172 173 174 175
    end

    def project_name
      project.name
    end

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

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

    def update_coverage
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 trace_empty?
      raw_trace.blank?
    end

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

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

    def trace=(trace)
237 238
      unless Dir.exists?(dir_to_trace)
        FileUtils.mkdir_p(dir_to_trace)
D
Douwe Maan 已提交
239 240 241 242 243 244 245
      end

      File.write(path_to_trace, trace)
    end

    def dir_to_trace
      File.join(
V
Valery Sizov 已提交
246
        Settings.gitlab_ci.builds_path,
D
Douwe Maan 已提交
247 248 249 250 251 252 253 254 255
        created_at.utc.strftime("%Y_%m"),
        project.id.to_s
      )
    end

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

256 257 258
    ##
    # Deprecated
    #
259 260 261
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
262 263 264 265 266 267 268 269 270 271 272
    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
    #
273 274 275
    # This is a hotfix for CI build data integrity, see #4246
    # Should be removed in 8.4, after CI files migration has been done.
    #
276 277 278 279
    def old_path_to_trace
      "#{old_dir_to_trace}/#{id}.log"
    end

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    ##
    # 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 已提交
305
    def token
K
Kamil Trzcinski 已提交
306
      project.runners_token
K
Kamil Trzcinski 已提交
307 308 309
    end

    def valid_token? token
K
Kamil Trzcinski 已提交
310
      project.valid_runners_token? token
K
Kamil Trzcinski 已提交
311 312
    end

K
Kamil Trzcinski 已提交
313
    def target_url
314
      namespace_project_build_url(project.namespace, project, self)
K
Kamil Trzcinski 已提交
315 316
    end

K
Kamil Trzcinski 已提交
317 318
    def cancel_url
      if active?
319
        cancel_namespace_project_build_path(project.namespace, project, self)
K
Kamil Trzcinski 已提交
320 321 322 323
      end
    end

    def retry_url
K
Kamil Trzcinski 已提交
324
      if retryable?
325
        retry_namespace_project_build_path(project.namespace, project, self)
K
Kamil Trzcinski 已提交
326 327 328
      end
    end

329 330 331 332 333 334 335 336 337 338 339 340
    def can_be_served?(runner)
      (tag_list - runner.tag_list).empty?
    end

    def any_runners_online?
      project.any_runners? { |runner| runner.active? && runner.online? && can_be_served?(runner) }
    end

    def show_warning?
      pending? && !any_runners_online?
    end

341 342
    def execute_hooks
      build_data = Gitlab::BuildDataBuilder.build(self)
K
Kamil Trzcinski 已提交
343 344
      project.execute_hooks(build_data.dup, :build_hooks)
      project.execute_services(build_data.dup, :build_hooks)
345 346
    end

347 348 349 350 351
    def artifacts?
      artifacts_file.exists?
    end

    def artifacts_download_url
352 353 354
      if artifacts?
        download_namespace_project_build_artifacts_path(project.namespace, project, self)
      end
355 356 357
    end

    def artifacts_browse_url
358
      if artifacts_metadata?
359 360
        browse_namespace_project_build_artifacts_path(project.namespace, project, self)
      end
361 362
    end

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

367 368
    def artifacts_metadata_entry(path, **options)
      Gitlab::Ci::Build::Artifacts::Metadata.new(artifacts_metadata.path, path, **options).to_entry
369 370
    end

D
Douwe Maan 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383
    private

    def yaml_variables
      if commit.config_processor
        commit.config_processor.variables.map do |key, value|
          { key: key, value: value, public: true }
        end
      else
        []
      end
    end

    def project_variables
384
      project.variables.map do |variable|
D
Douwe Maan 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397
        { 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
398 399 400

    def predefined_variables
      variables = []
401
      variables << { key: :CI_BUILD_TAG, value: ref, public: true } if tag?
402 403 404 405 406
      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
D
Douwe Maan 已提交
407 408
  end
end