Skip to content

Commit d5bd508

Browse files
committed
Add cleanup command
This also refacctors some common code to common.go
1 parent ab3e7cf commit d5bd508

File tree

4 files changed

+121
-82
lines changed

4 files changed

+121
-82
lines changed

gitpod-network-check/cmd/checks.go

Lines changed: 1 addition & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"time"
1111

1212
"github.com/aws/aws-sdk-go-v2/aws"
13-
"github.com/aws/aws-sdk-go-v2/config"
1413
"github.com/aws/aws-sdk-go-v2/service/ec2"
1514
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
1615
"github.com/aws/aws-sdk-go-v2/service/iam"
@@ -23,28 +22,6 @@ import (
2322
"k8s.io/apimachinery/pkg/util/wait"
2423
)
2524

26-
const gitpodRoleName = "GitpodNetworkCheck"
27-
const gitpodInstanceProfile = "GitpodNetworkCheck"
28-
29-
var networkCheckTag = []iam_types.Tag{
30-
{
31-
Key: aws.String("gitpod.io/network-check"),
32-
Value: aws.String("true"),
33-
},
34-
}
35-
36-
func initAwsConfig(ctx context.Context, region string) (aws.Config, error) {
37-
return config.LoadDefaultConfig(ctx, config.WithRegion(region))
38-
}
39-
40-
// this will be useful when we are cleaning up things at the end
41-
var (
42-
InstanceIds []string
43-
SecurityGroups []string
44-
Roles []string
45-
InstanceProfile string
46-
)
47-
4825
var checkCommand = &cobra.Command{ // nolint:gochecknoglobals
4926
PersistentPreRunE: validateSubnets,
5027
Use: "diagnose",
@@ -272,7 +249,7 @@ func launchInstances(ctx context.Context, ec2Client *ec2.Client, subnets []strin
272249
for _, subnet := range subnets {
273250
secGroup, err := createSecurityGroups(ctx, ec2Client, subnet)
274251
if err != nil {
275-
return nil, fmt.Errorf("❌ failed to create security group: %v", err)
252+
return nil, fmt.Errorf("❌ failed to create security group for subnet '%v': %v", subnet, err)
276253
}
277254
SecurityGroups = append(SecurityGroups, secGroup)
278255
instanceId, err := launchInstanceInSubnet(ctx, ec2Client, subnet, secGroup, profileArn)
@@ -486,64 +463,6 @@ func createSecurityGroups(ctx context.Context, svc *ec2.Client, subnetID string)
486463
return *sgID, nil
487464
}
488465

489-
func cleanup(ctx context.Context, svc *ec2.Client, iamsvc *iam.Client) {
490-
if len(InstanceIds) > 0 {
491-
_, err := svc.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
492-
InstanceIds: InstanceIds,
493-
})
494-
if err != nil {
495-
log.WithError(err).WithField("instanceIds", InstanceIds).Warnf("Failed to cleanup instances, please cleanup manually")
496-
}
497-
}
498-
if len(Roles) > 0 {
499-
for _, role := range Roles {
500-
_, err := iamsvc.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{PolicyArn: aws.String("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"), RoleName: aws.String(role)})
501-
if err != nil {
502-
log.WithError(err).WithField("rolename", role).Warnf("Failed to cleanup role, please cleanup manually")
503-
}
504-
505-
_, err = iamsvc.RemoveRoleFromInstanceProfile(ctx, &iam.RemoveRoleFromInstanceProfileInput{
506-
RoleName: aws.String(role),
507-
InstanceProfileName: aws.String(InstanceProfile),
508-
})
509-
if err != nil {
510-
log.WithError(err).WithField("roleName", role).WithField("profileName", InstanceProfile).Warnf("Failed to remove role from instance profile")
511-
}
512-
513-
_, err = iamsvc.DeleteRole(ctx, &iam.DeleteRoleInput{RoleName: aws.String(role)})
514-
if err != nil {
515-
log.WithError(err).WithField("rolename", role).Warnf("Failed to cleanup role, please cleanup manaullay")
516-
}
517-
}
518-
519-
_, err := iamsvc.DeleteInstanceProfile(ctx, &iam.DeleteInstanceProfileInput{
520-
InstanceProfileName: aws.String(InstanceProfile),
521-
})
522-
523-
if err != nil {
524-
log.WithError(err).WithField("instanceProfile", InstanceProfile).Warnf("Failed to clean up instance profile, please cleanup manually")
525-
}
526-
}
527-
528-
log.Info("Cleaning up: Waiting for 1 minute so network interfaces are deleted")
529-
time.Sleep(time.Minute)
530-
531-
if len(SecurityGroups) > 0 {
532-
for _, sg := range SecurityGroups {
533-
deleteSGInput := &ec2.DeleteSecurityGroupInput{
534-
GroupId: aws.String(sg),
535-
}
536-
537-
_, err := svc.DeleteSecurityGroup(ctx, deleteSGInput)
538-
if err != nil {
539-
log.WithError(err).WithField("securityGroup", sg).Warnf("Failed to clean up security group, please cleanup manually")
540-
}
541-
542-
}
543-
544-
}
545-
}
546-
547466
func createIAMRoleAndAttachPolicy(ctx context.Context, svc *iam.Client) (*iam_types.Role, error) {
548467
// Define the trust relationship
549468
trustPolicy := `{

gitpod-network-check/cmd/cleanup.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package cmd
2+
3+
import (
4+
"github.com/aws/aws-sdk-go-v2/service/ec2"
5+
"github.com/aws/aws-sdk-go-v2/service/iam"
6+
"github.com/spf13/cobra"
7+
)
8+
9+
var cleanCommand = &cobra.Command{ // nolint:gochecknoglobals
10+
PersistentPreRunE: validateSubnets,
11+
Use: "clean",
12+
Short: "Explicitly cleans up after the network check diagnosis",
13+
SilenceUsage: false,
14+
RunE: func(cmd *cobra.Command, args []string) error {
15+
cfg, err := initAwsConfig(cmd.Context(), networkConfig.AwsRegion)
16+
if err != nil {
17+
return err
18+
}
19+
20+
ec2Client := ec2.NewFromConfig(cfg)
21+
iamClient := iam.NewFromConfig(cfg)
22+
23+
cleanup(cmd.Context(), ec2Client, iamClient)
24+
return nil
25+
},
26+
}

gitpod-network-check/cmd/common.go

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package cmd
2+
3+
import (
4+
"context"
5+
"time"
6+
7+
"github.com/aws/aws-sdk-go-v2/aws"
8+
"github.com/aws/aws-sdk-go-v2/config"
9+
"github.com/aws/aws-sdk-go-v2/service/ec2"
10+
"github.com/aws/aws-sdk-go-v2/service/iam"
11+
iam_types "github.com/aws/aws-sdk-go-v2/service/iam/types"
12+
log "github.com/sirupsen/logrus"
13+
)
14+
15+
// this will be useful when we are cleaning up things at the end
16+
var (
17+
InstanceIds []string
18+
SecurityGroups []string
19+
Roles []string
20+
InstanceProfile string
21+
)
22+
23+
const gitpodRoleName = "GitpodNetworkCheck"
24+
const gitpodInstanceProfile = "GitpodNetworkCheck"
25+
26+
var networkCheckTag = []iam_types.Tag{
27+
{
28+
Key: aws.String("gitpod.io/network-check"),
29+
Value: aws.String("true"),
30+
},
31+
}
32+
33+
func initAwsConfig(ctx context.Context, region string) (aws.Config, error) {
34+
return config.LoadDefaultConfig(ctx, config.WithRegion(region))
35+
}
36+
37+
func cleanup(ctx context.Context, svc *ec2.Client, iamsvc *iam.Client) {
38+
if len(InstanceIds) > 0 {
39+
_, err := svc.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
40+
InstanceIds: InstanceIds,
41+
})
42+
if err != nil {
43+
log.WithError(err).WithField("instanceIds", InstanceIds).Warnf("Failed to cleanup instances, please cleanup manually")
44+
}
45+
}
46+
if len(Roles) > 0 {
47+
for _, role := range Roles {
48+
_, err := iamsvc.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{PolicyArn: aws.String("arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"), RoleName: aws.String(role)})
49+
if err != nil {
50+
log.WithError(err).WithField("rolename", role).Warnf("Failed to cleanup role, please cleanup manually")
51+
}
52+
53+
_, err = iamsvc.RemoveRoleFromInstanceProfile(ctx, &iam.RemoveRoleFromInstanceProfileInput{
54+
RoleName: aws.String(role),
55+
InstanceProfileName: aws.String(InstanceProfile),
56+
})
57+
if err != nil {
58+
log.WithError(err).WithField("roleName", role).WithField("profileName", InstanceProfile).Warnf("Failed to remove role from instance profile")
59+
}
60+
61+
_, err = iamsvc.DeleteRole(ctx, &iam.DeleteRoleInput{RoleName: aws.String(role)})
62+
if err != nil {
63+
log.WithError(err).WithField("rolename", role).Warnf("Failed to cleanup role, please cleanup manaullay")
64+
}
65+
}
66+
67+
_, err := iamsvc.DeleteInstanceProfile(ctx, &iam.DeleteInstanceProfileInput{
68+
InstanceProfileName: aws.String(InstanceProfile),
69+
})
70+
71+
if err != nil {
72+
log.WithError(err).WithField("instanceProfile", InstanceProfile).Warnf("Failed to clean up instance profile, please cleanup manually")
73+
}
74+
}
75+
76+
log.Info("Cleaning up: Waiting for 1 minute so network interfaces are deleted")
77+
time.Sleep(time.Minute)
78+
79+
if len(SecurityGroups) > 0 {
80+
for _, sg := range SecurityGroups {
81+
deleteSGInput := &ec2.DeleteSecurityGroupInput{
82+
GroupId: aws.String(sg),
83+
}
84+
85+
_, err := svc.DeleteSecurityGroup(ctx, deleteSGInput)
86+
if err != nil {
87+
log.WithError(err).WithField("securityGroup", sg).Warnf("Failed to clean up security group, please cleanup manually")
88+
}
89+
90+
}
91+
92+
}
93+
}

gitpod-network-check/cmd/root.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,6 @@ func readConfigFile() *viper.Viper {
126126

127127
func Execute() error {
128128
networkCheckCmd.AddCommand(checkCommand)
129+
networkCheckCmd.AddCommand(cleanCommand)
129130
return networkCheckCmd.Execute()
130131
}

0 commit comments

Comments
 (0)