Initial SSH transfer commit.

pull/61/head
Dan Lorenc 2016-05-10 12:59:16 -07:00
parent 46fcb77943
commit 92d0c94d7b
4 changed files with 356 additions and 1 deletions

View File

@ -0,0 +1,114 @@
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sshutil
import (
"bufio"
"fmt"
"io"
"os"
"github.com/docker/machine/libmachine/drivers"
machinessh "github.com/docker/machine/libmachine/ssh"
"golang.org/x/crypto/ssh"
)
// SSHSession provides methods for running commands on a host.
type SSHSession interface {
Close() error
StdinPipe() (io.WriteCloser, error)
Start(cmd string) error
Wait() error
}
// NewSSHSession returns an SSHSession object for running commands.
func NewSSHSession(d drivers.Driver) (SSHSession, error) {
h, err := newSSHHost(d)
if err != nil {
return nil, err
}
auth := &machinessh.Auth{}
if h.SSHKeyPath != "" {
auth.Keys = []string{h.SSHKeyPath}
}
config, err := machinessh.NewNativeConfig(h.Username, auth)
if err != nil {
return nil, err
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", h.IP, h.Port), &config)
if err != nil {
return nil, err
}
session, err := client.NewSession()
if err != nil {
return nil, err
}
return session, nil
}
// Transfer uses an SSH session to copy a file to the remote machine.
func Transfer(localpath, remotepath string, r SSHSession) error {
f, err := os.Open(localpath)
if err != nil {
return err
}
reader := bufio.NewReader(f)
cmd := fmt.Sprintf("cat > %s", remotepath)
stdin, err := r.StdinPipe()
if err != nil {
return err
}
if err := r.Start(cmd); err != nil {
return err
}
_, err = io.Copy(stdin, reader)
stdin.Close()
if err != nil {
return err
}
return r.Wait()
}
type sshHost struct {
IP string
Port int
SSHKeyPath string
Username string
}
func newSSHHost(d drivers.Driver) (*sshHost, error) {
ip, err := d.GetSSHHostname()
if err != nil {
return nil, err
}
port, err := d.GetSSHPort()
if err != nil {
return nil, err
}
return &sshHost{
IP: ip,
Port: port,
SSHKeyPath: d.GetSSHKeyPath(),
Username: d.GetSSHUsername(),
}, nil
}

View File

@ -0,0 +1,130 @@
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sshutil
import (
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"testing"
"github.com/docker/machine/libmachine/drivers"
"k8s.io/minikube/pkg/minikube/tests"
)
func TestNewSSHSession(t *testing.T) {
s, _ := tests.NewSSHServer()
port, err := s.Start()
if err != nil {
t.Fatalf("Error starting ssh server: %s", err)
}
d := &tests.MockDriver{
Port: port,
BaseDriver: drivers.BaseDriver{
IPAddress: "127.0.0.1",
SSHKeyPath: "",
},
}
session, err := NewSSHSession(d)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
if !s.Connected {
t.Fatalf("Error!")
}
cmd := "foo"
session.Start(cmd)
session.Wait()
if !strings.Contains(s.Commands[0], cmd) {
t.Fatalf("Expected command: %s, got %s", cmd, s.Commands[0])
}
}
func TestNewSSHHost(t *testing.T) {
sshKeyPath := "mypath"
ip := "localhost"
user := "myuser"
d := tests.MockDriver{
BaseDriver: drivers.BaseDriver{
IPAddress: ip,
SSHUser: user,
SSHKeyPath: sshKeyPath,
},
}
h, err := newSSHHost(&d)
if err != nil {
t.Fatalf("Unexpected error creating host: %s", err)
}
if h.SSHKeyPath != sshKeyPath {
t.Fatalf("%s != %s", h.SSHKeyPath, sshKeyPath)
}
if h.Username != user {
t.Fatalf("%s != %s", h.Username, user)
}
if h.IP != ip {
t.Fatalf("%s != %s", h.IP, ip)
}
}
func TestNewSSHHostError(t *testing.T) {
d := tests.MockDriver{HostError: true}
_, err := newSSHHost(&d)
if err == nil {
t.Fatal("Expected error creating host, got nil")
}
}
func TestTransfer(t *testing.T) {
s, _ := tests.NewSSHServer()
port, err := s.Start()
if err != nil {
t.Fatalf("Error starting ssh server: %s", err)
}
d := &tests.MockDriver{
Port: port,
BaseDriver: drivers.BaseDriver{
IPAddress: "127.0.0.1",
SSHKeyPath: "",
},
}
session, err := NewSSHSession(d)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
tempDir := tests.MakeTempDir()
defer os.RemoveAll(tempDir)
src := path.Join(tempDir, "foo")
dest := "bar"
ioutil.WriteFile(src, []byte("testcontents"), 0644)
if err := Transfer(src, dest, session); err != nil {
t.Fatalf("Unexpected error: %s", err)
}
cmd := fmt.Sprintf("cat > %s", dest)
if !strings.Contains(s.Commands[0], cmd) {
t.Fatalf("Expected command: %s, got %s", cmd, s.Commands[0])
}
}

View File

@ -29,6 +29,8 @@ type MockDriver struct {
drivers.BaseDriver
CurrentState state.State
RemoveError bool
HostError bool
Port int
}
// Create creates a MockDriver instance
@ -37,14 +39,30 @@ func (driver *MockDriver) Create() error {
return nil
}
func (driver *MockDriver) GetIP() (string, error) {
return driver.BaseDriver.GetIP()
}
// GetCreateFlags returns the flags used to create a MockDriver
func (driver *MockDriver) GetCreateFlags() []mcnflag.Flag {
return []mcnflag.Flag{}
}
func (driver *MockDriver) GetSSHPort() (int, error) {
return driver.Port, nil
}
// GetSSHHostname returns the hostname for SSH
func (driver *MockDriver) GetSSHHostname() (string, error) {
return "", nil
if driver.HostError {
return "", fmt.Errorf("Error getting host!")
}
return "localhost", nil
}
// GetSSHHostname returns the hostname for SSH
func (driver *MockDriver) GetSSHKeyPath() string {
return driver.BaseDriver.SSHKeyPath
}
// GetState returns the state of the driver

View File

@ -0,0 +1,93 @@
package tests
import (
"crypto/rand"
"crypto/rsa"
"io"
"io/ioutil"
"net"
"strconv"
"golang.org/x/crypto/ssh"
)
// SSHServer provides a mock SSH Server for testing. Commands are stored, not executed.
type SSHServer struct {
Config *ssh.ServerConfig
// Commands stores the raw commands executed against the server.
Commands []string
Connected bool
}
// NewSSHServer returns a NewSSHServer instance, ready for use.
func NewSSHServer() (*SSHServer, error) {
s := &SSHServer{}
s.Config = &ssh.ServerConfig{
NoClientAuth: true,
}
private, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
return nil, err
}
signer, err := ssh.NewSignerFromKey(private)
if err != nil {
return nil, err
}
s.Config.AddHostKey(signer)
return s, nil
}
// Start starts the mock SSH Server, and returns the port it's listening on.
func (s *SSHServer) Start() (int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
// Main loop, listen for connections and store the commands.
go func() {
for {
nConn, err := listener.Accept()
if err != nil {
return
}
_, chans, reqs, err := ssh.NewServerConn(nConn, s.Config)
if err != nil {
return
}
// The incoming Request channel must be serviced.
go ssh.DiscardRequests(reqs)
// Service the incoming Channel channel.
for newChannel := range chans {
channel, requests, err := newChannel.Accept()
s.Connected = true
if err != nil {
return
}
req := <-requests
req.Reply(true, nil)
s.Commands = append(s.Commands, string(req.Payload))
channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
// Discard anything that comes in over stdin.
io.Copy(ioutil.Discard, channel)
channel.Close()
}
}
}()
// Parse and return the port.
_, p, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
return 0, err
}
port, err := strconv.Atoi(p)
if err != nil {
return 0, err
}
return port, nil
}