|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + fleetEtcd "github.com/coreos/fleet/etcd" |
| 11 | + "github.com/coreos/fleet/ssh" |
| 12 | + "github.com/coreos/go-etcd/etcd" |
| 13 | + "github.com/deis/deisctl/client" |
| 14 | +) |
| 15 | + |
| 16 | +func getTunnelFlag() string { |
| 17 | + tun := client.Flags.Tunnel |
| 18 | + if tun != "" && !strings.Contains(tun, ":") { |
| 19 | + tun += ":22" |
| 20 | + } |
| 21 | + return tun |
| 22 | +} |
| 23 | + |
| 24 | +func getChecker() *ssh.HostKeyChecker { |
| 25 | + if !client.Flags.StrictHostKeyChecking { |
| 26 | + return nil |
| 27 | + } |
| 28 | + keyFile := ssh.NewHostKeyFile(client.Flags.KnownHostsFile) |
| 29 | + return ssh.NewHostKeyChecker(keyFile) |
| 30 | +} |
| 31 | + |
| 32 | +type etcdClient struct { |
| 33 | + etcd *etcd.Client |
| 34 | +} |
| 35 | + |
| 36 | +func (c *etcdClient) Get(key string) (string, error) { |
| 37 | + sort, recursive := true, false |
| 38 | + resp, err := c.etcd.Get(key, sort, recursive) |
| 39 | + if err != nil { |
| 40 | + return "", err |
| 41 | + } |
| 42 | + return resp.Node.Value, nil |
| 43 | +} |
| 44 | + |
| 45 | +func (c *etcdClient) Set(key string, value string) (string, error) { |
| 46 | + resp, err := c.etcd.Set(key, value, 0) // don't use TTLs |
| 47 | + if err != nil { |
| 48 | + return "", err |
| 49 | + } |
| 50 | + return resp.Node.Value, nil |
| 51 | +} |
| 52 | + |
| 53 | +func getEtcdClient() (*etcdClient, error) { |
| 54 | + var dial func(string, string) (net.Conn, error) |
| 55 | + tun := getTunnelFlag() |
| 56 | + if tun != "" { |
| 57 | + sshClient, err := ssh.NewSSHClient("core", tun, getChecker(), false) |
| 58 | + if err != nil { |
| 59 | + return nil, fmt.Errorf("failed initializing SSH client: %v", err) |
| 60 | + } |
| 61 | + |
| 62 | + dial = func(network, addr string) (net.Conn, error) { |
| 63 | + tcpaddr, err := net.ResolveTCPAddr(network, addr) |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + return sshClient.DialTCP(network, nil, tcpaddr) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + tlsConfig, err := fleetEtcd.ReadTLSConfigFiles(client.Flags.EtcdCAFile, |
| 72 | + client.Flags.EtcdCertFile, client.Flags.EtcdKeyFile) |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + |
| 77 | + trans := http.Transport{ |
| 78 | + Dial: dial, |
| 79 | + TLSClientConfig: tlsConfig, |
| 80 | + } |
| 81 | + |
| 82 | + timeout := time.Duration(client.Flags.RequestTimeout*1000) * time.Millisecond |
| 83 | + machines := []string{client.Flags.Endpoint} |
| 84 | + |
| 85 | + c := etcd.NewClient(machines) |
| 86 | + c.SetDialTimeout(timeout) |
| 87 | + |
| 88 | + // use custom transport with SSH tunnel capability |
| 89 | + c.SetTransport(&trans) |
| 90 | + |
| 91 | + return &etcdClient{etcd: c}, nil |
| 92 | +} |
0 commit comments