Created
May 22, 2018 19:37
-
-
Save baude/3641de4cc3e0ee7ef2ed0a13b72c933a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket, argparse | |
import select, sys, os, tty, atexit, termios, signal, shutil | |
hasVarlink = False | |
try: | |
import fiibar | |
from varlink import (Client, VarlinkError) | |
hasVarlink = True | |
except ImportError: | |
pass | |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) | |
address = "unix:/run/io.projectatomic.podman" | |
# stdin 1 | |
# stdout 2 | |
# stderr 3 | |
parser = argparse.ArgumentParser() | |
parser.add_argument('container', help='container name or id') | |
args = parser.parse_args() | |
socket_path = "" | |
control_socket_path = "" | |
if hasVarlink: | |
with Client(address=address) as client: | |
podman = client.open('io.projectatomic.podman') | |
try: | |
response = podman.GetAttachSockets(args.container) | |
except VarlinkError as e: | |
sys.exit(e.error()) | |
socket_path = response["sockets"]["io_socket"] | |
control_socket_path = response["sockets"]["control_socket"] | |
else: | |
sockets_dir = os.path.join("/var/run/libpod/socket/", args.container) | |
socket_path = os.path.join(sockets_dir, "attach") | |
control_socket_path = os.path.join(sockets_dir, "ctl") | |
control_socket = open(control_socket_path, 'w') | |
def reset_fd(my_fd, old_settings): | |
termios.tcsetattr(my_fd, termios.TCSADRAIN, old_settings) | |
os.close(my_fd) | |
control_socket.close() | |
def error_print(*args, **kwargs): | |
print(*args, file=sys.stderr, **kwargs) | |
def resize_handler(signum, frame): | |
# "%d %d %d\n", 1, size.Height, size.Width) | |
term_size = shutil.get_terminal_size() | |
control_socket.write("{} {} {}\n".format(1, term_size.lines, term_size.columns)) | |
control_socket.flush() | |
signal.signal(signal.SIGWINCH, resize_handler) | |
sock.connect(socket_path) | |
stdin = os.open("/dev/stdin", os.O_RDWR) | |
old_settings = termios.tcgetattr(stdin) | |
atexit.register(reset_fd, stdin, old_settings) | |
tty.setraw(stdin) | |
inputs = [sock, stdin] | |
outputs = [] | |
while inputs: | |
try: | |
readable, writable, exceptional = select.select(inputs, outputs, inputs) | |
for r in readable: | |
if isinstance(r, socket.socket): | |
data = r.recv(1024) | |
os.write(2, data[1:]) | |
if isinstance(r, int): | |
data = os.read(stdin, 1024) | |
if 29 in data: # Bail on ctrl-[ | |
sys.exit(0) | |
sock.send(data) | |
except BrokenPipeError: | |
error_print("socket quit on container end") | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment