<commit_before>package main

import (
	"log"
	"regexp"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/eks"
	"github.com/aws/aws-sdk-go/service/iam"
)

//nolint:gochecknoglobals
var deferError error

func (ac *AWSCluster) checkDeferError(err error) bool {
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case "NoSuchEntity":
			case "ResourceNotFoundException":
			case "ValidationError":
			case "InvalidParameterValue":
			default:
				log.Printf("Error (%s): %s\n", aerr.Code(), aerr.Message())
				deferError = aerr
				return true
			}
			log.Printf("Warning (%s): %s\n", aerr.Code(), aerr.Message())
		} else {
			log.Printf("Error: %s\n", err.Error())
			deferError = aerr
		}
		return true
	}
	return false
}

func (ac *AWSCluster) deleteEksRole(iamClient *iam.IAM, eksRoleName *string) {
	log.Printf("Deleting EKS service role \"%s\"...\n", *eksRoleName)

	policyArn := "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
	_, err := iamClient.DetachRolePolicy(&iam.DetachRolePolicyInput{
		RoleName:  eksRoleName,
		PolicyArn: &policyArn,
	})
	ac.checkDeferError(err)

	policyArn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy"
	_, err = iamClient.DetachRolePolicy(&iam.DetachRolePolicyInput{
		RoleName:  eksRoleName,
		PolicyArn: &policyArn,
	})
	ac.checkDeferError(err)

	_, err = iamClient.DeleteRole(&iam.DeleteRoleInput{
		RoleName: eksRoleName,
	})
	if ac.checkDeferError(err) {
		return
	}

	log.Printf("Role \"%s\" successfully deleted!\n", *eksRoleName)
}

func (ac *AWSCluster) deleteEC2NetworkInterfaces(ec2Client *ec2.EC2, cfClient *cloudformation.CloudFormation, nodesStackName *string) {
	cfResp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
		StackName: nodesStackName,
	})
	if ac.checkDeferError(err) {
		return
	}

	var sequrityGroup *string
	for _, output := range cfResp.Stacks[0].Outputs {
		if *output.OutputKey == "NodeSecurityGroup" {
			sequrityGroup = output.OutputValue
			break
		}
	}

	ec2Resp, err := ec2Client.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
		Filters: []*ec2.Filter{
			{
				Name:   aws.String("group-id"),
				Values: []*string{sequrityGroup},
			},
		},
	})

	if ac.checkDeferError(err) {
		return
	}

	for _, networkInterface := range ec2Resp.NetworkInterfaces {
		_, err := ec2Client.DeleteNetworkInterface(&ec2.DeleteNetworkInterfaceInput{
			NetworkInterfaceId: networkInterface.NetworkInterfaceId,
		})

		ac.checkDeferError(err)
	}
}

//nolint:funlen
func (ac *AWSCluster) deleteEksClusterVpc(cfClient *cloudformation.CloudFormation, ec2Client *ec2.EC2, clusterStackName *string) {
	log.Printf("Deleting Amazon EKS Cluster VPC \"%s\"...\n", *clusterStackName)

	resp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
		StackName: clusterStackName,
	})
	if ac.checkDeferError(err) {
		return
	}
	outputsMap := outputsToMap(resp.Stacks[0].Outputs)

	output, err := ec2Client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
		Filters: []*ec2.Filter{
			{
				Name:   aws.String("vpc-id"),
				Values: []*string{outputsMap.VpcId},
			},
		},
	})
	if !ac.checkDeferError(err) {
		for _, sg := range output.SecurityGroups {
			if *sg.GroupName != "default" {
				log.Printf("Deleting EC2 Security Group %s...", *sg.GroupId)
				_, err = ec2Client.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{GroupId: sg.GroupId})
				ac.checkDeferError(err)
			}
		}
	}

	_, err = ec2Client.DeleteVpc(&ec2.DeleteVpcInput{VpcId: outputsMap.VpcId})
	ac.checkDeferError(err)

	stackId := resp.Stacks[0].StackId

	_, err = cfClient.DeleteStack(&cloudformation.DeleteStackInput{
		StackName:       clusterStackName,
		RetainResources: []*string{aws.String("Ipv6VPCCidrBlock")},
	})
	if ac.checkDeferError(err) {
		return
	}

	for {
		resp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
			StackName: stackId,<commit_msg>Fix aws cluster deleting (#2111)<commit_after>package main

import (
	"log"
	"regexp"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudformation"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/eks"
	"github.com/aws/aws-sdk-go/service/iam"
)

//nolint:gochecknoglobals
var deferError error

func (ac *AWSCluster) checkDeferError(err error) bool {
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case "NoSuchEntity":
			case "ResourceNotFoundException":
			case "ValidationError":
			case "InvalidParameterValue":
			default:
				log.Printf("Error (%s): %s\n", aerr.Code(), aerr.Message())
				deferError = aerr
				return true
			}
			log.Printf("Warning (%s): %s\n", aerr.Code(), aerr.Message())
		} else {
			log.Printf("Error: %s\n", err.Error())
			deferError = aerr
		}
		return true
	}
	return false
}

func (ac *AWSCluster) deleteEksRole(iamClient *iam.IAM, eksRoleName *string) {
	log.Printf("Deleting EKS service role \"%s\"...\n", *eksRoleName)

	policyArn := "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
	_, err := iamClient.DetachRolePolicy(&iam.DetachRolePolicyInput{
		RoleName:  eksRoleName,
		PolicyArn: &policyArn,
	})
	ac.checkDeferError(err)

	policyArn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy"
	_, err = iamClient.DetachRolePolicy(&iam.DetachRolePolicyInput{
		RoleName:  eksRoleName,
		PolicyArn: &policyArn,
	})
	ac.checkDeferError(err)

	_, err = iamClient.DeleteRole(&iam.DeleteRoleInput{
		RoleName: eksRoleName,
	})
	if ac.checkDeferError(err) {
		return
	}

	log.Printf("Role \"%s\" successfully deleted!\n", *eksRoleName)
}

func (ac *AWSCluster) deleteEC2NetworkInterfaces(ec2Client *ec2.EC2, cfClient *cloudformation.CloudFormation, nodesStackName *string) {
	cfResp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
		StackName: nodesStackName,
	})
	if ac.checkDeferError(err) {
		return
	}

	var sequrityGroup *string
	for _, output := range cfResp.Stacks[0].Outputs {
		if *output.OutputKey == "NodeSecurityGroup" {
			sequrityGroup = output.OutputValue
			break
		}
	}

	ec2Resp, err := ec2Client.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
		Filters: []*ec2.Filter{
			{
				Name:   aws.String("group-id"),
				Values: []*string{sequrityGroup},
			},
		},
	})

	if ac.checkDeferError(err) {
		return
	}

	for _, networkInterface := range ec2Resp.NetworkInterfaces {
		_, err := ec2Client.DeleteNetworkInterface(&ec2.DeleteNetworkInterfaceInput{
			NetworkInterfaceId: networkInterface.NetworkInterfaceId,
		})

		ac.checkDeferError(err)
	}
}

//nolint:funlen
func (ac *AWSCluster) deleteEksClusterVpc(cfClient *cloudformation.CloudFormation, ec2Client *ec2.EC2, clusterStackName *string) {
	log.Printf("Deleting Amazon EKS Cluster VPC \"%s\"...\n", *clusterStackName)

	resp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
		StackName: clusterStackName,
	})
	if ac.checkDeferError(err) {
		return
	}
	outputsMap := outputsToMap(resp.Stacks[0].Outputs)

	output, err := ec2Client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
		Filters: []*ec2.Filter{
			{
				Name:   aws.String("vpc-id"),
				Values: []*string{outputsMap.VpcId},
			},
		},
	})
	if !ac.checkDeferError(err) {
		for _, sg := range output.SecurityGroups {
			if *sg.GroupName != "default" {
				log.Printf("Deleting EC2 Security Group %s...", *sg.GroupId)
				_, err = ec2Client.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{GroupId: sg.GroupId})
				ac.checkDeferError(err)
			}
		}
	}

	_, err = ec2Client.DeleteVpc(&ec2.DeleteVpcInput{VpcId: outputsMap.VpcId})
	ac.checkDeferError(err)

	stackId := resp.Stacks[0].StackId

	_, err = cfClient.DeleteStack(&cloudformation.DeleteStackInput{
		StackName: clusterStackName,
	})
	if err != nil {
		_, err = cfClient.DeleteStack(&cloudformation.DeleteStackInput{
			StackName:       clusterStackName,
			RetainResources: []*string{aws.String("Ipv6VPCCidrBlock")},
		})
		if ac.checkDeferError(err) {
			return
		}
	}

	for {
		resp, err := cfClient.DescribeStacks(&cloudformation.DescribeStacksInput{
			StackName: stackId,
{'fraction_non_alphanumeric': 0.14511935712597496, 'fraction_numerical': 0.0068541715906405105, 'mean_word_length': 4.564102564102564, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7474968', 'n_tokens_mistral': 3366, 'n_tokens_neox': 3105, 'n_words': 488}