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

ssh: Abort keepalive on not found #257

Merged
merged 3 commits into from
Mar 20, 2023
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
7 changes: 7 additions & 0 deletions pkg/cmd/ssh/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import (
"context"
"os"
"time"

operationsv1alpha1 "github.com/gardener/gardener/pkg/apis/operations/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

func SetBastionAvailabilityChecker(f func(hostname string, privateKey []byte) error) {
Expand Down Expand Up @@ -42,3 +45,7 @@ func SetKeepAliveInterval(d time.Duration) {

keepAliveInterval = d
}

func SetWaitForSignal(f func(ctx context.Context, o *SSHOptions, shootClient client.Client, bastion *operationsv1alpha1.Bastion, nodeHostname string, nodePrivateKeyFiles []string, signalChan <-chan struct{}) error) {
waitForSignal = f
}
212 changes: 109 additions & 103 deletions pkg/cmd/ssh/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,103 @@ var (

return cmd.Run()
}
// waitForSignal informs the user about their SSHOptions and keeps the
// bastion alive until gardenctl exits.
waitForSignal = func(ctx context.Context, o *SSHOptions, shootClient client.Client, bastion *operationsv1alpha1.Bastion, nodeHostname string, nodePrivateKeyFiles []string, signalChan <-chan struct{}) error {
petersutter marked this conversation as resolved.
Show resolved Hide resolved
if nodeHostname == "" {
nodeHostname = "IP_OR_HOSTNAME"

nodes, err := getNodes(ctx, shootClient)
if err != nil {
return fmt.Errorf("failed to list shoot cluster nodes: %w", err)
}

table := &metav1beta1.Table{
ColumnDefinitions: []metav1.TableColumnDefinition{
{
Name: "Node Name",
Type: "string",
Format: "name",
},
{
Name: "Status",
Type: "string",
},
{
Name: "IP",
Type: "string",
},
{
Name: "Hostname",
Type: "string",
},
},
Rows: []metav1.TableRow{},
}

for _, node := range nodes {
ip := ""
hostname := ""
status := "Ready"

if !isNodeReady(node) {
status = "Not Ready"
}

for _, addr := range node.Status.Addresses {
switch addr.Type {
case corev1.NodeInternalIP:
ip = addr.Address

case corev1.NodeInternalDNS:
hostname = addr.Address

// internal names have priority, as we jump via a bastion host,
// but in case the cloud provider does not offer internal IPs,
// we fallback to external values

case corev1.NodeExternalIP:
if ip == "" {
ip = addr.Address
}

case corev1.NodeExternalDNS:
if hostname == "" {
hostname = addr.Address
}
}
}

table.Rows = append(table.Rows, metav1.TableRow{
Cells: []interface{}{node.Name, status, ip, hostname},
})
}

fmt.Fprintln(o.IOStreams.Out, "The shoot cluster has the following nodes:")
fmt.Fprintln(o.IOStreams.Out, "")

printer := printers.NewTablePrinter(printers.PrintOptions{})
if err := printer.PrintObj(table, o.IOStreams.Out); err != nil {
return fmt.Errorf("failed to output node table: %w", err)
}

fmt.Fprintln(o.IOStreams.Out, "")
}

bastionAddr := preferredBastionAddress(bastion)
connectCmd := sshCommandLine(o, bastionAddr, nodePrivateKeyFiles, nodeHostname)

fmt.Fprintln(o.IOStreams.Out, "Connect to shoot nodes by using the bastion as a proxy/jump host, for example:")
fmt.Fprintln(o.IOStreams.Out, "")
fmt.Fprintln(o.IOStreams.Out, connectCmd)
fmt.Fprintln(o.IOStreams.Out, "")

fmt.Fprintln(o.IOStreams.Out, "Press Ctrl-C to stop gardenctl, after which the bastion will be removed.")

<-signalChan

return nil
}
)

// SSHOptions is a struct to support ssh command
Expand Down Expand Up @@ -544,7 +641,7 @@ func (o *SSHOptions) Run(f util.Factory) error {
}

// continuously keep the bastion alive by renewing its annotation
go keepBastionAlive(ctx, gardenClient.RuntimeClient(), bastion.DeepCopy())
go keepBastionAlive(ctx, cancel, gardenClient.RuntimeClient(), bastion.DeepCopy())

logger.Info("Waiting for bastion to be ready…", "waitTimeout", o.WaitTimeout)

Expand Down Expand Up @@ -638,10 +735,10 @@ func cleanup(ctx context.Context, o *SSHOptions, gardenClient client.Client, bas
logger := klog.FromContext(ctx)

if !o.KeepBastion {
logger.Info("Deleting bastion", "bastion", klog.KObj(bastion))
logger.Info("Cleaning up")

if err := gardenClient.Delete(ctx, bastion); client.IgnoreNotFound(err) != nil {
logger.Error(err, "Failed to delete bastion.")
logger.Error(err, "Failed to delete bastion.", "bastion", klog.KObj(bastion))
}

if o.generatedSSHKeys {
Expand Down Expand Up @@ -823,104 +920,6 @@ func remoteShell(ctx context.Context, o *SSHOptions, bastion *operationsv1alpha1
return execCommand(ctx, "ssh", args, o)
}

// waitForSignal informs the user about their SSHOptions and keeps the
// bastion alive until gardenctl exits.
func waitForSignal(ctx context.Context, o *SSHOptions, shootClient client.Client, bastion *operationsv1alpha1.Bastion, nodeHostname string, nodePrivateKeyFiles []string, signalChan <-chan struct{}) error {
if nodeHostname == "" {
nodeHostname = "IP_OR_HOSTNAME"

nodes, err := getNodes(ctx, shootClient)
if err != nil {
return fmt.Errorf("failed to list shoot cluster nodes: %w", err)
}

table := &metav1beta1.Table{
ColumnDefinitions: []metav1.TableColumnDefinition{
{
Name: "Node Name",
Type: "string",
Format: "name",
},
{
Name: "Status",
Type: "string",
},
{
Name: "IP",
Type: "string",
},
{
Name: "Hostname",
Type: "string",
},
},
Rows: []metav1.TableRow{},
}

for _, node := range nodes {
ip := ""
hostname := ""
status := "Ready"

if !isNodeReady(node) {
status = "Not Ready"
}

for _, addr := range node.Status.Addresses {
switch addr.Type {
case corev1.NodeInternalIP:
ip = addr.Address

case corev1.NodeInternalDNS:
hostname = addr.Address

// internal names have priority, as we jump via a bastion host,
// but in case the cloud provider does not offer internal IPs,
// we fallback to external values

case corev1.NodeExternalIP:
if ip == "" {
ip = addr.Address
}

case corev1.NodeExternalDNS:
if hostname == "" {
hostname = addr.Address
}
}
}

table.Rows = append(table.Rows, metav1.TableRow{
Cells: []interface{}{node.Name, status, ip, hostname},
})
}

fmt.Fprintln(o.IOStreams.Out, "The shoot cluster has the following nodes:")
fmt.Fprintln(o.IOStreams.Out, "")

printer := printers.NewTablePrinter(printers.PrintOptions{})
if err := printer.PrintObj(table, o.IOStreams.Out); err != nil {
return fmt.Errorf("failed to output node table: %w", err)
}

fmt.Fprintln(o.IOStreams.Out, "")
}

bastionAddr := preferredBastionAddress(bastion)
connectCmd := sshCommandLine(o, bastionAddr, nodePrivateKeyFiles, nodeHostname)

fmt.Fprintln(o.IOStreams.Out, "Connect to shoot nodes by using the bastion as a proxy/jump host, for example:")
fmt.Fprintln(o.IOStreams.Out, "")
fmt.Fprintln(o.IOStreams.Out, connectCmd)
fmt.Fprintln(o.IOStreams.Out, "")

fmt.Fprintln(o.IOStreams.Out, "Press Ctrl-C to stop gardenctl, after which the bastion will be removed.")

<-signalChan

return nil
}

func isNodeReady(node corev1.Node) bool {
for _, cond := range node.Status.Conditions {
if cond.Type == corev1.NodeReady {
Expand Down Expand Up @@ -967,8 +966,8 @@ func getKeepAliveInterval() time.Duration {
return keepAliveInterval
}

func keepBastionAlive(ctx context.Context, gardenClient client.Client, bastion *operationsv1alpha1.Bastion) {
logger := klog.FromContext(ctx)
func keepBastionAlive(ctx context.Context, cancel context.CancelFunc, gardenClient client.Client, bastion *operationsv1alpha1.Bastion) {
logger := klog.FromContext(ctx).WithValues("bastion", klog.KObj(bastion))

ticker := time.NewTicker(getKeepAliveInterval())
defer ticker.Stop()
Expand All @@ -986,6 +985,13 @@ func keepBastionAlive(ctx context.Context, gardenClient client.Client, bastion *
bastion.Annotations = map[string]string{}

if err := gardenClient.Get(ctx, key, bastion); err != nil {
if apierrors.IsNotFound(err) {
logger.Error(err, "Can't keep bastion alive. Bastion is already gone.")
cancel()

return
}

logger.Error(err, "Failed to keep bastion alive.")
}

Expand Down
33 changes: 33 additions & 0 deletions pkg/cmd/ssh/ssh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,39 @@ var _ = Describe("SSH Command", func() {
Expect(bastion.Annotations).To(HaveKeyWithValue(corev1beta1constants.GardenerOperation, corev1beta1constants.GardenerOperationKeepalive))
})

It("should stop keepalive when bastion is deleted ", func() {
options := ssh.NewSSHOptions(streams)
options.KeepBastion = true // we need to assert its annotations later

cmd := ssh.NewCmdSSH(factory, options)

// simulate an external controller processing the bastion and proving a successful status
go waitForBastionThenSetBastionReady(ctx, gardenClient, bastionName, *testProject.Spec.Namespace, bastionHostname, bastionIP)

// end the test after a couple of seconds (enough seconds for the keep-alive
// goroutine to do its thing)
ssh.SetKeepAliveInterval(100 * time.Millisecond)
signalChan := make(chan os.Signal, 1)
ssh.SetCreateSignalChannel(func() chan os.Signal {
return signalChan
})

// Once the waitForSignal function is called we delete the bastion
ssh.SetWaitForSignal(func(ctx context.Context, o *ssh.SSHOptions, shootClient client.Client, bastion *operationsv1alpha1.Bastion, nodeHostname string, nodePrivateKeyFiles []string, signalChan <-chan struct{}) error {
By("deleting bastion")
Expect(gardenClient.Delete(ctx, bastion)).To(Succeed())

<-signalChan

return nil
})

// let the magic happen
Expect(cmd.RunE(cmd, nil)).To(Succeed())

Expect(logs.String()).To(ContainSubstring("Can't keep bastion alive. Bastion is already gone."))
})

It("should skip the availability check", func() {
options := ssh.NewSSHOptions(streams)
options.SkipAvailabilityCheck = true
Expand Down