class ClusterBootstrapperErrorHandler {

    public void terminateFailedNodes(HostOrchestrator hostOrchestrator, ContainerOrchestrator containerOrchestrator,
            Stack stack, GatewayConfig gatewayConfig, Set<Node> nodes)
            throws CloudbreakOrchestratorFailedException {
        List<String> allAvailableNode;
        allAvailableNode = hostOrchestrator != null ? hostOrchestrator.getAvailableNodes(gatewayConfig, nodes)
                : containerOrchestrator.getAvailableNodes(gatewayConfig, nodes);
        List<Node> missingNodes = selectMissingNodes(nodes, allAvailableNode);
        if (!missingNodes.isEmpty()) {
            eventService.fireCloudbreakEvent(stack.getId(), Status.UPDATE_IN_PROGRESS.name(), CLUSTER_BOOTSTRAPPER_ERROR_BOOTSTRAP_FAILED_ON_NODES,
                    Arrays.asList(String.valueOf(missingNodes.size())));

            for (Node missingNode : missingNodes) {
                InstanceMetaData instanceMetaData =
                        instanceMetaDataService.findNotTerminatedByPrivateAddress(stack.getId(), missingNode.getPrivateIp())
                                .orElseThrow(NotFoundException.notFound("instanceMetaData", missingNode.getPrivateIp()));
                InstanceGroup ig = instanceGroupService.findOneWithInstanceMetadataByGroupNameInStack(stack.getId(),
                        instanceMetaData.getInstanceGroup().getGroupName())
                        .orElseThrow(NotFoundException.notFound("instanceGroup", instanceMetaData.getInstanceGroup().getGroupName()));
                if (ig.getNodeCount() < 1) {
                    throw new CloudbreakOrchestratorFailedException(cloudbreakMessagesService.getMessage(
                            CLUSTER_BOOTSTRAPPER_ERROR_INVALID_NODECOUNT.getMessage(),
                            Collections.singletonList(ig.getGroupName())));
                }
                instanceGroupService.save(ig);
                eventService.fireCloudbreakEvent(stack.getId(), Status.UPDATE_IN_PROGRESS.name(), CLUSTER_BOOTSTRAPPER_ERROR_DELETING_NODE,
                        Arrays.asList(instanceMetaData.getInstanceId(), ig.getGroupName()));
                deleteResourceAndDependencies(stack, instanceMetaData);
                deleteInstanceResourceFromDatabase(stack, instanceMetaData);
                instanceMetaData.setTerminationDate(clock.getCurrentTimeMillis());
                instanceMetaData.setInstanceStatus(InstanceStatus.TERMINATED);
                instanceMetaDataService.save(instanceMetaData);
                LOGGER.debug("InstanceMetadata [name: {}, id: {}] status set to {}.", instanceMetaData.getId(), instanceMetaData.getInstanceId(),
                        instanceMetaData.getInstanceStatus());
            }
        }
    }

}