Skip to content

Commit 6aa8bf6

Browse files
committed
vmtest: add new _ensure_ssh() that will retry 3x to login
Small helper to retry ssh to avoid flakyness when a VM closes the connection too early.
1 parent b211313 commit 6aa8bf6

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

vmtest/vm.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919

2020
_non_interactive_ssh = [
2121
"-o", "UserKnownHostsFile=/dev/null",
22-
"-o" "StrictHostKeyChecking=no",
23-
"-o" "LogLevel=ERROR",
22+
"-o", "StrictHostKeyChecking=no",
23+
"-o", "LogLevel=ERROR",
2424
]
2525

2626

@@ -57,12 +57,29 @@ def _sshpass(self, password):
5757
return []
5858
return ["sshpass", "-p", password]
5959

60+
def _ensure_ssh(self, user, password="", keyfile=None):
61+
if not self.running():
62+
self.start()
63+
n_retries = 3
64+
wait_sec = 10
65+
for _ in range(n_retries):
66+
try:
67+
ret, _ = self._run("true", user, password, keyfile)
68+
if ret == 0:
69+
return
70+
except Exception as e:
71+
print(f"ssh not ready {e}")
72+
time.sleep(wait_sec)
73+
raise RuntimeError(f"no ssh after {n_retries} retries of {wait_sec}")
74+
6075
def run(self, cmd, user, password="", keyfile=None):
76+
self._ensure_ssh(user, password, keyfile)
77+
return self._run(cmd, user, password, keyfile)
78+
79+
def _run(self, cmd, user, password="", keyfile=None):
6180
"""
6281
Run a command on the VM via SSH using the provided credentials.
6382
"""
64-
if not self.running():
65-
self.start()
6683
ssh_cmd = self._sshpass(password) + [
6784
"ssh", "-p", str(self._ssh_port),
6885
] + _non_interactive_ssh
@@ -82,8 +99,7 @@ def run(self, cmd, user, password="", keyfile=None):
8299
return p.returncode, output.getvalue()
83100

84101
def scp(self, src, dst, user, password="", keyfile=None):
85-
if not self.running():
86-
self.start()
102+
self._ensure_ssh(user, password, keyfile)
87103
scp_cmd = self._sshpass(password) + [
88104
"scp", "-P", str(self._ssh_port),
89105
] + _non_interactive_ssh

0 commit comments

Comments
 (0)