build.rb 17.4 KB
Newer Older
D
Douwe Maan 已提交
1
module Ci
K
Kamil Trzcinski 已提交
2
  class Build < CommitStatus
Z
Zeger-Jan van de Weg 已提交
3
    prepend ArtifactMigratable
4
    include TokenAuthenticatable
5
    include AfterCommitQueue
R
Rémy Coutable 已提交
6
    include Presentable
S
Shinya Maeda 已提交
7
    include Importable
8

9 10
    MissingDependenciesError = Class.new(StandardError)

11 12
    belongs_to :runner
    belongs_to :trigger_request
13
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
14

15
    has_many :deployments, as: :deployable
16

17
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
18
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
19

Z
Zeger-Jan van de Weg 已提交
20
    has_many :job_artifacts, class_name: 'Ci::JobArtifact', foreign_key: :job_id, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
21 22
    has_one :job_artifacts_archive, -> { where(file_type: Ci::JobArtifact.file_types[:archive]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
    has_one :job_artifacts_metadata, -> { where(file_type: Ci::JobArtifact.file_types[:metadata]) }, class_name: 'Ci::JobArtifact', inverse_of: :job, foreign_key: :job_id
23

24 25 26 27
    # 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 已提交
28
        project: project
29 30 31
      )
    end

32 33
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
34

D
Douwe Maan 已提交
35 36
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
37
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
38
    validates :ref, presence: true
D
Douwe Maan 已提交
39 40

    scope :unstarted, ->() { where(runner_id: nil) }
K
Kamil Trzcinski 已提交
41
    scope :ignore_failures, ->() { where(allow_failure: false) }
42
    scope :with_artifacts, ->() do
K
Kamil Trzcinski 已提交
43 44
      where('(artifacts_file IS NOT NULL AND artifacts_file <> ?) OR EXISTS (?)',
        '', Ci::JobArtifact.select(1).where('ci_builds.id = ci_job_artifacts.job_id'))
45
    end
46
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
47
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
48
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
49
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }
50
    scope :ref_protected, -> { where(protected: true) }
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    scope :matches_tag_ids, -> (tag_ids) do
      matcher = ::ActsAsTaggableOn::Tagging
        .where(taggable_type: CommitStatus)
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id')
        .where.not(tag_id: tag_ids).select('1')

      where("NOT EXISTS (?)", matcher)
    end

    scope :with_any_tags, -> do
      matcher = ::ActsAsTaggableOn::Tagging
        .where(taggable_type: CommitStatus)
        .where(context: 'tags')
        .where('taggable_id = ci_builds.id').select('1')

      where("EXISTS (?)", matcher)
    end

71 72
    mount_uploader :legacy_artifacts_file, LegacyArtifactUploader, mount_on: :artifacts_file
    mount_uploader :legacy_artifacts_metadata, LegacyArtifactUploader, mount_on: :artifacts_metadata
K
Kamil Trzcinski 已提交
73

D
Douwe Maan 已提交
74 75
    acts_as_taggable

76 77
    add_authentication_token_field :token

L
Lin Jen-Shin 已提交
78
    before_save :update_artifacts_size, if: :artifacts_file_changed?
79
    before_save :ensure_token
80
    before_destroy { unscoped_project }
G
Grzegorz Bizon 已提交
81

82
    after_create do |build|
83
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
84 85
    end

86 87
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy
D
Douwe Maan 已提交
88 89

    class << self
90 91 92 93 94 95
      # 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 已提交
96 97 98 99
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

100
      def retry(build, current_user)
101 102 103
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
104 105 106
      end
    end

107
    state_machine :status do
108 109
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
110 111
      end

112 113
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
114
          BuildQueueWorker.perform_async(id)
115 116 117
        end
      end

118
      after_transition pending: :running do |build|
119 120 121
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
122 123
      end

124
      after_transition any => [:success, :failed, :canceled] do |build|
125
        build.run_after_commit do
126
          BuildFinishedWorker.perform_async(id)
127
        end
D
Douwe Maan 已提交
128
      end
129

130
      after_transition any => [:success] do |build|
131 132
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
133 134
        end
      end
135

136
      before_transition any => [:failed] do |build|
137
        next unless build.project
138
        next if build.retries_max.zero?
139

140 141
        if build.retries_count < build.retries_max
          Ci::Build.retry(build, build.user)
142 143
        end
      end
144 145

      before_transition any => [:running] do |build|
146
        build.validates_dependencies! if Feature.enabled?('ci_validates_dependencies')
147
      end
D
Douwe Maan 已提交
148 149
    end

150
    def detailed_status(current_user)
151 152 153
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
154 155
    end

156
    def other_actions
157
      pipeline.manual_actions.where.not(name: name)
158 159
    end

160
    def playable?
161
      action? && (manual? || complete?)
K
Kamil Trzcinski 已提交
162 163
    end

164
    def action?
165 166 167
      self.when == 'manual'
    end

168
    def play(current_user)
169 170 171
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
172 173
    end

K
Kamil Trzcinski 已提交
174 175 176 177
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
178
    def retryable?
179
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
180
    end
181 182 183 184 185 186 187 188

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

    def retries_max
      self.options.fetch(:retry, 0).to_i
    end
K
Kamil Trzcinski 已提交
189

190 191
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
192 193
    end

194
    def expanded_environment_name
195
      ExpandVariables.expand(environment, simple_variables) if environment
196 197
    end

198
    def has_environment?
199
      environment.present?
200 201
    end

202
    def starts_environment?
203
      has_environment? && self.environment_action == 'start'
204 205 206
    end

    def stops_environment?
207
      has_environment? && self.environment_action == 'stop'
208 209 210
    end

    def environment_action
211
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
212 213 214 215
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
216
    end
217

218 219
    def depends_on_builds
      # Get builds of the same type
220
      latest_builds = self.pipeline.builds.latest
221 222 223 224 225

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

D
Douwe Maan 已提交
226
    def timeout
K
Kamil Trzcinski 已提交
227
      project.build_timeout
D
Douwe Maan 已提交
228 229
    end

230
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
231 232 233
      user == current_user
    end

N
Nick Thomas 已提交
234 235 236 237 238 239
    # 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
S
Shinya Maeda 已提交
240
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
241
    def ref_slug
V
vanadium23 已提交
242
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
243 244
    end

245
    # Variables whose value does not depend on environment
246
    def simple_variables
L
Lin Jen-Shin 已提交
247 248 249 250 251 252
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
253
      variables = predefined_variables
254 255 256 257 258
      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?
259
      variables += project.auto_devops_variables
260 261
      variables += yaml_variables
      variables += user_variables
S
Shinya Maeda 已提交
262
      variables += project.group.secret_variables_for(ref, project).map(&:to_runner_variable) if project.group
L
Lin Jen-Shin 已提交
263
      variables += secret_variables(environment: environment)
264
      variables += trigger_request.user_variables if trigger_request
265
      variables += pipeline.variables.map(&:to_runner_variable)
S
Shinya Maeda 已提交
266
      variables += pipeline.pipeline_schedule.job_variables if pipeline.pipeline_schedule
L
Lin Jen-Shin 已提交
267
      variables += persisted_environment_variables if environment
D
Douwe Maan 已提交
268

L
Lin Jen-Shin 已提交
269
      variables
270 271
    end

272 273 274 275
    def features
      { trace_sections: true }
    end

276
    def merge_request
Z
Z.J. van de Weg 已提交
277
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
278

279 280
      @merge_request ||=
        begin
281
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
282 283
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
284
            .reorder(iid: :desc)
285 286

          merge_requests.find do |merge_request|
287
            merge_request.commit_shas.include?(pipeline.sha)
288 289
          end
        end
290 291
    end

D
Douwe Maan 已提交
292
    def repo_url
K
Kamil Trzcinski 已提交
293
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
294 295 296
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
297 298 299
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
300
      project.build_allow_git_fetch
D
Douwe Maan 已提交
301 302 303
    end

    def update_coverage
304
      coverage = trace.extract_coverage(coverage_regex)
305
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
306 307
    end

308
    def parse_trace_sections!
309
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
310 311
    end

312 313
    def trace
      Gitlab::Ci::Trace.new(self)
314 315
    end

316
    def has_trace?
317
      trace.exist?
T
Tomasz Maczukin 已提交
318 319
    end

320 321
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
322 323
    end

324 325
    def old_trace
      read_attribute(:trace)
326 327
    end

328 329 330
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
331 332
    end

333 334 335 336
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
337
    def valid_token?(token)
338
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
339 340
    end

341 342 343 344
    def has_tags?
      tag_list.any?
    end

345
    def any_runners_online?
346
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
347 348
    end

K
Kamil Trzcinski 已提交
349
    def stuck?
350 351 352
      pending? && !any_runners_online?
    end

353
    def execute_hooks
354
      return unless project
355

356
      build_data = Gitlab::DataBuilder::Build.build(self)
357 358
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
359
      PagesService.new(build_data).execute
J
Josh Frye 已提交
360
      project.running_or_pending_build_count(force: true)
361 362
    end

363
    def artifacts_metadata_entry(path, **options)
364 365 366 367 368 369
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
370 371
    end

372 373 374
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
375
      save
376 377
    end

378 379 380
    def erase(opts = {})
      return false unless erasable?

381
      erase_artifacts!
382 383 384 385 386 387 388 389 390 391 392 393
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

394
    def artifacts_expired?
395
      artifacts_expire_at && artifacts_expire_at < Time.now
396 397
    end

398 399 400 401 402
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
403 404
      self.artifacts_expire_at =
        if value
405
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
406
        end
407 408
    end

409
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
410
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
411 412
    end

413
    def keep_artifacts!
414
      self.update(artifacts_expire_at: nil)
415
      self.job_artifacts.update_all(expire_at: nil)
416 417
    end

418
    def coverage_regex
419
      super || project.try(:build_coverage_regex)
420 421
    end

422 423
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
424 425
    end

426 427
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
428 429
    end

430 431 432 433 434
    def user_variables
      return [] if user.blank?

      [
        { key: 'GITLAB_USER_ID', value: user.id.to_s, public: true },
435
        { key: 'GITLAB_USER_EMAIL', value: user.email, public: true },
436
        { key: 'GITLAB_USER_LOGIN', value: user.username, public: true },
437
        { key: 'GITLAB_USER_NAME', value: user.name, public: true }
438 439 440
      ]
    end

L
Lin Jen-Shin 已提交
441 442 443 444 445
    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

446
    def steps
T
Tomasz Maczukin 已提交
447 448
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
449 450 451
    end

    def image
452
      Gitlab::Ci::Build::Image.from_image(self)
453 454 455
    end

    def services
456
      Gitlab::Ci::Build::Image.from_services(self)
457 458
    end

459
    def artifacts
460
      [options[:artifacts]]
461 462 463
    end

    def cache
464
      [options[:cache]]
465 466
    end

467
    def credentials
468
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
469 470
    end

T
Tomasz Maczukin 已提交
471
    def dependencies
472 473
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
474 475
      depended_jobs = depends_on_builds

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

478 479
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
480 481 482
      end
    end

483 484 485 486
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

487
    def validates_dependencies!
488 489
      dependencies.each do |dependency|
        raise MissingDependenciesError unless dependency.valid_dependency?
490
      end
491 492
    end

S
Shinya Maeda 已提交
493 494 495 496 497 498 499 500
    def valid_dependency?
      return false unless complete?
      return false if artifacts_expired?
      return false if erased?

      true
    end

501 502 503 504
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
505 506
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
507 508 509
      trace
    end

510
    def serializable_hash(options = {})
J
James Lopez 已提交
511
      super(options).merge(when: read_attribute(:when))
512 513
    end

514 515
    private

L
Lin Jen-Shin 已提交
516
    def update_artifacts_size
K
Kamil Trzcinski 已提交
517
      self.artifacts_size = legacy_artifacts_file&.size
L
Lin Jen-Shin 已提交
518 519
    end

520
    def erase_trace!
521
      trace.erase!
522 523 524
    end

    def update_erased!(user = nil)
525
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
526 527
    end

528
    def unscoped_project
K
Kamil Trzciński 已提交
529
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
530 531
    end

532 533
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

534
    def predefined_variables
535 536 537
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
538 539 540 541 542 543 544
        { 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 已提交
545
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
546 547 548 549 550 551 552 553 554 555 556 557 558
        { 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

559
    def persisted_environment_variables
560 561
      return [] unless persisted_environment

L
Lin Jen-Shin 已提交
562 563
      variables = persisted_environment.predefined_variables

564 565 566
      # 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.
567
      variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url
L
Lin Jen-Shin 已提交
568 569

      variables
570 571
    end

572 573
    def legacy_variables
      variables = [
574 575 576 577 578
        { 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 已提交
579
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
580
        { key: 'CI_BUILD_NAME', value: name, public: true },
581
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
582
      ]
583 584 585 586

      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?
587 588
      variables
    end
589

590
    def environment_url
591
      options&.dig(:environment, :url) || persisted_environment&.external_url
592 593
    end

594 595
    def build_attributes_from_config
      return {} unless pipeline.config_processor
596

597 598
      pipeline.config_processor.build_attributes(name)
    end
599

600 601 602 603 604
    def update_project_statistics
      return unless project

      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
605 606 607 608 609 610

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