build.rb 15.0 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

D
Douwe Maan 已提交
22
    serialize :options
23
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables
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).relevant }
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
M
Markus Koller 已提交
50 51
    after_save :update_project_statistics, if: :artifacts_size_changed?
    after_destroy :update_project_statistics
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?
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 143 144 145
    def expanded_environment_url
      ExpandVariables.expand(environment_url, simple_variables) if
        environment_url
    end

146 147 148 149
    def environment_url
      options.dig(:environment, :url)
    end

150
    def has_environment?
151
      environment.present?
152 153
    end

154
    def starts_environment?
155
      has_environment? && self.environment_action == 'start'
156 157 158
    end

    def stops_environment?
159
      has_environment? && self.environment_action == 'stop'
160 161 162
    end

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

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
168
    end
169

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

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

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

N
Nick Thomas 已提交
182 183 184 185 186 187 188 189 190 191 192
    # 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
    def ref_slug
      slugified = ref.to_s.downcase
      slugified.gsub(/[^a-z0-9]/, '-')[0..62]
    end

193 194
    # Variables whose value does not depend on other variables
    def simple_variables
195
      variables = predefined_variables
196 197 198 199 200 201 202 203 204
      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
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
205
      variables
D
Douwe Maan 已提交
206 207
    end

208 209
    # All variables, including those dependent on other variables
    def variables
210
      simple_variables.concat(persisted_environment_variables)
211 212
    end

213 214
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
K
Kamil Trzciński 已提交
215 216
                                   .where(source_branch: ref,
                                          source_project: pipeline.project)
217 218 219
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
220
        merge_request.commits_sha.include?(pipeline.sha)
221 222 223
      end
    end

D
Douwe Maan 已提交
224
    def repo_url
K
Kamil Trzcinski 已提交
225
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
226 227 228
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
229 230 231
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
232
      project.build_allow_git_fetch
D
Douwe Maan 已提交
233 234 235
    end

    def update_coverage
236
      coverage = trace.extract_coverage(coverage_regex)
237
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
238 239
    end

240 241
    def trace
      Gitlab::Ci::Trace.new(self)
242 243
    end

244
    def has_trace?
245
      trace.exist?
T
Tomasz Maczukin 已提交
246 247
    end

248 249
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
250 251
    end

252 253
    def old_trace
      read_attribute(:trace)
254 255
    end

256 257 258
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
259 260
    end

261 262 263 264
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

265 266 267 268 269 270 271 272 273 274 275
    ##
    # 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
276 277 278 279 280 281 282
      # We need the project even if it's soft deleted, because whenever
      # we're really deleting the project, we'll also delete the builds,
      # and in order to delete the builds, we need to know where to find
      # the artifacts, which is depending on the data of the project.
      # We need to retain the project in this case.
      the_project = project || unscoped_project

283
      old = File.join(created_at.utc.strftime('%Y_%m'),
284
                      the_project.ci_id.to_s,
285 286 287
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
288
      return old if the_project.ci_id && File.directory?(old_store)
289 290 291

      File.join(
        created_at.utc.strftime('%Y_%m'),
292
        the_project.id.to_s,
293 294 295 296
        id.to_s
      )
    end

L
Lin Jen-Shin 已提交
297
    def valid_token?(token)
298
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
299 300
    end

301 302 303 304
    def has_tags?
      tag_list.any?
    end

305
    def any_runners_online?
306
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
307 308
    end

K
Kamil Trzcinski 已提交
309
    def stuck?
310 311 312
      pending? && !any_runners_online?
    end

313
    def execute_hooks
314
      return unless project
315
      build_data = Gitlab::DataBuilder::Build.build(self)
316 317
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
318
      PagesService.new(build_data).execute
J
Josh Frye 已提交
319
      project.running_or_pending_build_count(force: true)
320 321
    end

322
    def artifacts?
323
      !artifacts_expired? && artifacts_file.exists?
324 325
    end

326
    def artifacts_metadata?
327
      artifacts? && artifacts_metadata.exists?
328 329
    end

330
    def artifacts_metadata_entry(path, **options)
331 332 333 334 335 336
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
337 338
    end

339 340 341
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
342
      save
343 344
    end

345 346 347
    def erase(opts = {})
      return false unless erasable?

348
      erase_artifacts!
349 350 351 352 353 354 355 356 357 358 359 360
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

361
    def artifacts_expired?
362
      artifacts_expire_at && artifacts_expire_at < Time.now
363 364
    end

365 366 367 368 369
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
370 371
      self.artifacts_expire_at =
        if value
372
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
373
        end
374 375
    end

376 377 378 379
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

380
    def keep_artifacts!
381 382 383
      self.update(artifacts_expire_at: nil)
    end

384
    def coverage_regex
385
      super || project.try(:build_coverage_regex)
386 387
    end

388 389
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
390 391
    end

392 393
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
394 395
    end

396 397 398 399 400 401 402 403 404
    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

405
    def steps
T
Tomasz Maczukin 已提交
406 407
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
408 409 410
    end

    def image
411
      Gitlab::Ci::Build::Image.from_image(self)
412 413 414
    end

    def services
415
      Gitlab::Ci::Build::Image.from_services(self)
416 417 418
    end

    def artifacts
419
      [options[:artifacts]]
420 421 422
    end

    def cache
423
      [options[:cache]]
424 425
    end

426
    def credentials
427
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
428 429
    end

T
Tomasz Maczukin 已提交
430
    def dependencies
431 432
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
433 434
      depended_jobs = depends_on_builds

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

437 438
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
439 440 441
      end
    end

442 443 444 445
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

446 447 448 449 450 451 452 453 454
    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

455 456
    private

L
Lin Jen-Shin 已提交
457
    def update_artifacts_size
458 459
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
460 461
                            else
                              nil
462
                            end
L
Lin Jen-Shin 已提交
463 464
    end

465
    def erase_trace!
466
      trace.erase!
467 468 469
    end

    def update_erased!(user = nil)
470
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
471 472
    end

473
    def unscoped_project
K
Kamil Trzciński 已提交
474
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
475 476
    end

477 478
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

479
    def predefined_variables
480 481 482
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
483 484 485 486 487 488 489
        { 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 已提交
490
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
491 492 493 494 495 496 497 498 499 500 501 502 503
        { 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

504
    def persisted_environment_variables
505 506
      return [] unless persisted_environment

L
Lin Jen-Shin 已提交
507 508
      variables = persisted_environment.predefined_variables

509 510 511 512 513 514 515 516 517
      if environment_url
        variables << { key: 'CI_ENVIRONMENT_URL',
                       value: expanded_environment_url,
                       public: true }
      elsif persisted_environment.external_url.present?
        variables << { key: 'CI_ENVIRONMENT_URL',
                       value: persisted_environment.external_url,
                       public: true }
      end
L
Lin Jen-Shin 已提交
518 519

      variables
520 521
    end

522 523
    def legacy_variables
      variables = [
524 525 526 527 528
        { 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 已提交
529
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
530
        { key: 'CI_BUILD_NAME', value: name, public: true },
531
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
532
      ]
533 534 535 536

      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?
537 538
      variables
    end
539 540 541

    def build_attributes_from_config
      return {} unless pipeline.config_processor
542

543 544
      pipeline.config_processor.build_attributes(name)
    end
545

M
Markus Koller 已提交
546
    def update_project_statistics
547 548
      return unless project

M
Markus Koller 已提交
549 550
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
551 552
  end
end