summaryrefslogtreecommitdiff
path: root/app/services/clusters/create_service.rb
blob: cb2de8b943c5f05a151bd283570bc6ca1ceaff0c (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
# frozen_string_literal: true

module Clusters
  class CreateService
    attr_reader :current_user, :params

    def initialize(user = nil, params = {})
      @current_user = user
      @params = params.dup
    end

    def execute(access_token: nil)
      raise ArgumentError, 'Unknown clusterable provided' unless clusterable

      cluster_params = params.merge(global_params).merge(clusterable_params)

      cluster_params[:provider_gcp_attributes].try do |provider|
        provider[:access_token] = access_token
      end

      cluster = Clusters::Cluster.new(cluster_params)

      validate_management_project_permissions(cluster)

      return cluster if cluster.errors.present?

      cluster.tap do |cluster|
        cluster.save && ClusterProvisionWorker.perform_async(cluster.id)
      end
    end

    private

    def clusterable
      @clusterable ||= params.delete(:clusterable)
    end

    def global_params
      { user: current_user }
    end

    def clusterable_params
      case clusterable
      when ::Project
        { cluster_type: :project_type, projects: [clusterable] }
      when ::Group
        { cluster_type: :group_type, groups: [clusterable] }
      when Instance
        { cluster_type: :instance_type }
      else
        raise NotImplementedError
      end
    end

    def validate_management_project_permissions(cluster)
      Clusters::Management::ValidateManagementProjectPermissionsService.new(current_user)
        .execute(cluster, params[:management_project_id])
    end
  end
end