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
29 30 31 32
    validates :environment_url,
              length: { maximum: 255 },
              allow_nil: true,
              addressable_url: true
D
Douwe Maan 已提交
33 34

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

K
Kamil Trzcinski 已提交
42
    mount_uploader :artifacts_file, ArtifactUploader
43
    mount_uploader :artifacts_metadata, ArtifactUploader
K
Kamil Trzcinski 已提交
44

D
Douwe Maan 已提交
45 46
    acts_as_taggable

47 48
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
49
    before_save :update_artifacts_size, if: :artifacts_file_changed?
50
    before_save :ensure_token
51
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
52

K
Kamil Trzcinski 已提交
53
    after_create :execute_hooks
M
Markus Koller 已提交
54 55
    after_save :update_project_statistics, if: :artifacts_size_changed?
    after_destroy :update_project_statistics
D
Douwe Maan 已提交
56 57 58 59 60 61

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

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

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

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

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

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

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

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

105
    def other_actions
106
      pipeline.manual_actions.where.not(name: name)
107 108
    end

109
    def playable?
110
      action? && manual?
K
Kamil Trzcinski 已提交
111 112
    end

113
    def action?
114 115 116
      self.when == 'manual'
    end

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

K
Kamil Trzcinski 已提交
123 124 125 126
    def cancelable?
      active?
    end

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

131 132
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
133 134
    end

135
    def expanded_environment_name
136
      ExpandVariables.expand(environment, simple_variables) if environment
137 138
    end

139 140 141 142 143
    def expanded_environment_url
      ExpandVariables.expand(environment_url, simple_variables) if
        environment_url
    end

144
    def has_environment?
145
      environment.present?
146 147
    end

148
    def starts_environment?
149
      has_environment? && self.environment_action == 'start'
150 151 152
    end

    def stops_environment?
153
      has_environment? && self.environment_action == 'stop'
154 155 156
    end

    def environment_action
157
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
158 159 160 161
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
162
    end
163

164 165
    def depends_on_builds
      # Get builds of the same type
166
      latest_builds = self.pipeline.builds.latest
167 168 169 170 171

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

D
Douwe Maan 已提交
172
    def timeout
K
Kamil Trzcinski 已提交
173
      project.build_timeout
D
Douwe Maan 已提交
174 175
    end

N
Nick Thomas 已提交
176 177 178 179 180 181 182 183 184 185 186
    # 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

187 188
    # Variables whose value does not depend on other variables
    def simple_variables
189
      variables = predefined_variables
190 191 192 193 194 195 196 197 198
      variables.concat(project.predefined_variables)
      variables.concat(pipeline.predefined_variables)
      variables.concat(runner.predefined_variables) if runner
      variables.concat(project.container_registry_variables)
      variables.concat(project.deployment_variables) if has_environment?
      variables.concat(yaml_variables)
      variables.concat(user_variables)
      variables.concat(project.secret_variables)
      variables.concat(trigger_request.user_variables) if trigger_request
199
      variables
D
Douwe Maan 已提交
200 201
    end

202 203 204
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
205 206
      variables.concat(persisted_environment_variables) if
        persisted_environment
207 208 209
      variables
    end

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

      merge_requests.find do |merge_request|
217
        merge_request.commits_sha.include?(pipeline.sha)
218 219 220
      end
    end

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

    def allow_git_fetch
K
Kamil Trzcinski 已提交
229
      project.build_allow_git_fetch
D
Douwe Maan 已提交
230 231 232
    end

    def update_coverage
233
      coverage = trace.extract_coverage(coverage_regex)
234
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
235 236
    end

237 238
    def trace
      Gitlab::Ci::Trace.new(self)
239 240
    end

241
    def has_trace?
242
      trace.exist?
T
Tomasz Maczukin 已提交
243 244
    end

245 246
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
247 248
    end

249 250
    def old_trace
      read_attribute(:trace)
251 252
    end

253 254 255
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
256 257
    end

258 259 260 261
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

262 263 264 265 266 267 268 269 270 271 272
    ##
    # 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
273 274 275 276 277 278 279
      # 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

280
      old = File.join(created_at.utc.strftime('%Y_%m'),
281
                      the_project.ci_id.to_s,
282 283 284
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
285
      return old if the_project.ci_id && File.directory?(old_store)
286 287 288

      File.join(
        created_at.utc.strftime('%Y_%m'),
289
        the_project.id.to_s,
290 291 292 293
        id.to_s
      )
    end

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

298 299 300 301
    def has_tags?
      tag_list.any?
    end

302
    def any_runners_online?
303
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
304 305
    end

K
Kamil Trzcinski 已提交
306
    def stuck?
307 308 309
      pending? && !any_runners_online?
    end

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

319
    def artifacts?
320
      !artifacts_expired? && artifacts_file.exists?
321 322
    end

323
    def artifacts_metadata?
324
      artifacts? && artifacts_metadata.exists?
325 326
    end

327
    def artifacts_metadata_entry(path, **options)
328 329 330 331 332 333
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
334 335
    end

336 337 338
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
339
      save
340 341
    end

342 343 344
    def erase(opts = {})
      return false unless erasable?

345
      erase_artifacts!
346 347 348 349 350 351 352 353 354 355 356 357
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

358
    def artifacts_expired?
359
      artifacts_expire_at && artifacts_expire_at < Time.now
360 361
    end

362 363 364 365 366
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

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

373 374 375 376
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

377
    def keep_artifacts!
378 379 380
      self.update(artifacts_expire_at: nil)
    end

381
    def coverage_regex
382
      super || project.try(:build_coverage_regex)
383 384
    end

385 386
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
387 388
    end

389 390
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
391 392
    end

393 394 395 396 397 398 399 400 401
    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

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

    def image
408
      Gitlab::Ci::Build::Image.from_image(self)
409 410 411
    end

    def services
412
      Gitlab::Ci::Build::Image.from_services(self)
413 414 415
    end

    def artifacts
416
      [options[:artifacts]]
417 418 419
    end

    def cache
420
      [options[:cache]]
421 422
    end

423
    def credentials
424
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
425 426
    end

T
Tomasz Maczukin 已提交
427
    def dependencies
428 429
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
430 431
      depended_jobs = depends_on_builds

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

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

439 440 441 442
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

443 444 445 446 447 448 449 450 451
    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

452 453
    private

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

462
    def erase_trace!
463
      trace.erase!
464 465 466
    end

    def update_erased!(user = nil)
467
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
468 469
    end

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

474 475
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

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

501
    def persisted_environment_variables
L
Lin Jen-Shin 已提交
502 503
      variables = persisted_environment.predefined_variables

504 505 506 507 508 509 510 511 512
      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 已提交
513 514

      variables
515 516
    end

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

      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?
532 533
      variables
    end
534 535 536

    def build_attributes_from_config
      return {} unless pipeline.config_processor
537

538 539
      pipeline.config_processor.build_attributes(name)
    end
540

M
Markus Koller 已提交
541
    def update_project_statistics
542 543
      return unless project

M
Markus Koller 已提交
544 545
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
D
Douwe Maan 已提交
546 547
  end
end