Skip to content

Commit

Permalink
fix: remove duplicate line in known_hosts when minikube deletes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jiaming Tang committed Jul 27, 2023
1 parent 37bf89b commit 0835970
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 0 deletions.
40 changes: 40 additions & 0 deletions cmd/minikube/cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"github.com/docker/machine/libmachine"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/client-go/util/homedir"
"k8s.io/klog/v2"
cmdcfg "k8s.io/minikube/cmd/minikube/cmd/config"
"k8s.io/minikube/pkg/drivers/kic"
Expand All @@ -48,11 +49,14 @@ import (
"k8s.io/minikube/pkg/minikube/kubeconfig"
"k8s.io/minikube/pkg/minikube/localpath"
"k8s.io/minikube/pkg/minikube/machine"
"k8s.io/minikube/pkg/minikube/mustload"
"k8s.io/minikube/pkg/minikube/node"
"k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/out/register"
"k8s.io/minikube/pkg/minikube/reason"
"k8s.io/minikube/pkg/minikube/sshagent"
"k8s.io/minikube/pkg/minikube/style"
"k8s.io/minikube/pkg/util"
)

var (
Expand Down Expand Up @@ -233,6 +237,9 @@ func runDelete(_ *cobra.Command, args []string) {
defer cancel()

if deleteAll {
if err := deleteKnownHosts(); err != nil {
klog.Warningf("error deleting known hosts: %v", err)
}
deleteContainersAndVolumes(delCtx, oci.Docker)
deleteContainersAndVolumes(delCtx, oci.Podman)

Expand Down Expand Up @@ -723,3 +730,36 @@ func getPids(path string) ([]int, error) {

return pids, nil
}

func deleteKnownHosts() error {
cname := ClusterFlagValue()
co, err := mustload.RunningWithError(cname)
if err != nil {
return err
}
if co.CP.Host.DriverName == driver.None {
// none' driver does not support 'minikube ssh-host' command
// so nothing needs to be done
return nil
}
var n *config.Node
if nodeName == "" {
n = co.CP.Node
} else {
n, _, err = node.Retrieve(*co.Config, nodeName)
if err != nil {
return fmt.Errorf("node %s does not exist: %v", nodeName, err)
}
}
// acquire the current key line
keyLine, err := machine.RunSSHHostCommand(co.API, *co.Config, *n, "ssh-keyscan", []string{"-t", "rsa"})
if err != nil {
return fmt.Errorf("failed to acquire the keys: %v", err)
}

// remove this line from known_hosts file if it exists
knownHosts := filepath.Join(homedir.HomeDir(), ".ssh", "known_hosts")

return util.RemoveLineFromFile(keyLine, knownHosts)

}
50 changes: 50 additions & 0 deletions pkg/minikube/mustload/mustload.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,56 @@ func Running(name string) ClusterController {
}
}

// Running is a cmd-friendly way to load a running cluster, and return an error
// if the cluster is not running
func RunningWithError(name string) (ClusterController, error) {
api, cc := Partial(name)

cp, err := config.PrimaryControlPlane(cc)
if err != nil {
return ClusterController{}, fmt.Errorf("unable to find control plane: %v", err)
}

machineName := config.MachineName(*cc, cp)
hs, err := machine.Status(api, machineName)
if err != nil {
return ClusterController{}, fmt.Errorf("unable to get machine status: %v", err)
}

if hs != state.Running.String() {
out.Styled(style.Shrug, `The control plane node is not running (state={{.state}})`, out.V{"name": cp.Name, "state": hs})
return ClusterController{}, fmt.Errorf("the control plane node is not running")
}

host, err := machine.LoadHost(api, name)
if err != nil {
return ClusterController{}, fmt.Errorf("unable to load host: %v", err)
}

cr, err := machine.CommandRunner(host)
if err != nil {
return ClusterController{}, fmt.Errorf("unable to get command runner: %v", err)
}

hostname, ip, port, err := driver.ControlPlaneEndpoint(cc, &cp, host.DriverName)
if err != nil {
return ClusterController{}, fmt.Errorf("Unable to get forwarded endpoint: %v", err)
}

return ClusterController{
API: api,
Config: cc,
CP: ControlPlane{
Runner: cr,
Host: host,
Node: &cp,
Hostname: hostname,
IP: ip,
Port: port,
},
}, nil
}

// Healthy is a cmd-friendly way to load a healthy cluster
func Healthy(name string) ClusterController {
co := Running(name)
Expand Down
35 changes: 35 additions & 0 deletions pkg/util/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ limitations under the License.
package util

import (
"bufio"
"fmt"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"

"github.com/blang/semver/v4"
units "github.com/docker/go-units"
Expand Down Expand Up @@ -123,3 +125,36 @@ func RemoveDuplicateStrings(initial []string) []string {
}
return result
}

// remove the specified line from the given file
func RemoveLineFromFile(knownHostLine string, filePath string) error {
fd, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return fmt.Errorf("failed to open %s: %v", filePath, err)
}
defer fd.Close()

// read each line from known_hosts and find theline we want to delete
scanner := bufio.NewScanner(fd)
newLines := make([]string, 0)
for scanner.Scan() {
line := string(scanner.Bytes())
if strings.TrimSpace(line) != strings.TrimSpace(knownHostLine) {
// remove the line which is identical with the key
newLines = append(newLines, line)
}
}
// remove the contents and move to the head of this file
fd.Truncate(0)
fd.Seek(0, 0)

// write the new content into the file

for _, line := range newLines {
if _, err := fmt.Fprintln(fd, line); err != nil {
return fmt.Errorf("failed to write to %s: %v", filePath, err)
}
}

return nil
}

0 comments on commit 0835970

Please sign in to comment.