build.rb 14.3 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
3
    include TokenAuthenticatable
4
    include AfterCommitQueue
R
Rémy Coutable 已提交
5
    include Presentable
6

7 8
    belongs_to :runner
    belongs_to :trigger_request
9
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
10

11
    has_many :deployments, as: :deployable
12
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
13

14 15 16 17
    # The "environment" field for builds is a String, and is the unexpanded name
    def persisted_environment
      @persisted_environment ||= Environment.find_by(
        name: expanded_environment_name,
K
Kamil Trzciński 已提交
18
        project: project
19 20 21
      )
    end

22 23
    serialize :options # rubocop:disable Cop/ActiverecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiverecordSerialize
D
Douwe Maan 已提交
24

D
Douwe Maan 已提交
25 26
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
27
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
28
    validates :ref, presence: true
D
Douwe Maan 已提交
29 30

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
31
    scope :ignore_failures, ->() { where(allow_failure: false) }
L
Lin Jen-Shin 已提交
32
    scope :with_artifacts, ->() { where.not(artifacts_file: [nil, '']) }
33
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
34
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
35
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
36
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
D
Douwe Maan 已提交
37

K
Kamil Trzcinski 已提交
38
    mount_uploader :artifacts_file, ArtifactUploader
39
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
40

D
Douwe Maan 已提交
41 42
    acts_as_taggable

43 44
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
45
    before_save :update_artifacts_size, if: :artifacts_file_changed?
46
    before_save :ensure_token
47
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
48

K
Kamil Trzcinski 已提交
49
    after_create :execute_hooks
50 51
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy
D
Douwe Maan 已提交
52 53

    class << self
54 55 56 57 58 59
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

D
Douwe Maan 已提交
60 61 62 63
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

64
      def retry(build, current_user)
65 66 67
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
68 69 70
      end
    end

71
    state_machine :status do
72 73
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
74 75
      end

76 77
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
78
          BuildQueueWorker.perform_async(id)
79 80 81
        end
      end

82
      after_transition pending: :running do |build|
83 84 85
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
86 87
      end

88
      after_transition any => [:success, :failed, :canceled] do |build|
89
        build.run_after_commit do
90
          BuildFinishedWorker.perform_async(id)
91
        end
D
Douwe Maan 已提交
92
      end
93

94
      after_transition any => [:success] do |build|
95 96
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
97 98
        end
      end
D
Douwe Maan 已提交
99 100
    end

101
    def detailed_status(current_user)
102 103 104
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
105 106
    end

107
    def other_actions
108
      pipeline.manual_actions.where.not(name: name)
109 110
    end

111
    def playable?
112
      action? && (manual? || complete?)
K
Kamil Trzcinski 已提交
113 114
    end

115
    def action?
116 117 118
      self.when == 'manual'
    end

119
    def play(current_user)
120 121 122
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
123 124
    end

K
Kamil Trzcinski 已提交
125 126 127 128
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
129
    def retryable?
130
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
131 132
    end

133 134
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
135 136
    end

137
    def expanded_environment_name
138
      ExpandVariables.expand(environment, simple_variables) if environment
139 140
    end

141 142
    def environment_url
      return @environment_url if defined?(@environment_url)
143

144
      @environment_url =
145
        if unexpanded_url = options&.dig(:environment, :url)
146 147 148 149
          ExpandVariables.expand(unexpanded_url, simple_variables)
        else
          persisted_environment&.external_url
        end
150 151
    end

152
    def has_environment?
153
      environment.present?
154 155
    end

156
    def starts_environment?
157
      has_environment? && self.environment_action == 'start'
158 159 160
    end

    def stops_environment?
161
      has_environment? && self.environment_action == 'stop'
162 163 164
    end

    def environment_action
165
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
166 167 168 169
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
170
    end
171

172 173
    def depends_on_builds
      # Get builds of the same type
174
      latest_builds = self.pipeline.builds.latest
175 176 177 178 179

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

D
Douwe Maan 已提交
180
    def timeout
K
Kamil Trzcinski 已提交
181
      project.build_timeout
D
Douwe Maan 已提交
182 183
    end

N
Nick Thomas 已提交
184 185 186 187 188 189
    # A slugified version of the build ref, suitable for inclusion in URLs and
    # domain names. Rules:
    #
    #   * Lowercased
    #   * Anything not matching [a-z0-9-] is replaced with a -
    #   * Maximum length is 63 bytes
190
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
191 192
    def ref_slug
      slugified = ref.to_s.downcase
S
Stefan Hanreich 已提交
193 194
      slugified.gsub!(/[^a-z0-9]/, '-')
      slugified[0..62].gsub(/(\A-+|-+\z)/, '')
N
Nick Thomas 已提交
195 196
    end

197 198
    # Variables whose value does not depend on other variables
    def simple_variables
199
      variables = predefined_variables
200 201 202 203 204 205 206
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
      variables += project.deployment_variables if has_environment?
      variables += yaml_variables
      variables += user_variables
207
      variables += project.secret_variables_for(ref).map(&:to_runner_variable)
208
      variables += trigger_request.user_variables if trigger_request
209
      variables
D
Douwe Maan 已提交
210 211
    end

212 213
    # All variables, including those dependent on other variables
    def variables
214
      simple_variables.concat(persisted_environment_variables)
215 216
    end

217
    def merge_request
Z
Z.J. van de Weg 已提交
218
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
219

220 221 222 223 224
      @merge_request ||=
        begin
          merge_requests = MergeRequest.includes(:merge_request_diff)
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
225
            .reorder(iid: :desc)
226 227 228 229 230

          merge_requests.find do |merge_request|
            merge_request.commits_sha.include?(pipeline.sha)
          end
        end
231 232
    end

D
Douwe Maan 已提交
233
    def repo_url
K
Kamil Trzcinski 已提交
234
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
235 236 237
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
238 239 240
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
241
      project.build_allow_git_fetch
D
Douwe Maan 已提交
242 243 244
    end

    def update_coverage
245
      coverage = trace.extract_coverage(coverage_regex)
246
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
247 248
    end

249 250
    def trace
      Gitlab::Ci::Trace.new(self)
251 252
    end

253
    def has_trace?
254
      trace.exist?
T
Tomasz Maczukin 已提交
255 256
    end

257 258
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
259 260
    end

261 262
    def old_trace
      read_attribute(:trace)
263 264
    end

265 266 267
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
268 269
    end

270 271 272 273
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
274
    def valid_token?(token)
275
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
276 277
    end

278 279 280 281
    def has_tags?
      tag_list.any?
    end

282
    def any_runners_online?
283
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
284 285
    end

K
Kamil Trzcinski 已提交
286
    def stuck?
287 288 289
      pending? && !any_runners_online?
    end

290
    def execute_hooks
291
      return unless project
292
      build_data = Gitlab::DataBuilder::Build.build(self)
293 294
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
295
      PagesService.new(build_data).execute
J
Josh Frye 已提交
296
      project.running_or_pending_build_count(force: true)
297 298
    end

299
    def artifacts?
300
      !artifacts_expired? && artifacts_file.exists?
301 302
    end

303
    def artifacts_metadata?
304
      artifacts? && artifacts_metadata.exists?
305 306
    end

307
    def artifacts_metadata_entry(path, **options)
308 309 310 311 312 313
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
314 315
    end

316 317 318
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
319
      save
320 321
    end

322 323 324
    def erase(opts = {})
      return false unless erasable?

325
      erase_artifacts!
326 327 328 329 330 331 332 333 334 335 336 337
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

338
    def artifacts_expired?
339
      artifacts_expire_at && artifacts_expire_at < Time.now
340 341
    end

342 343 344 345 346
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
347 348
      self.artifacts_expire_at =
        if value
349
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
350
        end
351 352
    end

353
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
354
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
355 356
    end

357
    def keep_artifacts!
358 359 360
      self.update(artifacts_expire_at: nil)
    end

361
    def coverage_regex
362
      super || project.try(:build_coverage_regex)
363 364
    end

365 366
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
367 368
    end

369 370
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
371 372
    end

373 374 375 376 377 378 379 380 381
    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

382
    def steps
T
Tomasz Maczukin 已提交
383 384
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
385 386 387
    end

    def image
388
      Gitlab::Ci::Build::Image.from_image(self)
389 390 391
    end

    def services
392
      Gitlab::Ci::Build::Image.from_services(self)
393 394 395
    end

    def artifacts
396
      [options[:artifacts]]
397 398 399
    end

    def cache
400
      [options[:cache]]
401 402
    end

403
    def credentials
404
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
405 406
    end

T
Tomasz Maczukin 已提交
407
    def dependencies
408 409
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
410 411
      depended_jobs = depends_on_builds

412
      return depended_jobs unless options[:dependencies].present?
T
Tomasz Maczukin 已提交
413

414 415
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
416 417 418
      end
    end

419 420 421 422
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

423 424 425 426 427 428 429 430 431
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
      trace
    end

432 433
    private

L
Lin Jen-Shin 已提交
434
    def update_artifacts_size
435 436
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
437 438
                            else
                              nil
439
                            end
L
Lin Jen-Shin 已提交
440 441
    end

442
    def erase_trace!
443
      trace.erase!
444 445 446
    end

    def update_erased!(user = nil)
447
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
448 449
    end

450
    def unscoped_project
K
Kamil Trzciński 已提交
451
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
452 453
    end

454 455
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

456
    def predefined_variables
457 458 459
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
460 461 462 463 464 465 466
        { 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 },
        { key: 'CI_JOB_ID', value: id.to_s, public: true },
        { key: 'CI_JOB_NAME', value: name, public: true },
        { key: 'CI_JOB_STAGE', value: stage, public: true },
        { key: 'CI_JOB_TOKEN', value: token, public: false },
Z
Z.J. van de Weg 已提交
467
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
468 469 470 471 472 473 474 475 476 477 478 479 480
        { key: 'CI_COMMIT_REF_NAME', value: ref, public: true },
        { key: 'CI_COMMIT_REF_SLUG', value: ref_slug, public: true },
        { key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER, public: true },
        { key: 'CI_REGISTRY_PASSWORD', value: token, public: false },
        { key: 'CI_REPOSITORY_URL', value: repo_url, public: false }
      ]

      variables << { key: "CI_COMMIT_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_PIPELINE_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_JOB_MANUAL", value: 'true', public: true } if action?
      variables.concat(legacy_variables)
    end

481
    def persisted_environment_variables
482 483
      return [] unless persisted_environment

L
Lin Jen-Shin 已提交
484 485
      variables = persisted_environment.predefined_variables

486
      if url = environment_url
487
        variables << { key: 'CI_ENVIRONMENT_URL', value: url, public: true }
488
      end
L
Lin Jen-Shin 已提交
489 490

      variables
491 492
    end

493 494
    def legacy_variables
      variables = [
495 496 497 498 499
        { 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 },
N
Nick Thomas 已提交
500
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
501
        { key: 'CI_BUILD_NAME', value: name, public: true },
502
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
503
      ]
504 505 506 507

      variables << { key: "CI_BUILD_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_BUILD_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_BUILD_MANUAL", value: 'true', public: true } if action?
508 509
      variables
    end
510 511 512

    def build_attributes_from_config
      return {} unless pipeline.config_processor
513

514 515
      pipeline.config_processor.build_attributes(name)
    end
516

M
Markus Koller 已提交
517
    def update_project_statistics
518 519
      return unless project

M
Markus Koller 已提交
520 521
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
522 523 524 525 526 527

    def update_project_statistics_after_save
      if previous_changes.include?('artifacts_size')
        update_project_statistics
      end
    end
D
Douwe Maan 已提交
528 529
  end
end