1
0
mirror of https://github.com/rancher/rke.git synced 2025-05-04 06:16:48 +00:00
rke/hosts/dialer.go

89 lines
2.1 KiB
Go
Raw Normal View History

2017-10-29 09:45:21 +00:00
package hosts
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"github.com/docker/docker/client"
2017-11-13 21:28:38 +00:00
"github.com/sirupsen/logrus"
2017-10-29 09:45:21 +00:00
"golang.org/x/crypto/ssh"
)
type dialer struct {
2017-11-17 21:33:07 +00:00
host *Host
signer ssh.Signer
2017-10-29 09:45:21 +00:00
}
const (
DockerAPIVersion = "1.24"
)
func (d *dialer) Dial(network, addr string) (net.Conn, error) {
sshAddr := d.host.IP + ":22"
// Build SSH client configuration
2017-11-17 21:33:07 +00:00
cfg, err := makeSSHConfig(d.host.User, d.signer)
2017-10-29 09:45:21 +00:00
if err != nil {
return nil, fmt.Errorf("Error configuring SSH: %v", err)
2017-10-29 09:45:21 +00:00
}
// Establish connection with SSH server
conn, err := ssh.Dial("tcp", sshAddr, cfg)
if err != nil {
return nil, fmt.Errorf("Error establishing SSH connection: %v", err)
2017-10-29 09:45:21 +00:00
}
if len(d.host.DockerSocket) == 0 {
d.host.DockerSocket = "/var/run/docker.sock"
}
remote, err := conn.Dial("unix", d.host.DockerSocket)
if err != nil {
return nil, fmt.Errorf("Error connecting to Docker socket on host [%s]: %v", d.host.AdvertisedHostname, err)
2017-10-29 09:45:21 +00:00
}
return remote, err
}
2017-11-17 21:33:07 +00:00
func (h *Host) TunnelUp(signer ssh.Signer) error {
2017-11-14 18:11:21 +00:00
logrus.Infof("[ssh] Start tunnel for host [%s]", h.AdvertisedHostname)
2017-10-29 09:45:21 +00:00
dialer := &dialer{
2017-11-17 21:33:07 +00:00
host: h,
signer: signer,
2017-10-29 09:45:21 +00:00
}
httpClient := &http.Client{
Transport: &http.Transport{
Dial: dialer.Dial,
},
}
// set Docker client
var err error
2017-11-14 18:11:21 +00:00
logrus.Debugf("Connecting to Docker API for host [%s]", h.AdvertisedHostname)
2017-10-29 09:45:21 +00:00
h.DClient, err = client.NewClient("unix:///var/run/docker.sock", DockerAPIVersion, httpClient, nil)
if err != nil {
2017-11-14 18:11:21 +00:00
return fmt.Errorf("Can't connect to Docker for host [%s]: %v", h.AdvertisedHostname, err)
2017-10-29 09:45:21 +00:00
}
return nil
}
2017-11-17 21:33:07 +00:00
func ParsePrivateKey(keyPath string) (ssh.Signer, error) {
2017-10-29 09:45:21 +00:00
buff, _ := ioutil.ReadFile(keyPath)
return ssh.ParsePrivateKey(buff)
}
2017-11-17 21:33:07 +00:00
func ParsePrivateKeyWithPassPhrase(keyPath string, passphrase []byte) (ssh.Signer, error) {
buff, _ := ioutil.ReadFile(keyPath)
return ssh.ParsePrivateKeyWithPassphrase(buff, passphrase)
}
2017-10-29 09:45:21 +00:00
2017-11-17 21:33:07 +00:00
func makeSSHConfig(user string, signer ssh.Signer) (*ssh.ClientConfig, error) {
2017-10-29 09:45:21 +00:00
config := ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
2017-11-17 21:33:07 +00:00
ssh.PublicKeys(signer),
2017-10-29 09:45:21 +00:00
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
return &config, nil
}