Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix 695 destroy #697

Merged
merged 3 commits into from
Nov 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 19 additions & 183 deletions cmd/destroy.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,12 @@
package cmd

import (
"errors"
"fmt"
"github.com/kubefirst/kubefirst/internal/services"
"github.com/kubefirst/kubefirst/pkg"
"log"
"net/http"
"os"
"syscall"
"time"

"github.com/kubefirst/kubefirst/configs"
"github.com/kubefirst/kubefirst/internal/flagset"
"github.com/kubefirst/kubefirst/internal/gitlab"
"github.com/kubefirst/kubefirst/internal/handlers"
"github.com/kubefirst/kubefirst/internal/k3d"
"github.com/kubefirst/kubefirst/internal/k8s"
"github.com/kubefirst/kubefirst/internal/progressPrinter"
"github.com/kubefirst/kubefirst/internal/terraform"
"github.com/kubefirst/kubefirst/internal/gitClient"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand All @@ -30,186 +18,34 @@ var destroyCmd = &cobra.Command{
Long: "destroy all the resources installed via Kubefirst installer",
RunE: func(cmd *cobra.Command, args []string) error {

config := configs.ReadConfig()

destroyFlags, err := flagset.ProcessDestroyFlags(cmd)
if err != nil {
log.Println(err)
return err
}

globalFlags, err := flagset.ProcessGlobalFlags(cmd)
if err != nil {
log.Println(err)
return err
}

if globalFlags.SilentMode {
informUser(
"Silent mode enabled, most of the UI prints wont be showed. Please check the logs for more details.\n",
globalFlags.SilentMode,
)
}

// todo: wrap business logic into the handler
if viper.GetString("cloud") == pkg.CloudK3d && config.GitHubPersonalAccessToken == "" {

httpClient := http.DefaultClient
gitHubService := services.NewGitHubService(httpClient)
gitHubHandler := handlers.NewGitHubHandler(gitHubService)
gitHubAccessToken, err := gitHubHandler.AuthenticateUser()
//Destroy is implemented based on the flavor selected.
if viper.GetString("cloud") == flagset.CloudK3d {
err := destroyLocalGithubCmd.RunE(cmd, args)
if err != nil {
log.Println("Erroring destroying local+github:", err)
return err
}

if len(gitHubAccessToken) == 0 {
return errors.New("unable to retrieve a GitHub token for the user")
}

err = os.Setenv("KUBEFIRST_GITHUB_AUTH_TOKEN", gitHubAccessToken)
if err != nil {
return errors.New("unable to set KUBEFIRST_GITHUB_AUTH_TOKEN")
}
err = viper.WriteConfig()
if err != nil {
return err
}

// todo: set common way to load env. values (viper->struct->load-env)
// todo: use viper file to load it, not load env. value
if err := os.Setenv("KUBEFIRST_GITHUB_AUTH_TOKEN", gitHubAccessToken); err != nil {
return err
}
log.Println("\nKUBEFIRST_GITHUB_AUTH_TOKEN set via OAuth")
}

if viper.GetString("cloud") == "k3d" {
// todo add progress bars to this

//* step 1.1 - open port-forward to state store and vault
// todo --skip-git-terraform
kPortForwardMinio, err := k8s.PortForward(globalFlags.DryRun, "minio", "svc/minio", "9000:9000")
defer func() {
err = kPortForwardMinio.Process.Signal(syscall.SIGTERM)
} else if viper.GetString("cloud") == flagset.CloudAws {
if viper.GetString("gitprovider") == gitClient.Github {
err := destroyAwsGithubCmd.RunE(cmd, args)
if err != nil {
log.Println("Error closing kPortForwardMinio")
log.Println("Error destroying aws+github:", err)
return err
}
}()
kPortForwardVault, err := k8s.PortForward(globalFlags.DryRun, "vault", "svc/vault", "8200:8200")
defer func() {
err = kPortForwardVault.Process.Signal(syscall.SIGTERM)

} else if viper.GetString("gitprovider") == gitClient.Gitlab {
err := destroyAwsGitlabCmd.RunE(cmd, args)
if err != nil {
log.Println("Error closing kPortForwardVault")
log.Println("Error destroying aws+gitlab:", err)
return err
}
}()

//* step 1.2
// usersTfApplied := viper.GetBool("terraform.users.apply.complete")
// if usersTfApplied {
// informUser("terraform destroying users resources", globalFlags.SilentMode)
// tfEntrypoint := config.GitOpsRepoPath + "/terraform/users"
// terraform.InitDestroyAutoApprove(globalFlags.DryRun, tfEntrypoint)
// informUser("successfully destroyed users resources", globalFlags.SilentMode)
// }

//* step 1.3 - terraform destroy github
githubTfApplied := viper.GetBool("terraform.github.apply.complete")
if githubTfApplied {
informUser("terraform destroying github resources", globalFlags.SilentMode)
tfEntrypoint := config.GitOpsRepoPath + "/terraform/github"
terraform.InitDestroyAutoApprove(globalFlags.DryRun, tfEntrypoint)
informUser("successfully destroyed github resources", globalFlags.SilentMode)
} else {
return fmt.Errorf("not supported git-provider")
}

//* step 2 - delete k3d cluster
// this could be useful for us to chase down in eks and destroy everything
// in the cloud / cluster minus eks to iterate from argocd forward
// todo --skip-cluster-destroy
informUser("deleting k3d cluster", globalFlags.SilentMode)
k3d.DeleteK3dCluster()
informUser("k3d cluster deleted", globalFlags.SilentMode)
informUser("be sure to run `kubefirst clean` before your next cloud provision", globalFlags.SilentMode)

//* step 3 - clean local .k1 dir
// err = cleanCmd.RunE(cmd, args)
// if err != nil {
// log.Println("Error running:", cleanCmd.Name())
// return err
// }
os.Exit(0)
}

progressPrinter.SetupProgress(2, globalFlags.SilentMode)

if globalFlags.DryRun {
destroyFlags.SkipGitlabTerraform = true
destroyFlags.SkipDeleteRegistryApplication = true
destroyFlags.SkipBaseTerraform = true
}
progressPrinter.AddTracker("step-prepare", "Open Ports", 3)

informUser("Open argocd port-forward", globalFlags.SilentMode)
progressPrinter.IncrementTracker("step-prepare", 1)

log.Println("destroying gitlab terraform")

progressPrinter.AddTracker("step-destroy", "Destroy Cloud", 4)
progressPrinter.IncrementTracker("step-destroy", 1)
informUser("Destroying Gitlab", globalFlags.SilentMode)
if !destroyFlags.SkipGitlabTerraform {
kPortForward, _ := k8s.PortForward(globalFlags.DryRun, "gitlab", "svc/gitlab-webservice-default", "8888:8080")
defer func() {
if kPortForward != nil {
log.Println("Closed GitLab port forward")
_ = kPortForward.Process.Signal(syscall.SIGTERM)
}
}()
informUser("Open gitlab port-forward", globalFlags.SilentMode)
progressPrinter.IncrementTracker("step-prepare", 1)

gitlab.DestroyGitlabTerraform(destroyFlags.SkipGitlabTerraform)
} else {
return fmt.Errorf("not supported mode")
}
progressPrinter.IncrementTracker("step-destroy", 1)

log.Println("gitlab terraform destruction complete")

//This should wrapped into a function, maybe to move to: k8s.DeleteRegistryApplication
if !destroyFlags.SkipDeleteRegistryApplication {
kPortForwardArgocd, _ := k8s.PortForward(globalFlags.DryRun, "argocd", "svc/argocd-server", "8080:80")
defer func() {
if kPortForwardArgocd != nil {
log.Println("Closed argocd port forward")
_ = kPortForwardArgocd.Process.Signal(syscall.SIGTERM)
}
}()
informUser("Open argocd port-forward", globalFlags.SilentMode)
progressPrinter.IncrementTracker("step-prepare", 1)

log.Println("deleting registry application in argocd")
// delete argocd registry
informUser("Destroying Registry Application", globalFlags.SilentMode)
k8s.DeleteRegistryApplication(destroyFlags.SkipDeleteRegistryApplication)
progressPrinter.IncrementTracker("step-destroy", 1)
log.Println("registry application deleted")
}

log.Println("terraform destroy base")
informUser("Destroying Cluster", globalFlags.SilentMode)
terraform.DestroyBaseTerraform(destroyFlags.SkipBaseTerraform)
progressPrinter.IncrementTracker("step-destroy", 1)

// destroy hosted zone
if destroyFlags.HostedZoneDelete {
hostedZone := viper.GetString("aws.hostedzonename")
awsHandler := handlers.NewAwsHandler(hostedZone, destroyFlags)
err := awsHandler.HostedZoneDelete()
if err != nil {
// if error, just log it
log.Println(err)
}
}

informUser("All Destroyed", globalFlags.SilentMode)

log.Println("terraform base destruction complete")
fmt.Println("End of execution destroy")
Expand Down
159 changes: 159 additions & 0 deletions cmd/destroyAwsGithub.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
"errors"
"fmt"
"log"
"net/http"
"os"
"syscall"
"time"

"github.com/kubefirst/kubefirst/configs"
"github.com/kubefirst/kubefirst/internal/flagset"
"github.com/kubefirst/kubefirst/internal/handlers"
"github.com/kubefirst/kubefirst/internal/k8s"
"github.com/kubefirst/kubefirst/internal/progressPrinter"
"github.com/kubefirst/kubefirst/internal/services"
"github.com/kubefirst/kubefirst/internal/terraform"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// destroyAwsGithubCmd represents the destroyAwsGithub command
var destroyAwsGithubCmd = &cobra.Command{
Use: "destroy-aws-github",
Short: "A brief description of your command",
Long: `TBD`,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("destroy-aws-github called")
config := configs.ReadConfig()

destroyFlags, err := flagset.ProcessDestroyFlags(cmd)
if err != nil {
log.Println(err)
return err
}

globalFlags, err := flagset.ProcessGlobalFlags(cmd)
if err != nil {
log.Println(err)
return err
}

if globalFlags.SilentMode {
informUser(
"Silent mode enabled, most of the UI prints wont be showed. Please check the logs for more details.\n",
globalFlags.SilentMode,
)
}

gitHubAccessToken := config.GitHubPersonalAccessToken
httpClient := http.DefaultClient
gitHubService := services.NewGitHubService(httpClient)
gitHubHandler := handlers.NewGitHubHandler(gitHubService)

if gitHubAccessToken == "" {

gitHubAccessToken, err = gitHubHandler.AuthenticateUser()
if err != nil {
return err
}

if gitHubAccessToken == "" {
return errors.New("cannot create a cluster without a github auth token. please export your " +
"KUBEFIRST_GITHUB_AUTH_TOKEN in your terminal",
)
}

// todo: set common way to load env. values (viper->struct->load-env)
if err := os.Setenv("KUBEFIRST_GITHUB_AUTH_TOKEN", gitHubAccessToken); err != nil {
return err
}
log.Println("\nKUBEFIRST_GITHUB_AUTH_TOKEN set via OAuth")
}

progressPrinter.SetupProgress(2, globalFlags.SilentMode)

if globalFlags.DryRun {
destroyFlags.SkipDeleteRegistryApplication = true
destroyFlags.SkipBaseTerraform = true
destroyFlags.SkipGithubTerraform = true
}
progressPrinter.AddTracker("step-prepare", "Open Ports", 3)

informUser("Open argocd port-forward", globalFlags.SilentMode)
progressPrinter.IncrementTracker("step-prepare", 1)

progressPrinter.AddTracker("step-destroy", "Destroy Cloud", 4)
progressPrinter.IncrementTracker("step-destroy", 1)

if !destroyFlags.SkipGithubTerraform {
githubTfApplied := viper.GetBool("terraform.github.apply.complete")
if githubTfApplied {
informUser("terraform destroying github resources", globalFlags.SilentMode)
tfEntrypoint := config.GitOpsRepoPath + "/terraform/github"
terraform.InitDestroyAutoApprove(globalFlags.DryRun, tfEntrypoint)
informUser("successfully destroyed github resources", globalFlags.SilentMode)
}
log.Println("github terraform destruction complete")
}

progressPrinter.IncrementTracker("step-destroy", 1)

//This should wrapped into a function, maybe to move to: k8s.DeleteRegistryApplication
if !destroyFlags.SkipDeleteRegistryApplication {
kPortForwardArgocd, _ := k8s.PortForward(globalFlags.DryRun, "argocd", "svc/argocd-server", "8080:80")
defer func() {
if kPortForwardArgocd != nil {
log.Println("Closed argocd port forward")
_ = kPortForwardArgocd.Process.Signal(syscall.SIGTERM)
}
}()
informUser("Open argocd port-forward", globalFlags.SilentMode)
progressPrinter.IncrementTracker("step-prepare", 1)

log.Println("deleting registry application in argocd")
// delete argocd registry
informUser("Destroying Registry Application", globalFlags.SilentMode)
k8s.DeleteRegistryApplication(destroyFlags.SkipDeleteRegistryApplication)
log.Println("registry application deleted")
}

progressPrinter.IncrementTracker("step-destroy", 1)

log.Println("terraform destroy base")
informUser("Destroying Cluster", globalFlags.SilentMode)
terraform.DestroyBaseTerraform(destroyFlags.SkipBaseTerraform)
progressPrinter.IncrementTracker("step-destroy", 1)

// destroy hosted zone
if destroyFlags.HostedZoneDelete {
hostedZone := viper.GetString("aws.hostedzonename")
awsHandler := handlers.NewAwsHandler(hostedZone, destroyFlags)
err := awsHandler.HostedZoneDelete()
if err != nil {
// if error, just log it
log.Println(err)
}
}

informUser("All Destroyed", globalFlags.SilentMode)

fmt.Println("End of execution destroy")
time.Sleep(time.Millisecond * 100)

log.Println(destroyFlags, config)
return nil
},
}

func init() {
clusterCmd.AddCommand(destroyAwsGithubCmd)
currentCommand := destroyAwsGithubCmd
flagset.DefineGlobalFlags(currentCommand)
flagset.DefineDestroyFlags(currentCommand)
}
Loading