summaryrefslogtreecommitdiff
path: root/app/services/create_deployment_service.rb
blob: 46823418bb02fb7a301e91776f5ba12273cf0ef3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class CreateDeploymentService
  attr_reader :job

  delegate :expanded_environment_name,
           :environment_url,
           :project,
           to: :job

  def initialize(job)
    @job = job
  end

  def execute
    return unless executable?

    ActiveRecord::Base.transaction do
      environment.external_url = environment_url if environment_url
      environment.fire_state_event(action)

      return unless environment.save
      return if environment.stopped?

      deploy.tap(&:update_merge_request_metrics!)
    end
  end

  private

  def executable?
    project && job.environment.present? && environment
  end

  def deploy
    project.deployments.create(
      environment: environment,
      ref: job.ref,
      tag: job.tag,
      sha: job.sha,
      user: job.user,
      deployable: job,
      on_stop: on_stop)
  end

  def environment
    @environment ||= job.persisted_environment
  end

  def environment_options
    @environment_options ||= job.options&.dig(:environment) || {}
  end

  def on_stop
    environment_options[:on_stop]
  end

  def action
    environment_options[:action] || 'start'
  end
end