BigW Consortium Gitlab

build.rb 15.1 KB
Newer Older
1
module Ci
2
  class Build < CommitStatus
3
    include TokenAuthenticatable
4
    include AfterCommitQueue
5
    include Presentable
6

7 8
    belongs_to :runner
    belongs_to :trigger_request
9
    belongs_to :erased_by, class_name: 'User'
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,
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
24

Douwe Maan committed
25 26
    delegate :name, to: :project, prefix: true

27
    validates :coverage, numericality: true, allow_blank: true
Douwe Maan committed
28
    validates :ref, presence: true
29 30

    scope :unstarted, ->() { where(runner_id: nil) }
31
    scope :ignore_failures, ->() { where(allow_failure: false) }
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]) }
37

38
    mount_uploader :artifacts_file, ArtifactUploader
39
    mount_uploader :artifacts_metadata, ArtifactUploader
40

41 42
    acts_as_taggable

43 44
    add_authentication_token_field :token

45
    before_save :update_artifacts_size, if: :artifacts_file_changed?
46
    before_save :ensure_token
47
    before_destroy { unscoped_project }
48

49
    after_create :execute_hooks
50 51
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy
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

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)
68 69 70
      end
    end

71
    state_machine :status do
72 73
      event :actionize do
        transition created: :manual
74 75
      end

76 77
      after_transition any => [:pending] do |build|
        build.run_after_commit do
Kim "BKC" Carlbäcker committed
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
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
99

100 101
      before_transition any => [:failed] do |build|
        next if build.retries_max.zero?
102

103 104
        if build.retries_count < build.retries_max
          Ci::Build.retry(build, build.user)
105 106
        end
      end
107 108
    end

109
    def detailed_status(current_user)
110 111 112
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
113 114
    end

115
    def other_actions
116
      pipeline.manual_actions.where.not(name: name)
117 118
    end

119
    def playable?
120
      action? && (manual? || complete?)
121 122
    end

123
    def action?
124 125 126
      self.when == 'manual'
    end

127
    def play(current_user)
128 129 130
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
131 132
    end

Kamil Trzcinski committed
133 134 135 136
    def cancelable?
      active?
    end

Kamil Trzcinski committed
137
    def retryable?
138
      success? || failed? || canceled?
Kamil Trzcinski committed
139
    end
140 141 142 143 144 145 146 147

    def retries_count
      pipeline.builds.retried.where(name: self.name).count
    end

    def retries_max
      self.options.fetch(:retry, 0).to_i
    end
Kamil Trzcinski committed
148

149 150
    def latest?
      !retried?
151 152
    end

153
    def expanded_environment_name
154
      ExpandVariables.expand(environment, simple_variables) if environment
155 156
    end

157
    def has_environment?
158
      environment.present?
159 160
    end

161
    def starts_environment?
162
      has_environment? && self.environment_action == 'start'
163 164 165
    end

    def stops_environment?
166
      has_environment? && self.environment_action == 'stop'
167 168 169
    end

    def environment_action
170
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
171 172 173 174
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
175
    end
176

177 178
    def depends_on_builds
      # Get builds of the same type
179
      latest_builds = self.pipeline.builds.latest
180 181 182 183 184

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

185
    def timeout
186
      project.build_timeout
187 188
    end

189 190 191 192 193 194
    # 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
195
    #   * First/Last Character is not a hyphen
196
    def ref_slug
197 198 199 200
      ref.to_s
          .downcase
          .gsub(/[^a-z0-9]/, '-')[0..62]
          .gsub(/(\A-+|-+\z)/, '')
201 202
    end

203
    # Variables whose value does not depend on environment
204
    def simple_variables
Lin Jen-Shin committed
205 206 207 208 209 210
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
211
      variables = predefined_variables
212 213 214 215 216 217 218
      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
Shinya Maeda committed
219
      variables += project.group.secret_variables_for(ref, project).map(&:to_runner_variable) if project.group
Lin Jen-Shin committed
220
      variables += secret_variables(environment: environment)
221
      variables += trigger_request.user_variables if trigger_request
222
      variables += pipeline.variables.map(&:to_runner_variable)
Shinya Maeda committed
223
      variables += pipeline.pipeline_schedule.job_variables if pipeline.pipeline_schedule
Lin Jen-Shin committed
224
      variables += persisted_environment_variables if environment
225

Lin Jen-Shin committed
226
      variables
227 228
    end

229
    def merge_request
230
      return @merge_request if defined?(@merge_request)
Z.J. van de Weg committed
231

232 233 234 235 236
      @merge_request ||=
        begin
          merge_requests = MergeRequest.includes(:merge_request_diff)
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z.J. van de Weg committed
237
            .reorder(iid: :desc)
238 239

          merge_requests.find do |merge_request|
240
            merge_request.commit_shas.include?(pipeline.sha)
241 242
          end
        end
243 244
    end

245
    def repo_url
246
      auth = "gitlab-ci-token:#{ensure_token!}@"
247 248 249
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
250 251 252
    end

    def allow_git_fetch
253
      project.build_allow_git_fetch
254 255 256
    end

    def update_coverage
257
      coverage = trace.extract_coverage(coverage_regex)
258
      update_attributes(coverage: coverage) if coverage.present?
259 260
    end

261 262
    def trace
      Gitlab::Ci::Trace.new(self)
263 264
    end

265
    def has_trace?
266
      trace.exist?
267 268
    end

269 270
    def trace=(data)
      raise NotImplementedError
Tomasz Maczukin committed
271 272
    end

273 274
    def old_trace
      read_attribute(:trace)
275 276
    end

277 278 279
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
280 281
    end

282 283 284 285
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

286
    def valid_token?(token)
287
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
288 289
    end

290 291 292 293
    def has_tags?
      tag_list.any?
    end

294
    def any_runners_online?
295
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
296 297
    end

298
    def stuck?
299 300 301
      pending? && !any_runners_online?
    end

302
    def execute_hooks
303
      return unless project
304
      build_data = Gitlab::DataBuilder::Build.build(self)
305 306
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
307
      PagesService.new(build_data).execute
Josh Frye committed
308
      project.running_or_pending_build_count(force: true)
309 310
    end

311
    def artifacts?
312
      !artifacts_expired? && artifacts_file.exists?
313 314
    end

315
    def artifacts_metadata?
316
      artifacts? && artifacts_metadata.exists?
317 318
    end

319
    def artifacts_metadata_entry(path, **options)
320 321 322 323 324 325
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
326 327
    end

328 329 330
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
331
      save
332 333
    end

334 335 336
    def erase(opts = {})
      return false unless erasable?

337
      erase_artifacts!
338 339 340 341 342 343 344 345 346 347 348 349
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

350
    def artifacts_expired?
351
      artifacts_expire_at && artifacts_expire_at < Time.now
352 353
    end

354 355 356 357 358
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
359 360
      self.artifacts_expire_at =
        if value
361
          ChronicDuration.parse(value)&.seconds&.from_now
362
        end
363 364
    end

365
    def has_expiring_artifacts?
Z.J. van de Weg committed
366
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
367 368
    end

369
    def keep_artifacts!
370 371 372
      self.update(artifacts_expire_at: nil)
    end

373
    def coverage_regex
374
      super || project.try(:build_coverage_regex)
375 376
    end

377 378
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
379 380
    end

381 382
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
383 384
    end

385 386 387 388 389 390 391 392 393
    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

Lin Jen-Shin committed
394 395 396 397 398
    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

399
    def steps
400 401
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
402 403 404
    end

    def image
405
      Gitlab::Ci::Build::Image.from_image(self)
406 407 408
    end

    def services
409
      Gitlab::Ci::Build::Image.from_services(self)
410 411 412
    end

    def artifacts
413
      [options[:artifacts]]
414 415 416
    end

    def cache
417
      [options[:cache]]
418 419
    end

420
    def credentials
421
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
422 423
    end

424
    def dependencies
425 426
      return [] if empty_dependencies?

427 428
      depended_jobs = depends_on_builds

429
      return depended_jobs unless options[:dependencies].present?
430

431 432
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
433 434 435
      end
    end

436 437 438 439
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

440 441 442 443 444 445 446 447 448
    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

449 450
    private

451
    def update_artifacts_size
452 453
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
454 455
                            else
                              nil
456
                            end
457 458
    end

459
    def erase_trace!
460
      trace.erase!
461 462 463
    end

    def update_erased!(user = nil)
464
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
465 466
    end

467
    def unscoped_project
468
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
469 470
    end

471 472
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

473
    def predefined_variables
474 475 476
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
477 478 479 480 481 482 483
        { 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.J. van de Weg committed
484
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
485 486 487 488 489 490 491 492 493 494 495 496 497
        { 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

498
    def persisted_environment_variables
499 500
      return [] unless persisted_environment

501 502
      variables = persisted_environment.predefined_variables

503 504 505
      # 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.
506
      variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url
507 508

      variables
509 510
    end

511 512
    def legacy_variables
      variables = [
513 514 515 516 517
        { 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 },
518
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
519
        { key: 'CI_BUILD_NAME', value: name, public: true },
520
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
521
      ]
522 523 524 525

      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?
526 527
      variables
    end
528

529
    def environment_url
530
      options&.dig(:environment, :url) || persisted_environment&.external_url
531 532
    end

533 534
    def build_attributes_from_config
      return {} unless pipeline.config_processor
535

536 537
      pipeline.config_processor.build_attributes(name)
    end
538

539
    def update_project_statistics
540 541
      return unless project

542 543
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
544 545 546 547 548 549

    def update_project_statistics_after_save
      if previous_changes.include?('artifacts_size')
        update_project_statistics
      end
    end
550 551
  end
end