summaryrefslogtreecommitdiff
path: root/app/models/deployment.rb
blob: 5450357fe1b1a4f49aed6b7d068f55904008fc9f (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# frozen_string_literal: true

class Deployment < ApplicationRecord
  include AtomicInternalId
  include IidRoutes
  include AfterCommitQueue
  include UpdatedAtFilterable
  include Importable
  include Gitlab::Utils::StrongMemoize

  belongs_to :project, required: true
  belongs_to :environment, required: true
  belongs_to :cluster, class_name: 'Clusters::Cluster', optional: true
  belongs_to :user
  belongs_to :deployable, polymorphic: true, optional: true # rubocop:disable Cop/PolymorphicAssociations
  has_many :deployment_merge_requests

  has_many :merge_requests,
    through: :deployment_merge_requests

  has_one :deployment_cluster

  has_internal_id :iid, scope: :project, track_if: -> { !importing? }, init: ->(s) do
    Deployment.where(project: s.project).maximum(:iid) if s&.project
  end

  validates :sha, presence: true
  validates :ref, presence: true
  validate :valid_sha, on: :create
  validate :valid_ref, on: :create

  delegate :name, to: :environment, prefix: true

  scope :for_environment, -> (environment) { where(environment_id: environment) }
  scope :for_environment_name, -> (name) do
    joins(:environment).where(environments: { name: name })
  end

  scope :for_status, -> (status) { where(status: status) }

  scope :visible, -> { where(status: %i[running success failed canceled]) }
  scope :stoppable, -> { where.not(on_stop: nil).where.not(deployable_id: nil).success }

  state_machine :status, initial: :created do
    event :run do
      transition created: :running
    end

    event :succeed do
      transition any - [:success] => :success
    end

    event :drop do
      transition any - [:failed] => :failed
    end

    event :cancel do
      transition any - [:canceled] => :canceled
    end

    before_transition any => [:success, :failed, :canceled] do |deployment|
      deployment.finished_at = Time.now
    end

    after_transition any => :success do |deployment|
      deployment.run_after_commit do
        Deployments::SuccessWorker.perform_async(id)
      end
    end

    after_transition any => [:success, :failed, :canceled] do |deployment|
      deployment.run_after_commit do
        Deployments::FinishedWorker.perform_async(id)
      end
    end
  end

  enum status: {
    created: 0,
    running: 1,
    success: 2,
    failed: 3,
    canceled: 4
  }

  def self.last_for_environment(environment)
    ids = self
      .for_environment(environment)
      .select('MAX(id) AS id')
      .group(:environment_id)
      .map(&:id)
    find(ids)
  end

  def self.distinct_on_environment
    order('environment_id, deployments.id DESC')
      .select('DISTINCT ON (environment_id) deployments.*')
  end

  def self.find_successful_deployment!(iid)
    success.find_by!(iid: iid)
  end

  def commit
    project.commit(sha)
  end

  def commit_title
    commit.try(:title)
  end

  def short_sha
    Commit.truncate_sha(sha)
  end

  def execute_hooks
    deployment_data = Gitlab::DataBuilder::Deployment.build(self)
    project.execute_services(deployment_data, :deployment_hooks)
  end

  def last?
    self == environment.last_deployment
  end

  def create_ref
    project.repository.create_ref(ref, ref_path)
  end

  def invalidate_cache
    environment.expire_etag_cache
  end

  def manual_actions
    @manual_actions ||= deployable.try(:other_manual_actions)
  end

  def scheduled_actions
    @scheduled_actions ||= deployable.try(:other_scheduled_actions)
  end

  def playable_build
    strong_memoize(:playable_build) do
      deployable.try(:playable?) ? deployable : nil
    end
  end

  def includes_commit?(commit)
    return false unless commit

    project.repository.ancestor?(commit.id, sha)
  end

  def update_merge_request_metrics!
    return unless environment.update_merge_request_metrics? && success?

    merge_requests = project.merge_requests
                     .joins(:metrics)
                     .where(target_branch: self.ref, merge_request_metrics: { first_deployed_to_production_at: nil })
                     .where("merge_request_metrics.merged_at <= ?", finished_at)

    if previous_deployment
      merge_requests = merge_requests.where("merge_request_metrics.merged_at >= ?", previous_deployment.finished_at)
    end

    MergeRequest::Metrics
      .where(merge_request_id: merge_requests.select(:id), first_deployed_to_production_at: nil)
      .update_all(first_deployed_to_production_at: finished_at)
  end

  def previous_deployment
    @previous_deployment ||=
      project.deployments.joins(:environment)
      .where(environments: { name: self.environment.name }, ref: self.ref)
      .where.not(id: self.id)
      .order(id: :desc)
      .take
  end

  def previous_environment_deployment
    project
      .deployments
      .success
      .joins(:environment)
      .where(environments: { name: environment.name })
      .where.not(id: self.id)
      .order(id: :desc)
      .take
  end

  def stop_action
    return unless on_stop.present?
    return unless manual_actions

    @stop_action ||= manual_actions.find_by(name: on_stop)
  end

  def finished_at
    read_attribute(:finished_at) || legacy_finished_at
  end

  def deployed_at
    return unless success?

    finished_at
  end

  def formatted_deployment_time
    deployed_at&.to_time&.in_time_zone&.to_s(:medium)
  end

  def deployed_by
    # We use deployable's user if available because Ci::PlayBuildService
    # does not update the deployment's user, just the one for the deployable.
    # TODO: use deployment's user once https://gitlab.com/gitlab-org/gitlab-foss/issues/66442
    # is completed.
    deployable&.user || user
  end

  def link_merge_requests(relation)
    select = relation.select(['merge_requests.id', id]).to_sql

    # We don't use `Gitlab::Database.bulk_insert` here so that we don't need to
    # first pluck lots of IDs into memory.
    #
    # We also ignore any duplicates so this method can be called multiple times
    # for the same deployment, only inserting any missing merge requests.
    DeploymentMergeRequest.connection.execute(<<~SQL)
      INSERT INTO #{DeploymentMergeRequest.table_name}
      (merge_request_id, deployment_id)
      #{select}
      ON CONFLICT DO NOTHING
    SQL
  end

  # Changes the status of a deployment and triggers the correspinding state
  # machine events.
  def update_status(status)
    case status
    when 'running'
      run
    when 'success'
      succeed
    when 'failed'
      drop
    when 'canceled'
      cancel
    else
      raise ArgumentError, "The status #{status.inspect} is invalid"
    end
  end

  def valid_sha
    return if project&.commit(sha)

    errors.add(:sha, _('The commit does not exist'))
  end

  def valid_ref
    return if project&.commit(ref)

    errors.add(:ref, _('The branch or tag does not exist'))
  end

  private

  def ref_path
    File.join(environment.ref_path, 'deployments', iid.to_s)
  end

  def legacy_finished_at
    self.created_at if success? && !read_attribute(:finished_at)
  end
end

Deployment.prepend_if_ee('EE::Deployment')