github.com/justinjmoses/evergreen@v0.0.0-20170530173719-1d50e381ff0d/command/scp_command.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os/exec"
     7  
     8  	"github.com/mongodb/grip"
     9  )
    10  
    11  type ScpCommand struct {
    12  	Id     string
    13  	Source string
    14  	Dest   string
    15  
    16  	Stdout io.Writer
    17  	Stderr io.Writer
    18  
    19  	// info about the remote host
    20  	RemoteHostName string
    21  	User           string
    22  	Options        []string
    23  
    24  	// tells us whether to copy from local to remote or from remote to local
    25  	SourceIsRemote bool
    26  
    27  	// set after the command is started
    28  	Cmd *exec.Cmd
    29  }
    30  
    31  func (self *ScpCommand) Run() error {
    32  	grip.Debugf("SCPCommand(%s) beginning Run()", self.Id)
    33  
    34  	if err := self.Start(); err != nil {
    35  		return err
    36  	}
    37  
    38  	if self.Cmd != nil && self.Cmd.Process != nil {
    39  		grip.Debugf("SCPCommand(%s) started process %d", self.Id, self.Cmd.Process.Pid)
    40  	} else {
    41  		grip.Debugf("SCPCommand(%s) has nil Cmd or Cmd.Process in Run()", self.Id)
    42  	}
    43  
    44  	return self.Cmd.Wait()
    45  }
    46  
    47  func (self *ScpCommand) Start() error {
    48  
    49  	// build the remote side of the connection, in user@host: format
    50  	remote := self.RemoteHostName
    51  	if self.User != "" {
    52  		remote = fmt.Sprintf("%s@%s", self.User, remote)
    53  	}
    54  
    55  	// set up the source and destination
    56  	source := self.Source
    57  	dest := self.Dest
    58  	if self.SourceIsRemote {
    59  		source = fmt.Sprintf("%s:%s", remote, source)
    60  	} else {
    61  		dest = fmt.Sprintf("%s:%s", remote, dest)
    62  	}
    63  
    64  	// build the command
    65  	cmdArray := append(self.Options, source, dest)
    66  
    67  	// set up execution
    68  	cmd := exec.Command("scp", cmdArray...)
    69  	cmd.Stdout = self.Stdout
    70  	cmd.Stderr = self.Stderr
    71  
    72  	// cache the command running
    73  	self.Cmd = cmd
    74  
    75  	return cmd.Start()
    76  }
    77  
    78  func (self *ScpCommand) Stop() error {
    79  	if self.Cmd != nil && self.Cmd.Process != nil {
    80  		grip.Debugf("SCPCommand(%s) killing process %d", self.Id, self.Cmd.Process.Pid)
    81  		return self.Cmd.Process.Kill()
    82  	}
    83  	grip.Warningf("SCPCommand(%s) Trying to stop command but Cmd / Process was nil", self.Id)
    84  	return nil
    85  }