build.rb 15.8 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
S
Shinya Maeda 已提交
6
    include Importable
7

8 9
    belongs_to :runner
    belongs_to :trigger_request
10
    belongs_to :erased_by, class_name: 'User'
D
Douwe Maan 已提交
11

12
    has_many :deployments, as: :deployable
13
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'
14
    has_many :trace_sections, class_name: 'Ci::BuildTraceSection'
15

16 17 18 19
    # 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 已提交
20
        project: project
21 22 23
      )
    end

24 25
    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize
D
Douwe Maan 已提交
26

D
Douwe Maan 已提交
27 28
    delegate :name, to: :project, prefix: true

D
Douwe Maan 已提交
29
    validates :coverage, numericality: true, allow_blank: true
D
Douwe Maan 已提交
30
    validates :ref, presence: true
D
Douwe Maan 已提交
31 32

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

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

D
Douwe Maan 已提交
44 45
    acts_as_taggable

46 47
    add_authentication_token_field :token

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

52
    after_create do |build|
53
      run_after_commit { BuildHooksWorker.perform_async(build.id) }
54 55
    end

56 57
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy
D
Douwe Maan 已提交
58 59

    class << self
60 61 62 63 64 65
      # 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 已提交
66 67 68 69
      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

70
      def retry(build, current_user)
71 72 73
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
D
Douwe Maan 已提交
74 75 76
      end
    end

77
    state_machine :status do
78 79
      event :actionize do
        transition created: :manual
K
Kamil Trzcinski 已提交
80 81
      end

82 83
      after_transition any => [:pending] do |build|
        build.run_after_commit do
K
linting  
Kim "BKC" Carlbäcker 已提交
84
          BuildQueueWorker.perform_async(id)
85 86 87
        end
      end

88
      after_transition pending: :running do |build|
89 90 91
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
92 93
      end

94
      after_transition any => [:success, :failed, :canceled] do |build|
95
        build.run_after_commit do
96
          BuildFinishedWorker.perform_async(id)
97
        end
D
Douwe Maan 已提交
98
      end
99

100
      after_transition any => [:success] do |build|
101 102
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
103 104
        end
      end
105

106 107
      before_transition any => [:failed] do |build|
        next if build.retries_max.zero?
108

109 110
        if build.retries_count < build.retries_max
          Ci::Build.retry(build, build.user)
111 112
        end
      end
D
Douwe Maan 已提交
113 114
    end

115
    def detailed_status(current_user)
116 117 118
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
K
Kamil Trzcinski 已提交
119 120
    end

121
    def other_actions
122
      pipeline.manual_actions.where.not(name: name)
123 124
    end

125
    def playable?
126
      action? && (manual? || complete?)
K
Kamil Trzcinski 已提交
127 128
    end

129
    def action?
130 131 132
      self.when == 'manual'
    end

133
    def play(current_user)
134 135 136
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
137 138
    end

K
Kamil Trzcinski 已提交
139 140 141 142
    def cancelable?
      active?
    end

K
Kamil Trzcinski 已提交
143
    def retryable?
144
      success? || failed? || canceled?
K
Kamil Trzcinski 已提交
145
    end
146 147 148 149 150 151 152 153

    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 已提交
154

155 156
    def latest?
      !retried?
K
Kamil Trzcinski 已提交
157 158
    end

159
    def expanded_environment_name
160
      ExpandVariables.expand(environment, simple_variables) if environment
161 162
    end

163
    def has_environment?
164
      environment.present?
165 166
    end

167
    def starts_environment?
168
      has_environment? && self.environment_action == 'start'
169 170 171
    end

    def stops_environment?
172
      has_environment? && self.environment_action == 'stop'
173 174 175
    end

    def environment_action
176
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
177 178 179 180
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
181
    end
182

183 184
    def depends_on_builds
      # Get builds of the same type
185
      latest_builds = self.pipeline.builds.latest
186 187 188 189 190

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

D
Douwe Maan 已提交
191
    def timeout
K
Kamil Trzcinski 已提交
192
      project.build_timeout
D
Douwe Maan 已提交
193 194
    end

195
    def triggered_by?(current_user)
S
Shinya Maeda 已提交
196 197 198
      user == current_user
    end

N
Nick Thomas 已提交
199 200 201 202 203 204
    # 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 已提交
205
    #   * First/Last Character is not a hyphen
N
Nick Thomas 已提交
206
    def ref_slug
V
vanadium23 已提交
207
      Gitlab::Utils.slugify(ref.to_s)
N
Nick Thomas 已提交
208 209
    end

210
    # Variables whose value does not depend on environment
211
    def simple_variables
L
Lin Jen-Shin 已提交
212 213 214 215 216 217
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
218
      variables = predefined_variables
219 220 221 222 223
      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?
224
      variables += project.auto_devops_variables
225 226
      variables += yaml_variables
      variables += user_variables
S
Shinya Maeda 已提交
227
      variables += project.group.secret_variables_for(ref, project).map(&:to_runner_variable) if project.group
L
Lin Jen-Shin 已提交
228
      variables += secret_variables(environment: environment)
229
      variables += trigger_request.user_variables if trigger_request
230
      variables += pipeline.variables.map(&:to_runner_variable)
S
Shinya Maeda 已提交
231
      variables += pipeline.pipeline_schedule.job_variables if pipeline.pipeline_schedule
L
Lin Jen-Shin 已提交
232
      variables += persisted_environment_variables if environment
D
Douwe Maan 已提交
233

L
Lin Jen-Shin 已提交
234
      variables
235 236
    end

237 238 239 240
    def features
      { trace_sections: true }
    end

241
    def merge_request
Z
Z.J. van de Weg 已提交
242
      return @merge_request if defined?(@merge_request)
Z
Z.J. van de Weg 已提交
243

244 245
      @merge_request ||=
        begin
246
          merge_requests = MergeRequest.includes(:latest_merge_request_diff)
247 248
            .where(source_branch: ref,
                   source_project: pipeline.project)
Z
Z.J. van de Weg 已提交
249
            .reorder(iid: :desc)
250 251

          merge_requests.find do |merge_request|
252
            merge_request.commit_shas.include?(pipeline.sha)
253 254
          end
        end
255 256
    end

D
Douwe Maan 已提交
257
    def repo_url
K
Kamil Trzcinski 已提交
258
      auth = "gitlab-ci-token:#{ensure_token!}@"
K
Kamil Trzcinski 已提交
259 260 261
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
D
Douwe Maan 已提交
262 263 264
    end

    def allow_git_fetch
K
Kamil Trzcinski 已提交
265
      project.build_allow_git_fetch
D
Douwe Maan 已提交
266 267 268
    end

    def update_coverage
269
      coverage = trace.extract_coverage(coverage_regex)
270
      update_attributes(coverage: coverage) if coverage.present?
D
Douwe Maan 已提交
271 272
    end

273
    def parse_trace_sections!
274
      ExtractSectionsFromBuildTraceService.new(project, user).execute(self)
275 276
    end

277 278
    def trace
      Gitlab::Ci::Trace.new(self)
279 280
    end

281
    def has_trace?
282
      trace.exist?
T
Tomasz Maczukin 已提交
283 284
    end

285 286
    def trace=(data)
      raise NotImplementedError
T
Tomasz Maczukin 已提交
287 288
    end

289 290
    def old_trace
      read_attribute(:trace)
291 292
    end

293 294 295
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
D
Douwe Maan 已提交
296 297
    end

298 299 300 301
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

L
Lin Jen-Shin 已提交
302
    def valid_token?(token)
303
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
K
Kamil Trzcinski 已提交
304 305
    end

306 307 308 309
    def has_tags?
      tag_list.any?
    end

310
    def any_runners_online?
311
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
312 313
    end

K
Kamil Trzcinski 已提交
314
    def stuck?
315 316 317
      pending? && !any_runners_online?
    end

318
    def execute_hooks
319
      return unless project
320

321
      build_data = Gitlab::DataBuilder::Build.build(self)
322 323
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
324
      PagesService.new(build_data).execute
J
Josh Frye 已提交
325
      project.running_or_pending_build_count(force: true)
326 327
    end

328
    def artifacts?
329
      !artifacts_expired? && artifacts_file.exists?
330 331
    end

332
    def artifacts_metadata?
333
      artifacts? && artifacts_metadata.exists?
334 335
    end

336
    def artifacts_metadata_entry(path, **options)
337 338 339 340 341 342
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
343 344
    end

345 346 347
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
348
      save
349 350
    end

351 352 353
    def erase(opts = {})
      return false unless erasable?

354
      erase_artifacts!
355 356 357 358 359 360 361 362 363 364 365 366
      erase_trace!
      update_erased!(opts[:erased_by])
    end

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

    def erased?
      !self.erased_at.nil?
    end

367
    def artifacts_expired?
368
      artifacts_expire_at && artifacts_expire_at < Time.now
369 370
    end

371 372 373 374 375
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
K
Kamil Trzcinski 已提交
376 377
      self.artifacts_expire_at =
        if value
378
          ChronicDuration.parse(value)&.seconds&.from_now
K
Kamil Trzcinski 已提交
379
        end
380 381
    end

382
    def has_expiring_artifacts?
Z
Z.J. van de Weg 已提交
383
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
384 385
    end

386
    def keep_artifacts!
387 388 389
      self.update(artifacts_expire_at: nil)
    end

390
    def coverage_regex
391
      super || project.try(:build_coverage_regex)
392 393
    end

394 395
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
396 397
    end

398 399
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
400 401
    end

402 403 404 405 406
    def user_variables
      return [] if user.blank?

      [
        { key: 'GITLAB_USER_ID', value: user.id.to_s, public: true },
407
        { key: 'GITLAB_USER_EMAIL', value: user.email, public: true },
408
        { key: 'GITLAB_USER_LOGIN', value: user.username, public: true },
409
        { key: 'GITLAB_USER_NAME', value: user.name, public: true }
410 411 412
      ]
    end

L
Lin Jen-Shin 已提交
413 414 415 416 417
    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

418
    def steps
T
Tomasz Maczukin 已提交
419 420
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
421 422 423
    end

    def image
424
      Gitlab::Ci::Build::Image.from_image(self)
425 426 427
    end

    def services
428
      Gitlab::Ci::Build::Image.from_services(self)
429 430 431
    end

    def artifacts
432
      [options[:artifacts]]
433 434 435
    end

    def cache
436
      [options[:cache]]
437 438
    end

439
    def credentials
440
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
441 442
    end

T
Tomasz Maczukin 已提交
443
    def dependencies
444 445
      return [] if empty_dependencies?

T
Tomasz Maczukin 已提交
446 447
      depended_jobs = depends_on_builds

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

450 451
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
T
Tomasz Maczukin 已提交
452 453 454
      end
    end

455 456 457 458
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

459 460 461 462
    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
463 464
      Gitlab::Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Gitlab::Ci::MaskSecret.mask!(trace, token)
465 466 467
      trace
    end

468
    def serializable_hash(options = {})
J
James Lopez 已提交
469
      super(options).merge(when: read_attribute(:when))
470 471
    end

472 473
    private

L
Lin Jen-Shin 已提交
474
    def update_artifacts_size
475 476
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
477 478
                            else
                              nil
479
                            end
L
Lin Jen-Shin 已提交
480 481
    end

482
    def erase_trace!
483
      trace.erase!
484 485 486
    end

    def update_erased!(user = nil)
487
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
488 489
    end

490
    def unscoped_project
K
Kamil Trzciński 已提交
491
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
492 493
    end

494 495
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

496
    def predefined_variables
497 498 499
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
500 501 502 503 504 505 506
        { 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 已提交
507
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
508 509 510 511 512 513 514 515 516 517 518 519 520
        { 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

521
    def persisted_environment_variables
522 523
      return [] unless persisted_environment

L
Lin Jen-Shin 已提交
524 525
      variables = persisted_environment.predefined_variables

526 527 528
      # 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.
529
      variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url
L
Lin Jen-Shin 已提交
530 531

      variables
532 533
    end

534 535
    def legacy_variables
      variables = [
536 537 538 539 540
        { 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 已提交
541
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
542
        { key: 'CI_BUILD_NAME', value: name, public: true },
543
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
544
      ]
545 546 547 548

      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?
549 550
      variables
    end
551

552
    def environment_url
553
      options&.dig(:environment, :url) || persisted_environment&.external_url
554 555
    end

556 557
    def build_attributes_from_config
      return {} unless pipeline.config_processor
558

559 560
      pipeline.config_processor.build_attributes(name)
    end
561

M
Markus Koller 已提交
562
    def update_project_statistics
563 564
      return unless project

M
Markus Koller 已提交
565 566
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
567 568 569 570 571 572

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