Compare commits

...

9 Commits

28 changed files with 426 additions and 171 deletions

View File

@ -17,6 +17,8 @@ const build_image_repo = 'vieter-build'
// makepkg with. The base image should be some Linux distribution that uses
// Pacman as its package manager.
pub fn create_build_image(base_image string) ?string {
mut dd := docker.new_conn() ?
commands := [
// Update repos & install required packages
'pacman -Syu --needed --noconfirm base-devel git'
@ -48,12 +50,14 @@ pub fn create_build_image(base_image string) ?string {
// We pull the provided image
docker.pull_image(image_name, image_tag)?
id := docker.create_container(c) ?
docker.start_container(id) ?
id := dd.create_container(c)?.id
/* id := docker.create_container(c)? */
dd.start_container(id)?
// This loop waits until the container has stopped, so we can remove it after
for {
data := docker.inspect_container(id) ?
println('wot')
data := dd.inspect_container(id)?
if !data.state.running {
break
@ -68,7 +72,7 @@ pub fn create_build_image(base_image string) ?string {
// conflicts.
tag := time.sys_mono_now().str()
image := docker.create_image_from_container(id, 'vieter-build', tag)?
docker.remove_container(id) ?
dd.remove_container(id)?
return image.id
}

View File

@ -1 +1,56 @@
module console
import arrays
import strings
// pretty_table converts a list of string data into a pretty table. Many thanks
// to @hungrybluedev in the Vlang Discord for providing this code!
// https://ptb.discord.com/channels/592103645835821068/592106336838352923/970278787143045192
pub fn pretty_table(header []string, data [][]string) ?string {
column_count := header.len
mut column_widths := []int{len: column_count, init: header[it].len}
for values in data {
for col, value in values {
if column_widths[col] < value.len {
column_widths[col] = value.len
}
}
}
single_line_length := arrays.sum(column_widths)? + (column_count + 1) * 3 - 4
horizontal_line := '+' + strings.repeat(`-`, single_line_length) + '+'
mut buffer := strings.new_builder(data.len * single_line_length)
buffer.writeln(horizontal_line)
buffer.write_string('| ')
for col, head in header {
if col != 0 {
buffer.write_string(' | ')
}
buffer.write_string(head)
buffer.write_string(strings.repeat(` `, column_widths[col] - head.len))
}
buffer.writeln(' |')
buffer.writeln(horizontal_line)
for values in data {
buffer.write_string('| ')
for col, value in values {
if col != 0 {
buffer.write_string(' | ')
}
buffer.write_string(value)
buffer.write_string(strings.repeat(` `, column_widths[col] - value.len))
}
buffer.writeln(' |')
}
buffer.writeln(horizontal_line)
return buffer.str()
}

View File

@ -4,6 +4,7 @@ import cli
import env
import cron.expression { parse_expression }
import client
import console
struct Config {
address string [required]
@ -122,10 +123,9 @@ pub fn cmd() cli.Command {
fn list(conf Config) ? {
c := client.new(conf.address, conf.api_key)
repos := c.get_git_repos()?
data := repos.map([it.id.str(), it.url, it.branch, it.repo])
for repo in repos {
println('$repo.id\t$repo.url\t$repo.branch\t$repo.repo')
}
println(console.pretty_table(['id', 'url', 'branch', 'repo'], data)?)
}
// add adds a new repository to the server's list.

View File

@ -4,6 +4,7 @@ import cli
import env
import client
import db
import console
struct Config {
address string [required]
@ -66,10 +67,11 @@ pub fn cmd() cli.Command {
}
// print_log_list prints a list of logs.
fn print_log_list(logs []db.BuildLog) {
for log in logs {
println('$log.id\t$log.start_time\t$log.exit_code')
}
fn print_log_list(logs []db.BuildLog) ? {
data := logs.map([it.id.str(), it.repo_id.str(), it.start_time.str(),
it.exit_code.str()])
println(console.pretty_table(['id', 'repo', 'start time', 'exit code'], data)?)
}
// list prints a list of all build logs.
@ -77,7 +79,7 @@ fn list(conf Config) ? {
c := client.new(conf.address, conf.api_key)
logs := c.get_build_logs()?.data
print_log_list(logs)
print_log_list(logs)?
}
// list prints a list of all build logs for a given repo.
@ -85,7 +87,7 @@ fn list_for_repo(conf Config, repo_id int) ? {
c := client.new(conf.address, conf.api_key)
logs := c.get_build_logs_for_repo(repo_id)?.data
print_log_list(logs)
print_log_list(logs)?
}
// info print the detailed info for a given build log.

View File

@ -3,19 +3,33 @@ module docker
import json
import net.urllib
import time
import net.http
struct DockerError {
message string
}
struct Container {
id string [json: Id]
names []string [json: Names]
}
// containers returns a list of all currently running containers
pub fn containers() ?[]Container {
res := request('GET', urllib.parse('/v1.41/containers/json') ?) ?
pub fn (mut d DockerDaemon) containers() ?[]Container {
d.send_request('GET', urllib.parse('/v1.41/containers/json')?)?
head, res := d.read_response()?
return json.decode([]Container, res.text) or {}
if head.status_code != 200 {
data := json.decode(DockerError, res)?
return error(data.message)
}
data := json.decode([]Container, res)?
return data
}
[params]
pub struct NewContainer {
image string [json: Image]
entrypoint []string [json: Entrypoint]
@ -26,7 +40,35 @@ pub struct NewContainer {
}
struct CreatedContainer {
pub:
id string [json: Id]
warnings []string [json: Warnings]
}
pub fn (mut d DockerDaemon) create_container(c NewContainer) ?CreatedContainer {
d.send_request_with_json('POST', urllib.parse('/v1.41/containers/create')?, c)?
head, res := d.read_response()?
if head.status_code != 201 {
data := json.decode(DockerError, res)?
return error(data.message)
}
data := json.decode(CreatedContainer, res)?
return data
}
pub fn (mut d DockerDaemon) start_container(id string) ? {
d.send_request('POST', urllib.parse('/v1.41/containers/$id/start')?)?
head, body := d.read_response() ?
if head.status_code != 204 {
data := json.decode(DockerError, body)?
return error(data.message)
}
}
// create_container creates a container defined by the given configuration. If
@ -67,6 +109,27 @@ pub mut:
end_time time.Time [skip]
}
pub fn (mut d DockerDaemon) inspect_container(id string) ?ContainerInspect {
d.send_request('GET', urllib.parse('/v1.41/containers/$id/json')?)?
head, body := d.read_response()?
if head.status_code != 200 {
data := json.decode(DockerError, body)?
return error(data.message)
}
mut data := json.decode(ContainerInspect, body)?
data.state.start_time = time.parse_rfc3339(data.state.start_time_str)?
if data.state.status == 'exited' {
data.state.end_time = time.parse_rfc3339(data.state.end_time_str)?
}
return data
}
// inspect_container returns the result of inspecting a container with a given
// ID.
pub fn inspect_container(id string) ?ContainerInspect {
@ -87,6 +150,17 @@ pub fn inspect_container(id string) ?ContainerInspect {
return data
}
pub fn (mut d DockerDaemon) remove_container(id string) ? {
d.send_request('DELETE', urllib.parse('/v1.41/containers/$id')?)?
head, body := d.read_response() ?
if head.status_code != 204 {
data := json.decode(DockerError, body)?
return error(data.message)
}
}
// remove_container removes a container with a given ID.
pub fn remove_container(id string) ?bool {
res := request('DELETE', urllib.parse('/v1.41/containers/$id')?)?

View File

@ -5,16 +5,12 @@ 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 {
// Open a connection to the socket
mut s := unix.connect_stream(docker.socket) or {
return error('Failed to connect to socket ${docker.socket}.')
mut s := unix.connect_stream(socket) or {
return error('Failed to connect to socket ${socket}.')
}
defer {
@ -25,19 +21,19 @@ fn send(req &string) ?http.Response {
}
// Write the request to the socket
s.write_string(req) or { return error('Failed to write request to socket ${docker.socket}.') }
s.write_string(req) or { return error('Failed to write request to socket ${socket}.') }
s.wait_for_write()?
mut c := 0
mut buf := []u8{len: docker.buf_len}
mut buf := []u8{len: buf_len}
mut res := []u8{}
for {
c = s.read(mut buf) or { return error('Failed to read data from socket ${docker.socket}.') }
c = s.read(mut buf) or { return error('Failed to read data from socket ${socket}.') }
res << buf[..c]
if c < docker.buf_len {
if c < buf_len {
break
}
}
@ -45,7 +41,7 @@ fn send(req &string) ?http.Response {
// After reading the first part of the response, we parse it into an HTTP
// response. If it isn't chunked, we return early with the data.
parsed := http.parse_response(res.bytestr()) or {
return error('Failed to parse HTTP response from socket ${docker.socket}.')
return error('Failed to parse HTTP response from socket ${socket}.')
}
if parsed.header.get(http.CommonHeader.transfer_encoding) or { '' } != 'chunked' {
@ -59,12 +55,10 @@ fn send(req &string) ?http.Response {
s.wait_for_write()?
for {
c = s.read(mut buf) or {
return error('Failed to read data from socket ${docker.socket}.')
}
c = s.read(mut buf) or { return error('Failed to read data from socket ${socket}.') }
res << buf[..c]
if c < docker.buf_len {
if c < buf_len {
break
}
}

116
src/docker/socket.v 100644
View File

@ -0,0 +1,116 @@
module docker
import net.unix
import io
import net.http
import strings
import net.urllib
import json
const (
socket = '/var/run/docker.sock'
buf_len = 10 * 1024
http_separator = [u8(`\r`), `\n`, `\r`, `\n`]
)
pub struct DockerDaemon {
mut:
socket &unix.StreamConn
reader &io.BufferedReader
}
pub fn new_conn() ?&DockerDaemon {
s := unix.connect_stream(docker.socket)?
d := &DockerDaemon{
socket: s
reader: io.new_buffered_reader(reader: s)
}
return d
}
pub fn (mut d DockerDaemon) send_request(method string, url urllib.URL) ? {
req := '$method $url.request_uri() HTTP/1.1\nHost: localhost\n\n'
d.socket.write_string(req)?
}
pub fn (mut d DockerDaemon) send_request_with_body(method string, url urllib.URL, content_type string, body string) ? {
req := '$method $url.request_uri() HTTP/1.1\nHost: localhost\nContent-Type: $content_type\nContent-Length: $body.len\n\n$body\n\n'
d.socket.write_string(req)?
}
pub fn (mut d DockerDaemon) send_request_with_json<T>(method string, url urllib.URL, data &T) ? {
body := json.encode(data)
return d.send_request_with_body(method, url, 'application/json', body)
}
// read_response_head consumes the socket's contents until it encounters
// '\r\n\r\n', after which it parses the response as an HTTP response.
// Importantly, this function never consumes past the HTTP separator, so the
// body can be read fully later on.
pub fn (mut d DockerDaemon) read_response_head() ?http.Response {
mut c := 0
mut buf := []u8{len: 4}
mut res := []u8{}
for {
c = d.reader.read(mut buf)?
res << buf[..c]
mut i := 0
mut match_len := 0
for i + match_len < c {
if buf[i + match_len] == docker.http_separator[match_len] {
match_len += 1
} else {
i += match_len + 1
match_len = 0
}
}
if match_len == 4 {
break
} else if match_len > 0 {
mut buf2 := []u8{len: 4 - match_len}
c2 := d.reader.read(mut buf2)?
res << buf2[..c2]
if buf2 == docker.http_separator[match_len..] {
break
}
}
}
return http.parse_response(res.bytestr())
}
pub fn (mut d DockerDaemon) read_response_body(length int) ?string {
if length == 0 {
return ''
}
mut buf := []u8{len: docker.buf_len}
mut c := 0
mut builder := strings.new_builder(docker.buf_len)
for builder.len < length {
c = d.reader.read(mut buf) or { break }
builder.write(buf[..c])?
}
return builder.str()
}
pub fn (mut d DockerDaemon) read_response() ?(http.Response, string) {
head := d.read_response_head()?
content_length := head.header.get(http.CommonHeader.content_length)?.int()
res := d.read_response_body(content_length)?
return head, res
}

View File

@ -0,0 +1,9 @@
module docker
import io
struct ChunkedResponseStream {
reader io.Reader
}

View File

@ -7,6 +7,7 @@ import build
import console.git
import console.logs
import cron
import docker
fn main() {
mut app := cli.Command{
@ -31,7 +32,7 @@ fn main() {
logs.cmd(),
]
}
app.setup()
app.parse(os.args)
return
}