1# frozen_string_literal: true
2
3module Clusters
4  module Aws
5    class VerifyProvisionStatusService
6      attr_reader :provider
7
8      INITIAL_INTERVAL = 5.minutes
9      POLL_INTERVAL = 1.minute
10      TIMEOUT = 30.minutes
11
12      def execute(provider)
13        @provider = provider
14
15        case cluster_stack.stack_status
16        when 'CREATE_IN_PROGRESS'
17          continue_creation
18        when 'CREATE_COMPLETE'
19          finalize_creation
20        else
21          provider.make_errored!("Unexpected status; #{cluster_stack.stack_status}")
22        end
23      rescue ::Aws::CloudFormation::Errors::ServiceError => e
24        provider.make_errored!("Amazon CloudFormation request failed; #{e.message}")
25      end
26
27      private
28
29      def cluster_stack
30        @cluster_stack ||= provider.api_client.describe_stacks(stack_name: provider.cluster.name).stacks.first
31      end
32
33      def continue_creation
34        if timeout_threshold.future?
35          WaitForClusterCreationWorker.perform_in(POLL_INTERVAL, provider.cluster_id)
36        else
37          provider.make_errored!(_('Kubernetes cluster creation time exceeds timeout; %{timeout}') % { timeout: TIMEOUT })
38        end
39      end
40
41      def timeout_threshold
42        cluster_stack.creation_time + TIMEOUT
43      end
44
45      def finalize_creation
46        Clusters::Aws::FinalizeCreationService.new.execute(provider)
47      end
48    end
49  end
50end
51