Skip to content

Commit fa9abc1

Browse files
committed
fix: lazy SSH connection to host in testdevice
Previously, newHost dialed SSH immediately at device initialization, causing failures when the host OS hadn't finished booting yet or when running BMC-only suites that don't need host access. Now the SSH connection is established on first use via ExecuteCommandLine. Signed-off-by: llogen <christoph.lange@blindspot.software>
1 parent 1477792 commit fa9abc1

File tree

1 file changed

+37
-14
lines changed

1 file changed

+37
-14
lines changed

pkg/testdevice/host.go

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@ package testdevice
22

33
import (
44
"fmt"
5+
"log"
56
"os"
67

78
"github.com/9elements/bmc-test-go/pkg/configuration"
89
"golang.org/x/crypto/ssh"
910
)
1011

1112
type Host struct {
12-
Name string
13-
RemoteConn
13+
Name string
14+
hostport string
15+
sshConfig *ssh.ClientConfig
16+
remoteConn *RemoteConn
1417
}
1518

1619
func newHost(sshPrivKeyPath string, hostCfg configuration.Host) (*Host, error) {
@@ -38,25 +41,45 @@ func newHost(sshPrivKeyPath string, hostCfg configuration.Host) (*Host, error) {
3841
}
3942
}
4043

41-
hostport := fmt.Sprintf("%s:%s", hostCfg.IP, hostCfg.SSHPort)
42-
client, err := ssh.Dial("tcp", hostport, sshConfig)
44+
return &Host{
45+
Name: hostCfg.Name,
46+
hostport: fmt.Sprintf("%s:%s", hostCfg.IP, hostCfg.SSHPort),
47+
sshConfig: sshConfig,
48+
}, nil
49+
}
50+
51+
func (h *Host) connect() error {
52+
if h.remoteConn != nil {
53+
return nil
54+
}
55+
client, err := ssh.Dial("tcp", h.hostport, h.sshConfig)
4356
if err != nil {
44-
return nil, err
57+
return err
4558
}
46-
47-
con := RemoteConn{
48-
IP: hostCfg.IP,
49-
User: hostCfg.Username,
50-
Password: "",
51-
client: client,
59+
h.remoteConn = &RemoteConn{
60+
IP: h.hostport,
61+
User: h.sshConfig.User,
62+
client: client,
5263
}
53-
return &Host{Name: hostCfg.Name, RemoteConn: con}, nil
64+
return nil
5465
}
5566

5667
func (h *Host) Close() error {
57-
return h.RemoteConn.Close()
68+
if h.remoteConn == nil {
69+
return nil
70+
}
71+
return h.remoteConn.Close()
5872
}
5973

6074
func (h *Host) ExecuteCommandLine(cmd string, args ...string) ([]byte, error) {
61-
return h.RemoteConn.ExecuteCmdline(cmd, args...)
75+
if err := h.connect(); err != nil {
76+
return nil, err
77+
}
78+
defer func() {
79+
if err := h.remoteConn.Close(); err != nil {
80+
log.Print(err)
81+
}
82+
h.remoteConn = nil
83+
}()
84+
return h.remoteConn.ExecuteCmdline(cmd, args...)
6285
}

0 commit comments

Comments
 (0)