github.com/jerryclinesmith/packer@v0.3.7/communicator/ssh/communicator.go (about)

     1  package ssh
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"code.google.com/p/go.crypto/ssh"
     7  	"errors"
     8  	"fmt"
     9  	"github.com/mitchellh/packer/packer"
    10  	"io"
    11  	"log"
    12  	"net"
    13  	"os"
    14  	"path/filepath"
    15  	"sync"
    16  	"time"
    17  )
    18  
    19  type comm struct {
    20  	client *ssh.ClientConn
    21  	config *Config
    22  	conn   net.Conn
    23  }
    24  
    25  // Config is the structure used to configure the SSH communicator.
    26  type Config struct {
    27  	// The configuration of the Go SSH connection
    28  	SSHConfig *ssh.ClientConfig
    29  
    30  	// Connection returns a new connection. The current connection
    31  	// in use will be closed as part of the Close method, or in the
    32  	// case an error occurs.
    33  	Connection func() (net.Conn, error)
    34  
    35  	// NoPty, if true, will not request a pty from the remote end.
    36  	NoPty bool
    37  }
    38  
    39  // Creates a new packer.Communicator implementation over SSH. This takes
    40  // an already existing TCP connection and SSH configuration.
    41  func New(config *Config) (result *comm, err error) {
    42  	// Establish an initial connection and connect
    43  	result = &comm{
    44  		config: config,
    45  	}
    46  
    47  	if err = result.reconnect(); err != nil {
    48  		result = nil
    49  		return
    50  	}
    51  
    52  	return
    53  }
    54  
    55  func (c *comm) Start(cmd *packer.RemoteCmd) (err error) {
    56  	session, err := c.newSession()
    57  	if err != nil {
    58  		return
    59  	}
    60  
    61  	// Setup our session
    62  	session.Stdin = cmd.Stdin
    63  	session.Stdout = cmd.Stdout
    64  	session.Stderr = cmd.Stderr
    65  
    66  	if !c.config.NoPty {
    67  		// Request a PTY
    68  		termModes := ssh.TerminalModes{
    69  			ssh.ECHO:          0,     // do not echo
    70  			ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
    71  			ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
    72  		}
    73  
    74  		if err = session.RequestPty("xterm", 80, 40, termModes); err != nil {
    75  			return
    76  		}
    77  	}
    78  
    79  	log.Printf("starting remote command: %s", cmd.Command)
    80  	err = session.Start(cmd.Command + "\n")
    81  	if err != nil {
    82  		return
    83  	}
    84  
    85  	// A channel to keep track of our done state
    86  	doneCh := make(chan struct{})
    87  	sessionLock := new(sync.Mutex)
    88  	timedOut := false
    89  
    90  	// Start a goroutine to wait for the session to end and set the
    91  	// exit boolean and status.
    92  	go func() {
    93  		defer session.Close()
    94  
    95  		err := session.Wait()
    96  		exitStatus := 0
    97  		if err != nil {
    98  			exitErr, ok := err.(*ssh.ExitError)
    99  			if ok {
   100  				exitStatus = exitErr.ExitStatus()
   101  			}
   102  		}
   103  
   104  		sessionLock.Lock()
   105  		defer sessionLock.Unlock()
   106  
   107  		if timedOut {
   108  			// We timed out, so set the exit status to -1
   109  			exitStatus = -1
   110  		}
   111  
   112  		log.Printf("remote command exited with '%d': %s", exitStatus, cmd.Command)
   113  		cmd.SetExited(exitStatus)
   114  		close(doneCh)
   115  	}()
   116  
   117  	go func() {
   118  		failures := 0
   119  		for {
   120  			dummy, err := c.config.Connection()
   121  			if err == nil {
   122  				failures = 0
   123  				dummy.Close()
   124  			}
   125  
   126  			select {
   127  			case <-doneCh:
   128  				return
   129  			default:
   130  			}
   131  
   132  			if err != nil {
   133  				log.Printf("background SSH connection checker failure: %s", err)
   134  				failures += 1
   135  			}
   136  
   137  			if failures < 5 {
   138  				time.Sleep(5 * time.Second)
   139  				continue
   140  			}
   141  
   142  			// Acquire a lock in order to modify session state
   143  			sessionLock.Lock()
   144  			defer sessionLock.Unlock()
   145  
   146  			// Kill the connection and mark that we timed out.
   147  			log.Printf("Too many SSH connection failures. Killing it!")
   148  			c.conn.Close()
   149  			timedOut = true
   150  
   151  			return
   152  		}
   153  	}()
   154  
   155  	return
   156  }
   157  
   158  func (c *comm) Upload(path string, input io.Reader) error {
   159  	// The target directory and file for talking the SCP protocol
   160  	target_dir := filepath.Dir(path)
   161  	target_file := filepath.Base(path)
   162  
   163  	// On windows, filepath.Dir uses backslash seperators (ie. "\tmp").
   164  	// This does not work when the target host is unix.  Switch to forward slash
   165  	// which works for unix and windows
   166  	target_dir = filepath.ToSlash(target_dir)
   167  
   168  	scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error {
   169  		return scpUploadFile(target_file, input, w, stdoutR)
   170  	}
   171  
   172  	return c.scpSession("scp -vt "+target_dir, scpFunc)
   173  }
   174  
   175  func (c *comm) UploadDir(dst string, src string, excl []string) error {
   176  	log.Printf("Upload dir '%s' to '%s'", src, dst)
   177  	scpFunc := func(w io.Writer, r *bufio.Reader) error {
   178  		uploadEntries := func() error {
   179  			f, err := os.Open(src)
   180  			if err != nil {
   181  				return err
   182  			}
   183  			defer f.Close()
   184  
   185  			entries, err := f.Readdir(-1)
   186  			if err != nil {
   187  				return err
   188  			}
   189  
   190  			return scpUploadDir(src, entries, w, r)
   191  		}
   192  
   193  		if src[len(src)-1] != '/' {
   194  			log.Printf("No trailing slash, creating the source directory name")
   195  			return scpUploadDirProtocol(filepath.Base(src), w, r, uploadEntries)
   196  		} else {
   197  			// Trailing slash, so only upload the contents
   198  			return uploadEntries()
   199  		}
   200  	}
   201  
   202  	return c.scpSession("scp -rvt "+dst, scpFunc)
   203  }
   204  
   205  func (c *comm) Download(string, io.Writer) error {
   206  	panic("not implemented yet")
   207  }
   208  
   209  func (c *comm) newSession() (session *ssh.Session, err error) {
   210  	log.Println("opening new ssh session")
   211  	if c.client == nil {
   212  		err = errors.New("client not available")
   213  	} else {
   214  		session, err = c.client.NewSession()
   215  	}
   216  
   217  	if err != nil {
   218  		log.Printf("ssh session open error: '%s', attempting reconnect", err)
   219  		if err := c.reconnect(); err != nil {
   220  			return nil, err
   221  		}
   222  
   223  		return c.client.NewSession()
   224  	}
   225  
   226  	return session, nil
   227  }
   228  
   229  func (c *comm) reconnect() (err error) {
   230  	if c.conn != nil {
   231  		c.conn.Close()
   232  	}
   233  
   234  	// Set the conn and client to nil since we'll recreate it
   235  	c.conn = nil
   236  	c.client = nil
   237  
   238  	log.Printf("reconnecting to TCP connection for SSH")
   239  	c.conn, err = c.config.Connection()
   240  	if err != nil {
   241  		log.Printf("reconnection error: %s", err)
   242  		return
   243  	}
   244  
   245  	log.Printf("handshaking with SSH")
   246  	c.client, err = ssh.Client(c.conn, c.config.SSHConfig)
   247  	if err != nil {
   248  		log.Printf("handshake error: %s", err)
   249  	}
   250  
   251  	return
   252  }
   253  
   254  func (c *comm) scpSession(scpCommand string, f func(io.Writer, *bufio.Reader) error) error {
   255  	session, err := c.newSession()
   256  	if err != nil {
   257  		return err
   258  	}
   259  	defer session.Close()
   260  
   261  	// Get a pipe to stdin so that we can send data down
   262  	stdinW, err := session.StdinPipe()
   263  	if err != nil {
   264  		return err
   265  	}
   266  
   267  	// We only want to close once, so we nil w after we close it,
   268  	// and only close in the defer if it hasn't been closed already.
   269  	defer func() {
   270  		if stdinW != nil {
   271  			stdinW.Close()
   272  		}
   273  	}()
   274  
   275  	// Get a pipe to stdout so that we can get responses back
   276  	stdoutPipe, err := session.StdoutPipe()
   277  	if err != nil {
   278  		return err
   279  	}
   280  	stdoutR := bufio.NewReader(stdoutPipe)
   281  
   282  	// Set stderr to a bytes buffer
   283  	stderr := new(bytes.Buffer)
   284  	session.Stderr = stderr
   285  
   286  	// Start the sink mode on the other side
   287  	// TODO(mitchellh): There are probably issues with shell escaping the path
   288  	log.Println("Starting remote scp process: ", scpCommand)
   289  	if err := session.Start(scpCommand); err != nil {
   290  		return err
   291  	}
   292  
   293  	// Call our callback that executes in the context of SCP. We ignore
   294  	// EOF errors if they occur because it usually means that SCP prematurely
   295  	// ended on the other side.
   296  	log.Println("Started SCP session, beginning transfers...")
   297  	if err := f(stdinW, stdoutR); err != nil && err != io.EOF {
   298  		return err
   299  	}
   300  
   301  	// Close the stdin, which sends an EOF, and then set w to nil so that
   302  	// our defer func doesn't close it again since that is unsafe with
   303  	// the Go SSH package.
   304  	log.Println("SCP session complete, closing stdin pipe.")
   305  	stdinW.Close()
   306  	stdinW = nil
   307  
   308  	// Wait for the SCP connection to close, meaning it has consumed all
   309  	// our data and has completed. Or has errored.
   310  	log.Println("Waiting for SSH session to complete.")
   311  	err = session.Wait()
   312  	if err != nil {
   313  		if exitErr, ok := err.(*ssh.ExitError); ok {
   314  			// Otherwise, we have an ExitErorr, meaning we can just read
   315  			// the exit status
   316  			log.Printf("non-zero exit status: %d", exitErr.ExitStatus())
   317  
   318  			// If we exited with status 127, it means SCP isn't available.
   319  			// Return a more descriptive error for that.
   320  			if exitErr.ExitStatus() == 127 {
   321  				return errors.New(
   322  					"SCP failed to start. This usually means that SCP is not\n" +
   323  						"properly installed on the remote system.")
   324  			}
   325  		}
   326  
   327  		return err
   328  	}
   329  
   330  	log.Printf("scp stderr (length %d): %s", stderr.Len(), stderr.String())
   331  	return nil
   332  }
   333  
   334  // checkSCPStatus checks that a prior command sent to SCP completed
   335  // successfully. If it did not complete successfully, an error will
   336  // be returned.
   337  func checkSCPStatus(r *bufio.Reader) error {
   338  	code, err := r.ReadByte()
   339  	if err != nil {
   340  		return err
   341  	}
   342  
   343  	if code != 0 {
   344  		// Treat any non-zero (really 1 and 2) as fatal errors
   345  		message, _, err := r.ReadLine()
   346  		if err != nil {
   347  			return fmt.Errorf("Error reading error message: %s", err)
   348  		}
   349  
   350  		return errors.New(string(message))
   351  	}
   352  
   353  	return nil
   354  }
   355  
   356  func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader) error {
   357  	// Determine the length of the upload content by copying it
   358  	// into an in-memory buffer. Note that this means what we upload
   359  	// must fit into memory.
   360  	log.Println("Copying input data into in-memory buffer so we can get the length")
   361  	inputBuf := new(bytes.Buffer)
   362  	if _, err := io.Copy(inputBuf, src); err != nil {
   363  		return err
   364  	}
   365  
   366  	// Start the protocol
   367  	log.Println("Beginning file upload...")
   368  	fmt.Fprintln(w, "C0644", inputBuf.Len(), dst)
   369  	err := checkSCPStatus(r)
   370  	if err != nil {
   371  		return err
   372  	}
   373  
   374  	if _, err := io.Copy(w, inputBuf); err != nil {
   375  		return err
   376  	}
   377  
   378  	fmt.Fprint(w, "\x00")
   379  	err = checkSCPStatus(r)
   380  	if err != nil {
   381  		return err
   382  	}
   383  
   384  	return nil
   385  }
   386  
   387  func scpUploadDirProtocol(name string, w io.Writer, r *bufio.Reader, f func() error) error {
   388  	log.Printf("SCP: starting directory upload: %s", name)
   389  	fmt.Fprintln(w, "D0755 0", name)
   390  	err := checkSCPStatus(r)
   391  	if err != nil {
   392  		return err
   393  	}
   394  
   395  	if err := f(); err != nil {
   396  		return err
   397  	}
   398  
   399  	fmt.Fprintln(w, "E")
   400  	if err != nil {
   401  		return err
   402  	}
   403  
   404  	return nil
   405  }
   406  
   407  func scpUploadDir(root string, fs []os.FileInfo, w io.Writer, r *bufio.Reader) error {
   408  	for _, fi := range fs {
   409  		realPath := filepath.Join(root, fi.Name())
   410  
   411  		if !fi.IsDir() {
   412  			// It is a regular file, just upload it
   413  			f, err := os.Open(realPath)
   414  			if err != nil {
   415  				return err
   416  			}
   417  
   418  			err = func() error {
   419  				defer f.Close()
   420  				return scpUploadFile(fi.Name(), f, w, r)
   421  			}()
   422  
   423  			if err != nil {
   424  				return err
   425  			}
   426  
   427  			continue
   428  		}
   429  
   430  		// It is a directory, recursively upload
   431  		err := scpUploadDirProtocol(fi.Name(), w, r, func() error {
   432  			f, err := os.Open(realPath)
   433  			if err != nil {
   434  				return err
   435  			}
   436  			defer f.Close()
   437  
   438  			entries, err := f.Readdir(-1)
   439  			if err != nil {
   440  				return err
   441  			}
   442  
   443  			return scpUploadDir(realPath, entries, w, r)
   444  		})
   445  		if err != nil {
   446  			return err
   447  		}
   448  	}
   449  
   450  	return nil
   451  }