summaryrefslogtreecommitdiff
path: root/app/services/ci/runners/create_runner_service.rb
blob: 2de9ee4d38ee99577c2c5ce777fd7e86afa87fb7 (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
# frozen_string_literal: true

module Ci
  module Runners
    class CreateRunnerService
      RUNNER_CLASS_MAPPING = {
        'instance_type' => Ci::Runners::RunnerCreationStrategies::InstanceRunnerStrategy,
        nil => Ci::Runners::RunnerCreationStrategies::InstanceRunnerStrategy
      }.freeze

      attr_accessor :user, :type, :params, :strategy

      def initialize(user:, type:, params:)
        @user = user
        @type = type
        @params = params
        @strategy = RUNNER_CLASS_MAPPING[type].new(user: user, type: type, params: params)
      end

      def execute
        normalize_params

        return ServiceResponse.error(message: 'Validation error') unless strategy.validate_params
        return ServiceResponse.error(message: 'Insufficient permissions') unless strategy.authorized_user?

        runner = ::Ci::Runner.new(params)

        return ServiceResponse.success(payload: { runner: runner }) if runner.save

        ServiceResponse.error(message: runner.errors.full_messages)
      end

      def normalize_params
        params[:registration_type] = :authenticated_user
        params[:runner_type] = type
        params[:active] = !params.delete(:paused) if params[:paused].present?
        params[:creator] = user

        strategy.normalize_params
      end
    end
  end
end