build.rb 14.5 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
    def has_environment?
142
      environment.present?
143 144
    end

145
    def starts_environment?
146
      has_environment? && self.environment_action == 'start'
147 148 149
    end

    def stops_environment?
150
      has_environment? && self.environment_action == 'stop'
151 152 153
    end

    def environment_action
154
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
155 156 157 158
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
159
    end
160

161 162
    def depends_on_builds
      # Get builds of the same type
163
      latest_builds = self.pipeline.builds.latest
164 165 166 167 168

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

D
Douwe Maan 已提交
169
    def timeout
K
Kamil Trzcinski 已提交
170
      project.build_timeout
D
Douwe Maan 已提交
171 172
    end

N
Nick Thomas 已提交
173 174 175 176 177 178
    # 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
179
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
180
    def ref_slug
181 182 183 184
      ref.to_s
          .downcase
          .gsub(/[^a-z0-9]/, '-')[0..62]
          .gsub(/(\A-+|-+\z)/, '')
N
Nick Thomas 已提交
185 186
    end

187
    # Variables whose value does not depend on environment
188
    def simple_variables
L
Lin Jen-Shin 已提交
189 190 191 192 193 194
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
195
      variables = predefined_variables
196 197 198 199 200 201 202
      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
L
Lin Jen-Shin 已提交
203
      variables += secret_variables(environment: environment)
204
      variables += trigger_request.user_variables if trigger_request
L
Lin Jen-Shin 已提交
205
      variables += persisted_environment_variables if environment
D
Douwe Maan 已提交
206

L
Lin Jen-Shin 已提交
207
      variables
208 209
    end

210
    def merge_request
Z
Z.J. van de Weg 已提交
211
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
212

213 214 215 216 217
      @merge_request ||=
        begin
          merge_requests = MergeRequest.includes(:merge_request_diff)
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
218
            .reorder(iid: :desc)
219 220 221 222 223

          merge_requests.find do |merge_request|
            merge_request.commits_sha.include?(pipeline.sha)
          end
        end
224 225
    end

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

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

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

242 243
    def trace
      Gitlab::Ci::Trace.new(self)
244 245
    end

246
    def has_trace?
247
      trace.exist?
T
Tomasz Maczukin 已提交
248 249
    end

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

254 255
    def old_trace
      read_attribute(:trace)
256 257
    end

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

263 264 265 266
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
267
    def valid_token?(token)
268
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
269 270
    end

271 272 273 274
    def has_tags?
      tag_list.any?
    end

275
    def any_runners_online?
276
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
277 278
    end

K
Kamil Trzcinski 已提交
279
    def stuck?
280 281 282
      pending? && !any_runners_online?
    end

283
    def execute_hooks
284
      return unless project
285
      build_data = Gitlab::DataBuilder::Build.build(self)
286 287
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
288
      PagesService.new(build_data).execute
J
Josh Frye 已提交
289
      project.running_or_pending_build_count(force: true)
290 291
    end

292
    def artifacts?
293
      !artifacts_expired? && artifacts_file.exists?
294 295
    end

296
    def artifacts_metadata?
297
      artifacts? && artifacts_metadata.exists?
298 299
    end

300
    def artifacts_metadata_entry(path, **options)
301 302 303 304 305 306
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
307 308
    end

309 310 311
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
312
      save
313 314
    end

315 316 317
    def erase(opts = {})
      return false unless erasable?

318
      erase_artifacts!
319 320 321 322 323 324 325 326 327 328 329 330
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

331
    def artifacts_expired?
332
      artifacts_expire_at && artifacts_expire_at < Time.now
333 334
    end

335 336 337 338 339
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
340 341
      self.artifacts_expire_at =
        if value
342
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
343
        end
344 345
    end

346
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
347
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
348 349
    end

350
    def keep_artifacts!
351 352 353
      self.update(artifacts_expire_at: nil)
    end

354
    def coverage_regex
355
      super || project.try(:build_coverage_regex)
356 357
    end

358 359
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
360 361
    end

362 363
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
364 365
    end

366 367 368 369 370 371 372 373 374
    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

L
Lin Jen-Shin 已提交
375 376 377 378 379
    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

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

    def image
386
      Gitlab::Ci::Build::Image.from_image(self)
387 388 389
    end

    def services
390
      Gitlab::Ci::Build::Image.from_services(self)
391 392 393
    end

    def artifacts
394
      [options[:artifacts]]
395 396 397
    end

    def cache
398
      [options[:cache]]
399 400
    end

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

T
Tomasz Maczukin 已提交
405
    def dependencies
406 407
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
408 409
      depended_jobs = depends_on_builds

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

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

417 418 419 420
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

421 422 423 424 425 426 427 428 429
    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

430 431
    private

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

440
    def erase_trace!
441
      trace.erase!
442 443 444
    end

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

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

452 453
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

454
    def predefined_variables
455 456 457
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
458 459 460 461 462 463 464
        { 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 已提交
465
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
466 467 468 469 470 471 472 473 474 475 476 477 478
        { 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

479
    def persisted_environment_variables
480 481
      return [] unless persisted_environment

L
Lin Jen-Shin 已提交
482 483
      variables = persisted_environment.predefined_variables

484 485 486
      # Here we're passing unexpanded environment_url for runner to expand,
      # and we need to make sure that CI_ENVIRONMENT_NAME and
      # CI_ENVIRONMENT_SLUG so on are available for the URL be expanded.
487
      variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url
L
Lin Jen-Shin 已提交
488 489

      variables
490 491
    end

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

      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?
507 508
      variables
    end
509

510
    def environment_url
511
      options&.dig(:environment, :url) || persisted_environment&.external_url
512 513
    end

514 515
    def build_attributes_from_config
      return {} unless pipeline.config_processor
516

517 518
      pipeline.config_processor.build_attributes(name)
    end
519

M
Markus Koller 已提交
520
    def update_project_statistics
521 522
      return unless project

M
Markus Koller 已提交
523 524
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
525 526 527 528 529 530

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