BigW Consortium Gitlab

build.rb 14.2 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
    serialize :options
23
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables
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).relevant }
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_save :update_project_statistics, if: :artifacts_size_changed?
    after_destroy :update_project_statistics
52 53 54 55 56 57

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

58
      def retry(build, current_user)
59 60 61
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
62 63 64
      end
    end

65
    state_machine :status do
66 67
      event :actionize do
        transition created: :manual
68 69
      end

70 71
      after_transition any => [:pending] do |build|
        build.run_after_commit do
Kim "BKC" Carlbäcker committed
72
          BuildQueueWorker.perform_async(id)
73 74 75
        end
      end

76
      after_transition pending: :running do |build|
77 78 79
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
80 81
      end

82
      after_transition any => [:success, :failed, :canceled] do |build|
83
        build.run_after_commit do
84
          BuildFinishedWorker.perform_async(id)
85
        end
86
      end
87

88
      after_transition any => [:success] do |build|
89 90
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
91 92
        end
      end
93 94
    end

95
    def detailed_status(current_user)
96 97 98
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
99 100
    end

101
    def other_actions
102
      pipeline.manual_actions.where.not(name: name)
103 104
    end

105
    def playable?
106
      action? && manual?
107 108
    end

109
    def action?
110 111 112
      self.when == 'manual'
    end

113
    def play(current_user)
114 115 116
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
117 118
    end

Kamil Trzcinski committed
119 120 121 122
    def cancelable?
      active?
    end

Kamil Trzcinski committed
123
    def retryable?
124
      success? || failed? || canceled?
Kamil Trzcinski committed
125 126
    end

127 128
    def latest?
      !retried?
129 130
    end

131
    def expanded_environment_name
132
      ExpandVariables.expand(environment, simple_variables) if environment
133 134
    end

135
    def has_environment?
136
      environment.present?
137 138
    end

139
    def starts_environment?
140
      has_environment? && self.environment_action == 'start'
141 142 143
    end

    def stops_environment?
144
      has_environment? && self.environment_action == 'stop'
145 146 147
    end

    def environment_action
148
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
149 150 151 152
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
153
    end
154

155 156
    def depends_on_builds
      # Get builds of the same type
157
      latest_builds = self.pipeline.builds.latest
158 159 160 161 162

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

163
    def timeout
164
      project.build_timeout
165 166
    end

167 168 169 170 171 172 173 174 175 176 177
    # 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

178 179
    # Variables whose value does not depend on other variables
    def simple_variables
180 181 182 183 184
      variables = predefined_variables
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
185
      variables += project.deployment_variables if has_environment?
186
      variables += yaml_variables
187
      variables += user_variables
188 189
      variables += project.secret_variables
      variables += trigger_request.user_variables if trigger_request
190
      variables
191 192
    end

193 194 195 196 197 198 199
    # All variables, including those dependent on other variables
    def variables
      variables = simple_variables
      variables += persisted_environment.predefined_variables if persisted_environment.present?
      variables
    end

200 201
    def merge_request
      merge_requests = MergeRequest.includes(:merge_request_diff)
202 203
                                   .where(source_branch: ref,
                                          source_project: pipeline.project)
204 205 206
                                   .reorder(iid: :asc)

      merge_requests.find do |merge_request|
207
        merge_request.commits_sha.include?(pipeline.sha)
208 209 210
      end
    end

211
    def repo_url
212
      auth = "gitlab-ci-token:#{ensure_token!}@"
213 214 215
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
216 217 218
    end

    def allow_git_fetch
219
      project.build_allow_git_fetch
220 221 222
    end

    def update_coverage
223
      coverage = trace.extract_coverage(coverage_regex)
224
      update_attributes(coverage: coverage) if coverage.present?
225 226
    end

227 228
    def trace
      Gitlab::Ci::Trace.new(self)
229 230
    end

231
    def has_trace?
232
      trace.exist?
233 234
    end

235 236
    def trace=(data)
      raise NotImplementedError
Tomasz Maczukin committed
237 238
    end

239 240
    def old_trace
      read_attribute(:trace)
241 242
    end

243 244 245
    def erase_old_trace!
      write_attribute(:trace, nil)
      save
246 247
    end

248 249 250 251
    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

252 253 254 255 256 257 258 259 260 261 262
    ##
    # 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
263 264 265 266 267 268 269
      # 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

270
      old = File.join(created_at.utc.strftime('%Y_%m'),
271
                      the_project.ci_id.to_s,
272 273 274
                      id.to_s)

      old_store = File.join(ArtifactUploader.artifacts_path, old)
275
      return old if the_project.ci_id && File.directory?(old_store)
276 277 278

      File.join(
        created_at.utc.strftime('%Y_%m'),
279
        the_project.id.to_s,
280 281 282 283
        id.to_s
      )
    end

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

288 289 290 291
    def has_tags?
      tag_list.any?
    end

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

296
    def stuck?
297 298 299
      pending? && !any_runners_online?
    end

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

309
    def artifacts?
310
      !artifacts_expired? && artifacts_file.exists?
311 312
    end

313
    def artifacts_metadata?
314
      artifacts? && artifacts_metadata.exists?
315 316
    end

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

      metadata.to_entry
324 325
    end

326 327 328
    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
329
      save
330 331
    end

332 333 334
    def erase(opts = {})
      return false unless erasable?

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

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

    def erased?
      !self.erased_at.nil?
    end

348
    def artifacts_expired?
349
      artifacts_expire_at && artifacts_expire_at < Time.now
350 351
    end

352 353 354 355 356
    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

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

363 364 365 366
    def has_expiring_artifacts?
      artifacts_expire_at.present?
    end

367
    def keep_artifacts!
368 369 370
      self.update(artifacts_expire_at: nil)
    end

371
    def coverage_regex
372
      super || project.try(:build_coverage_regex)
373 374
    end

375 376
    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
377 378
    end

379 380
    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
381 382
    end

383 384 385 386 387 388 389 390 391
    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

392
    def steps
393 394
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
395 396 397
    end

    def image
398
      Gitlab::Ci::Build::Image.from_image(self)
399 400 401
    end

    def services
402
      Gitlab::Ci::Build::Image.from_services(self)
403 404 405
    end

    def artifacts
406
      [options[:artifacts]]
407 408 409
    end

    def cache
410
      [options[:cache]]
411 412
    end

413
    def credentials
414
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
415 416
    end

417
    def dependencies
418 419
      return [] if empty_dependencies?

420 421
      depended_jobs = depends_on_builds

422
      return depended_jobs unless options[:dependencies].present?
423

424 425
      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
426 427 428
      end
    end

429 430 431 432
    def empty_dependencies?
      options[:dependencies]&.empty?
    end

433 434 435 436 437 438 439 440 441
    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

442 443
    private

444
    def update_artifacts_size
445 446
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
447 448
                            else
                              nil
449
                            end
450 451
    end

452
    def erase_trace!
453
      trace.erase!
454 455 456
    end

    def update_erased!(user = nil)
457
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
458 459
    end

460
    def unscoped_project
461
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
462 463
    end

464 465
    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

466
    def predefined_variables
467 468 469
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
470 471 472 473 474 475 476
        { 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
477
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        { 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

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

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

    def build_attributes_from_config
      return {} unless pipeline.config_processor
511

512 513
      pipeline.config_processor.build_attributes(name)
    end
514

515
    def update_project_statistics
516 517
      return unless project

518 519
      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end
520 521
  end
end