forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
86 lines (73 loc) · 2.54 KB
/
session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package ssh
import (
"golang.org/x/crypto/ssh"
"fmt"
"io"
"net"
"reflect"
"github.com/gruntwork-io/terratest/modules/collections"
"testing"
"github.com/gruntwork-io/terratest/modules/logger"
)
type SshConnectionOptions struct {
Username string
Address string
Port int
AuthMethods []ssh.AuthMethod
Command string
JumpHost *SshConnectionOptions
}
func (options *SshConnectionOptions) ConnectionString() string {
return fmt.Sprintf("%s:%d", options.Address, options.Port)
}
// A container object for all resources created by an SSH session. The reason we need this is so that we can do a
// single defer in a top-level method that calls the Cleanup method to go through and ensure all of these resources are
// released and cleaned up.
type SshSession struct {
Options *SshConnectionOptions
Client *ssh.Client
Session *ssh.Session
JumpHost *JumpHostSession
}
func (sshSession *SshSession) Cleanup(t *testing.T) {
if sshSession == nil {
return
}
// Closing the session may result in an EOF error if it's already closed (e.g. due to hitting CTRL + D), so
// don't report those errors, as there is nothing actually wrong in that case.
Close(t, sshSession.Session, io.EOF.Error())
Close(t, sshSession.Client)
sshSession.JumpHost.Cleanup(t)
}
type JumpHostSession struct {
JumpHostClient *ssh.Client
HostVirtualConnection net.Conn
HostConnection ssh.Conn
}
func (jumpHost *JumpHostSession) Cleanup(t *testing.T) {
if jumpHost == nil {
return
}
// Closing a connection may result in an EOF error if it's already closed (e.g. due to hitting CTRL + D), so
// don't report those errors, as there is nothing actually wrong in that case.
Close(t, jumpHost.HostConnection, io.EOF.Error())
Close(t, jumpHost.HostVirtualConnection, io.EOF.Error())
Close(t, jumpHost.JumpHostClient)
}
type Closeable interface {
Close() error
}
func Close(t *testing.T, closeable Closeable, ignoreErrors ...string) {
if interfaceIsNil(closeable) {
return
}
if err := closeable.Close(); err != nil && !collections.ListContains(ignoreErrors, err.Error()) {
logger.Logf(t, "Error closing %s: %s", closeable, err.Error())
}
}
// Go is a shitty language. Checking an interface directly against nil does not work, and if you don't know the exact
// types the interface may be ahead of time, the only way to know if you're dealing with nil is to use reflection.
// http://stackoverflow.com/questions/13476349/check-for-nil-and-nil-interface-in-go
func interfaceIsNil(i interface{}) bool {
return i == nil || reflect.ValueOf(i).IsNil()
}