Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sshdriver: Add Port Forwarding to Unix Sockets #1262

Merged
merged 1 commit into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions labgrid/driver/sshdriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,34 @@ def forward_remote_port(self, remoteport, localport):
with self._forward(forward):
yield

@Driver.check_active
@contextlib.contextmanager
def forward_unix_socket(self, unixsocket, localport=None):
"""Forward a unix socket on the target to a local port

A context manager that keeps a unix socket forwarded to a local port as
long as the context remains valid. A connection can be made to the
remote socket on the target device will be forwarded to the returned
local port on localhost

usage:
with ssh.forward_unix_socket("/run/docker.sock") as localport:
# Use localhost:localport here to connect to the socket on the
# target

returns:
localport
"""
if not self._check_keepalive():
raise ExecutionError("Keepalive no longer running")

if localport is None:
localport = get_free_port()

forward = f"-L{localport:d}:{unixsocket:s}"
with self._forward(forward):
yield localport

@Driver.check_active
@step(args=['src', 'dst'])
def scp(self, *, src, dst):
Expand Down
20 changes: 20 additions & 0 deletions tests/test_sshdriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,23 @@ def test_local_remote_forward(ssh_localhost, tmpdir):
send_socket.send(test_string.encode('utf-8'))

assert client_socket.recv(16).decode("utf-8") == test_string


@pytest.mark.sshusername
def test_unix_socket_forward(ssh_localhost, tmpdir):
p = tmpdir.join("console.sock")
test_string = "Hello World"

with ssh_localhost.forward_unix_socket(str(p)) as localport:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server_socket:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as send_socket:
server_socket.bind(str(p))
server_socket.listen(1)

send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
send_socket.connect(("127.0.0.1", localport))

client_socket, address = server_socket.accept()
send_socket.send(test_string.encode("utf-8"))

assert client_socket.recv(16).decode("utf-8") == test_string