github.com/scaleway/scaleway-cli@v1.11.1/pkg/commands/kill.go (about)

     1  // Copyright (C) 2015 Scaleway. All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE.md file.
     4  
     5  package commands
     6  
     7  import (
     8  	"fmt"
     9  	"os/exec"
    10  
    11  	"github.com/Sirupsen/logrus"
    12  	"github.com/scaleway/scaleway-cli/pkg/api"
    13  	"github.com/scaleway/scaleway-cli/pkg/utils"
    14  )
    15  
    16  // KillArgs are flags for the `RunKill` function
    17  type KillArgs struct {
    18  	Gateway string
    19  	Server  string
    20  	SSHUser string
    21  	SSHPort int
    22  }
    23  
    24  // RunKill is the handler for 'scw kill'
    25  func RunKill(ctx CommandContext, args KillArgs) error {
    26  	serverID, err := ctx.API.GetServerID(args.Server)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	command := "halt"
    31  	server, err := ctx.API.GetServer(serverID)
    32  	if err != nil {
    33  		return fmt.Errorf("failed to get server information for %s: %v", serverID, err)
    34  	}
    35  
    36  	// Resolve gateway
    37  	if args.Gateway == "" {
    38  		args.Gateway = ctx.Getenv("SCW_GATEWAY")
    39  	}
    40  	var gateway string
    41  	if args.Gateway == serverID || args.Gateway == args.Server {
    42  		gateway = ""
    43  	} else {
    44  		gateway, err = api.ResolveGateway(ctx.API, args.Gateway)
    45  		if err != nil {
    46  			return fmt.Errorf("cannot resolve Gateway '%s': %v", args.Gateway, err)
    47  		}
    48  	}
    49  
    50  	sshCommand := utils.NewSSHExecCmd(server.PublicAddress.IP, server.PrivateIP, args.SSHUser, args.SSHPort, true, []string{command}, gateway)
    51  
    52  	logrus.Debugf("Executing: %s", sshCommand)
    53  
    54  	spawn := exec.Command("ssh", sshCommand.Slice()[1:]...)
    55  	spawn.Stdout = ctx.Stdout
    56  	spawn.Stdin = ctx.Stdin
    57  	spawn.Stderr = ctx.Stderr
    58  
    59  	return spawn.Run()
    60  }