From 473c7ec06b10735b82959a50df7bb470d12ded7a Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Wed, 11 May 2022 10:03:43 +0200 Subject: [PATCH] feat(docker): start of new socket implementation --- src/docker/docker.v | 4 ---- src/docker/socket.v | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 src/docker/socket.v diff --git a/src/docker/docker.v b/src/docker/docker.v index 305e825..ce01e7e 100644 --- a/src/docker/docker.v +++ b/src/docker/docker.v @@ -5,10 +5,6 @@ import net.urllib import net.http import json -const socket = '/var/run/docker.sock' - -const buf_len = 1024 - // send writes a request to the Docker socket, waits for a response & returns // it. fn send(req &string) ?http.Response { diff --git a/src/docker/socket.v b/src/docker/socket.v new file mode 100644 index 0000000..3a72f14 --- /dev/null +++ b/src/docker/socket.v @@ -0,0 +1,47 @@ +module docker + +import net.unix +import io +import net.http + +const socket = '/var/run/docker.sock' + +const buf_len = 10 * 1024 + +pub struct DockerDaemon { +mut: + socket &unix.StreamConn + reader &io.BufferedReader +} + +pub fn new_conn() ?DockerDaemon { + s := unix.connect_stream(socket) ? + + d := DockerDaemon{socket: s, reader: io.new_buffered_reader(reader: s)} + + return d +} + +fn (mut d DockerDaemon) send_request(req &string) ? { + d.socket.write_string(req) ? + d.socket.wait_for_write() ? +} + +// read_response_head consumes the socket's contents until it encounters +// '\n\n', after which it parses the response as an HTTP response. +fn (mut d DockerDaemon) read_response_head() ?http.Response { + mut c := 0 + mut buf := [buf_len]u8{len: docker.buf_len} + mut res := []u8{} + + for { + c = d.socket.read(mut buf) ? + res << buf[..c] + + if res#[-2..] == [u8(`\n`), `\n`] { + break + } + } + + return http.parse_response(res.bytestr()) +}