summaryrefslogtreecommitdiff
path: root/app/controllers/clusters/clusters_controller.rb
blob: 7006c23321c8fe94381513fb820d67cb470b240d (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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# frozen_string_literal: true

class Clusters::ClustersController < Clusters::BaseController
  include RoutableActions
  include Metrics::Dashboard::PrometheusApiProxy
  include MetricsDashboard

  before_action :cluster, only: [:cluster_status, :show, :update, :destroy, :clear_cache]
  before_action :generate_gcp_authorize_url, only: [:new]
  before_action :validate_gcp_token, only: [:new]
  before_action :gcp_cluster, only: [:new]
  before_action :user_cluster, only: [:new]
  before_action :authorize_create_cluster!, only: [:new, :authorize_aws_role]
  before_action :authorize_update_cluster!, only: [:update]
  before_action :authorize_admin_cluster!, only: [:destroy, :clear_cache]
  before_action :update_applications_status, only: [:cluster_status]

  helper_method :token_in_session

  STATUS_POLLING_INTERVAL = 10_000

  def index
    @clusters = cluster_list

    respond_to do |format|
      format.html
      format.json do
        Gitlab::PollingInterval.set_header(response, interval: STATUS_POLLING_INTERVAL)
        serializer = ClusterSerializer.new(current_user: current_user)

        render json: {
          clusters: serializer.with_pagination(request, response).represent_list(@clusters),
          has_ancestor_clusters: @has_ancestor_clusters
        }
      end
    end
  end

  def new
    if params[:provider] == 'aws'
      @aws_role = Aws::Role.create_or_find_by!(user: current_user)
      @instance_types = load_instance_types.to_json

    elsif params[:provider] == 'gcp'
      redirect_to @authorize_url if @authorize_url && !@valid_gcp_token
    end
  end

  # Overridding ActionController::Metal#status is NOT a good idea
  def cluster_status
    respond_to do |format|
      format.json do
        Gitlab::PollingInterval.set_header(response, interval: STATUS_POLLING_INTERVAL)

        render json: ClusterSerializer
          .new(current_user: @current_user)
          .represent_status(@cluster)
      end
    end
  end

  def show
  end

  def update
    Clusters::UpdateService
      .new(current_user, update_params)
      .execute(cluster)

    if cluster.valid?
      respond_to do |format|
        format.json do
          head :no_content
        end
        format.html do
          flash[:notice] = _('Kubernetes cluster was successfully updated.')
          redirect_to cluster.show_path
        end
      end
    else
      respond_to do |format|
        format.json { head :bad_request }
        format.html { render :show }
      end
    end
  end

  def destroy
    response = Clusters::DestroyService
      .new(current_user, destroy_params)
      .execute(cluster)

    flash[:notice] = response[:message]
    redirect_to clusterable.index_path, status: :found
  end

  def create_gcp
    @gcp_cluster = ::Clusters::CreateService
      .new(current_user, create_gcp_cluster_params)
      .execute(access_token: token_in_session)
      .present(current_user: current_user)

    if @gcp_cluster.persisted?
      redirect_to @gcp_cluster.show_path
    else
      generate_gcp_authorize_url
      validate_gcp_token
      user_cluster
      params[:provider] = 'gcp'

      render :new, locals: { active_tab: 'create' }
    end
  end

  def create_aws
    @aws_cluster = ::Clusters::CreateService
      .new(current_user, create_aws_cluster_params)
      .execute
      .present(current_user: current_user)

    if @aws_cluster.persisted?
      head :created, location: @aws_cluster.show_path
    else
      render status: :unprocessable_entity, json: @aws_cluster.errors
    end
  end

  def create_user
    @user_cluster = ::Clusters::CreateService
      .new(current_user, create_user_cluster_params)
      .execute(access_token: token_in_session)
      .present(current_user: current_user)

    if @user_cluster.persisted?
      redirect_to @user_cluster.show_path
    else
      generate_gcp_authorize_url
      validate_gcp_token
      gcp_cluster

      render :new, locals: { active_tab: 'add' }
    end
  end

  def authorize_aws_role
    response = Clusters::Aws::AuthorizeRoleService.new(
      current_user,
      params: aws_role_params
    ).execute

    render json: response.body, status: response.status
  end

  def clear_cache
    cluster.delete_cached_resources!

    redirect_to cluster.show_path, notice: _('Cluster cache cleared.')
  end

  private

  def cluster_list
    finder = ClusterAncestorsFinder.new(clusterable.subject, current_user)
    clusters = finder.execute

    @has_ancestor_clusters = finder.has_ancestor_clusters?

    # Note: We are paginating through an array here but this should OK as:
    #
    # In CE, we can have a maximum group nesting depth of 21, so including
    # project cluster, we can have max 22 clusters for a group hierarchy.
    # In EE (Premium) we can have any number, as multiple clusters are
    # supported, but the number of clusters are fairly low currently.
    #
    # See https://gitlab.com/gitlab-org/gitlab-foss/issues/55260 also.
    Kaminari.paginate_array(clusters).page(params[:page]).per(20)
  end

  def destroy_params
    params.permit(:cleanup)
  end

  def update_params
    if cluster.provided_by_user?
      params.require(:cluster).permit(
        :enabled,
        :name,
        :environment_scope,
        :managed,
        :base_domain,
        :management_project_id,
        platform_kubernetes_attributes: [
          :api_url,
          :token,
          :ca_cert,
          :namespace
        ]
      )
    else
      params.require(:cluster).permit(
        :enabled,
        :environment_scope,
        :managed,
        :base_domain,
        :management_project_id,
        platform_kubernetes_attributes: [
          :namespace
        ]
      )
    end
  end

  def create_gcp_cluster_params
    params.require(:cluster).permit(
      :enabled,
      :name,
      :environment_scope,
      :managed,
      provider_gcp_attributes: [
        :gcp_project_id,
        :zone,
        :num_nodes,
        :machine_type,
        :cloud_run,
        :legacy_abac
      ]).merge(
        provider_type: :gcp,
        platform_type: :kubernetes,
        clusterable: clusterable.subject
      )
  end

  def create_aws_cluster_params
    params.require(:cluster).permit(
      :enabled,
      :name,
      :environment_scope,
      :managed,
      provider_aws_attributes: [
        :kubernetes_version,
        :key_name,
        :role_arn,
        :region,
        :vpc_id,
        :instance_type,
        :num_nodes,
        :security_group_id,
        subnet_ids: []
      ]).merge(
        provider_type: :aws,
        platform_type: :kubernetes,
        clusterable: clusterable.subject
      )
  end

  def create_user_cluster_params
    params.require(:cluster).permit(
      :enabled,
      :name,
      :environment_scope,
      :managed,
      platform_kubernetes_attributes: [
        :namespace,
        :api_url,
        :token,
        :ca_cert,
        :authorization_type
      ]).merge(
        provider_type: :user,
        platform_type: :kubernetes,
        clusterable: clusterable.subject
      )
  end

  def aws_role_params
    params.require(:cluster).permit(:role_arn)
  end

  def generate_gcp_authorize_url
    state = generate_session_key_redirect(clusterable.new_path(provider: :gcp).to_s)

    @authorize_url = GoogleApi::CloudPlatform::Client.new(
      nil, callback_google_api_auth_url,
      state: state).authorize_url
  rescue GoogleApi::Auth::ConfigMissingError
    # no-op
  end

  def gcp_cluster
    cluster = Clusters::BuildService.new(clusterable.subject).execute
    cluster.build_provider_gcp
    @gcp_cluster = cluster.present(current_user: current_user)
  end

  def proxyable
    cluster.cluster
  end

  # During first iteration of dashboard variables implementation
  # cluster health case was omitted. Existing service for now is tied to
  # environment, which is not always present for cluster health dashboard.
  # It is planned to break coupling to environment https://gitlab.com/gitlab-org/gitlab/-/issues/213833.
  # It is also planned to move cluster health to metrics dashboard section https://gitlab.com/gitlab-org/gitlab/-/issues/220214
  # but for now I've used dummy class to stub variable substitution service, as there are no variables
  # in cluster health dashboard
  def proxy_variable_substitution_service
    @empty_service ||= Class.new(BaseService) do
      def initialize(proxyable, params)
        @proxyable, @params = proxyable, params
      end

      def execute
        success(params: @params)
      end
    end
  end

  def user_cluster
    cluster = Clusters::BuildService.new(clusterable.subject).execute
    cluster.build_platform_kubernetes
    @user_cluster = cluster.present(current_user: current_user)
  end

  def validate_gcp_token
    @valid_gcp_token = GoogleApi::CloudPlatform::Client.new(token_in_session, nil)
      .validate_token(expires_at_in_session)
  end

  def token_in_session
    session[GoogleApi::CloudPlatform::Client.session_key_for_token]
  end

  def expires_at_in_session
    @expires_at_in_session ||=
      session[GoogleApi::CloudPlatform::Client.session_key_for_expires_at]
  end

  def generate_session_key_redirect(uri)
    GoogleApi::CloudPlatform::Client.new_session_key_for_redirect_uri do |key|
      session[key] = uri
    end
  end

  ##
  # Unfortunately the EC2 API doesn't provide a list of
  # possible instance types. There is a workaround, using
  # the Pricing API, but instead of requiring the
  # user to grant extra permissions for this we use the
  # values that validate the CloudFormation template.
  def load_instance_types
    stack_template = File.read(Rails.root.join('vendor', 'aws', 'cloudformation', 'eks_cluster.yaml'))
    instance_types = YAML.safe_load(stack_template).dig('Parameters', 'NodeInstanceType', 'AllowedValues')

    instance_types.map { |type| Hash(name: type, value: type) }
  end

  def update_applications_status
    @cluster.applications.each(&:schedule_status_update)
  end
end

Clusters::ClustersController.prepend_if_ee('EE::Clusters::ClustersController')