From aea1ffa9bf186dd0fc826ee28425afc453dcc360 Mon Sep 17 00:00:00 2001 From: Chandarith Chea <45872539+chandarith-chea@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:08:31 +0700 Subject: [PATCH 1/2] Containers list follows Dockiva Engine's own events The core watched `docker events` on the docker CLI's current context, so with Dockiva Engine selected it heard another daemon (OrbStack here) and the app never refreshed for containers started outside it, such as CI runner containers. With Dockiva Engine selected, the core now streams the engine's GET /events over engine.sock, reconnects when the engine restarts, and asks for one refresh on each (re)connect for events missed meanwhile. Other runtimes keep `docker events`. The watch switches when the user selects another runtime. --- docker_platform.go | 128 +++++++++++++++------------------- runtime_vmfree.go | 60 +++++++++++++--- runtime_vmfree_events_test.go | 50 +++++++++++++ 3 files changed, 157 insertions(+), 81 deletions(-) create mode 100644 runtime_vmfree_events_test.go diff --git a/docker_platform.go b/docker_platform.go index 766dfaa..0e2d3f0 100644 --- a/docker_platform.go +++ b/docker_platform.go @@ -594,85 +594,73 @@ func (s *DockerService) ServiceStartup( return nil } +// watchDockerEvents turns the active runtime's events into dockerChangedEvent, so +// the app refreshes when containers change outside it (docker run, CI runners). +// Dockiva Engine streams its own /events; other runtimes use the docker CLI's +// current context. The watch follows the runtime the user selects. func (s *DockerService) watchDockerEvents(ctx context.Context) { - for { - if ctx.Err() != nil { - return - } - - dockerPath, err := dockerCLIPath() - if err != nil { - if !sleepContext(ctx, 3*time.Second) { - return - } - continue - } - - cmd := exec.CommandContext( - ctx, - dockerPath, - "events", - "--format", - "{{json .}}", - ) - - stdout, err := cmd.StdoutPipe() - if err != nil { - if !sleepContext(ctx, 2*time.Second) { - return - } - continue - } - - if err := cmd.Start(); err != nil { - if !sleepContext(ctx, 2*time.Second) { - return - } - continue - } - - scanner := bufio.NewScanner(stdout) - scanner.Buffer(make([]byte, 64*1024), 1024*1024) - - for scanner.Scan() { - if ctx.Err() != nil { - _ = cmd.Process.Kill() - _ = cmd.Wait() - return - } - - line := scanner.Bytes() - - var raw struct { - Type string `json:"Type"` - Action string `json:"Action"` - ID string `json:"id"` - Time int64 `json:"time"` - } - - if err := json.Unmarshal(line, &raw); err != nil { - continue + for ctx.Err() == nil { + engine, isEngine := s.currentRuntime().(*vmfreeRuntime) + watch, stop := context.WithCancel(ctx) + go func() { + for sleepContext(watch, 2*time.Second) { + if _, now := s.currentRuntime().(*vmfreeRuntime); now != isEngine { + stop() + } } - - emitEvent( - dockerChangedEvent, - DockerEventNotice{ - Type: raw.Type, - Action: raw.Action, - ID: raw.ID, - Time: raw.Time, - }, - ) + }() + if isEngine { + _ = engine.streamEvents(watch, func(line []byte) { + emitDockerEventLine(line) + }, func() { + // Events missed while disconnected: refresh once on (re)connect. + emitEvent(dockerChangedEvent, DockerEventNotice{Type: "engine", Action: "connected"}) + }) + } else { + watchDockerCLIEvents(watch) } - - _ = cmd.Wait() - + stop() if !sleepContext(ctx, 1500*time.Millisecond) { return } } } +// watchDockerCLIEvents runs one `docker events` session until it ends or ctx is done. +func watchDockerCLIEvents(ctx context.Context) { + dockerPath, err := dockerCLIPath() + if err != nil { + return + } + cmd := exec.CommandContext(ctx, dockerPath, "events", "--format", "{{json .}}") + stdout, err := cmd.StdoutPipe() + if err != nil { + return + } + if err := cmd.Start(); err != nil { + return + } + scanner := bufio.NewScanner(stdout) + scanner.Buffer(make([]byte, 64*1024), 1024*1024) + for scanner.Scan() { + emitDockerEventLine(scanner.Bytes()) + } + _ = cmd.Wait() +} + +func emitDockerEventLine(line []byte) { + var raw struct { + Type string `json:"Type"` + Action string `json:"Action"` + ID string `json:"id"` + Time int64 `json:"time"` + } + if err := json.Unmarshal(line, &raw); err != nil { + return + } + emitEvent(dockerChangedEvent, DockerEventNotice{Type: raw.Type, Action: raw.Action, ID: raw.ID, Time: raw.Time}) +} + func sleepContext(ctx context.Context, duration time.Duration) bool { timer := time.NewTimer(duration) defer timer.Stop() diff --git a/runtime_vmfree.go b/runtime_vmfree.go index ca0b467..d1c264e 100644 --- a/runtime_vmfree.go +++ b/runtime_vmfree.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "bytes" "context" "encoding/binary" @@ -62,20 +63,11 @@ func (r *vmfreeRuntime) request(ctx context.Context, method, path string, body a ctx, cancel = context.WithTimeout(ctx, 25*time.Second) defer cancel() } - // Read the token on each request so an engine restart does not require restarting Dockiva. - data, err := os.ReadFile(filepath.Join(r.home, "docker-client", "config.json")) + token, err := r.token() if err != nil { - return nil, fmt.Errorf("Dockiva Engine is not ready: %w", err) - } - var config struct{ HttpHeaders map[string]string } - if err = json.Unmarshal(data, &config); err != nil { return nil, err } - token := config.HttpHeaders["X-VMFree-Token"] - if len(token) != 64 { - return nil, errors.New("invalid Dockiva Engine authentication configuration") - } - var payload []byte + var data, payload []byte if body != nil { payload, err = json.Marshal(body) if err != nil { @@ -107,6 +99,52 @@ func (r *vmfreeRuntime) request(ctx context.Context, method, path string, body a } return data, nil } + +// token is read on each request so an engine restart does not require restarting Dockiva. +func (r *vmfreeRuntime) token() (string, error) { + data, err := os.ReadFile(filepath.Join(r.home, "docker-client", "config.json")) + if err != nil { + return "", fmt.Errorf("Dockiva Engine is not ready: %w", err) + } + var config struct{ HttpHeaders map[string]string } + if err = json.Unmarshal(data, &config); err != nil { + return "", err + } + token := config.HttpHeaders["X-VMFree-Token"] + if len(token) != 64 { + return "", errors.New("invalid Dockiva Engine authentication configuration") + } + return token, nil +} + +// streamEvents follows the engine's GET /events (JSON lines) until ctx is done or the +// connection ends, as when the engine restarts. connected runs once it is following. +func (r *vmfreeRuntime) streamEvents(ctx context.Context, each func([]byte), connected func()) error { + token, err := r.token() + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, "GET", "http://vmfree/v1.45/events", nil) + if err != nil { + return err + } + req.Header.Set("X-VMFree-Token", token) + resp, err := r.http.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("Dockiva Engine events: HTTP %d", resp.StatusCode) + } + connected() + scanner := bufio.NewScanner(resp.Body) + scanner.Buffer(make([]byte, 64*1024), 1024*1024) + for scanner.Scan() { + each(scanner.Bytes()) + } + return scanner.Err() +} func (r *vmfreeRuntime) Info(ctx context.Context) ContainerRuntimeInfo { info := ContainerRuntimeInfo{Provider: "vmfree", DisplayName: "Dockiva Engine", Endpoint: "unix://" + filepath.Join(r.home, "engine.sock"), Experimental: true, Capabilities: RuntimeCapabilities{Containers: true, Lifecycle: true, Stats: true, Logs: true, Terminal: true, Images: true, PullImages: true, CreateContainer: true, Volumes: true, Networks: true, PortPublishing: true, Compose: true}, diff --git a/runtime_vmfree_events_test.go b/runtime_vmfree_events_test.go new file mode 100644 index 0000000..39026ed --- /dev/null +++ b/runtime_vmfree_events_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "context" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +// The app follows Dockiva Engine's own /events stream, not the docker CLI's +// current context, so containers started outside the app show up. +func TestVMFreeStreamEvents(t *testing.T) { + home, err := os.MkdirTemp("/tmp", "dkv-ev") // short: unix socket paths are limited + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(home) + token := strings.Repeat("a", 64) + if err := os.MkdirAll(filepath.Join(home, "docker-client"), 0o700); err != nil { + t.Fatal(err) + } + config := `{"HttpHeaders":{"X-VMFree-Token":"` + token + `"}}` + if err := os.WriteFile(filepath.Join(home, "docker-client", "config.json"), []byte(config), 0o600); err != nil { + t.Fatal(err) + } + listener, err := net.Listen("unix", filepath.Join(home, "engine.sock")) + if err != nil { + t.Fatal(err) + } + defer listener.Close() + go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1.45/events" || r.Header.Get("X-VMFree-Token") != token { + http.Error(w, "unexpected request", http.StatusBadRequest) + return + } + w.Write([]byte(`{"Type":"container","Action":"start","id":"a1"}` + "\n" + `{"Type":"container","Action":"die","id":"a1"}` + "\n")) + })) + + var lines []string + connected := 0 + err = vmfreeAt(home).streamEvents(context.Background(), func(line []byte) { + lines = append(lines, string(line)) + }, func() { connected++ }) + if err != nil || connected != 1 || len(lines) != 2 || !strings.Contains(lines[1], `"die"`) { + t.Fatalf("err %v, connected %d, lines %q", err, connected, lines) + } +} From 6894d44a7936865c1a7eed4f9c5285a6e035f086 Mon Sep 17 00:00:00 2001 From: Chandarith Chea <45872539+chandarith-chea@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:18:43 +0700 Subject: [PATCH 2/2] Containers: a New container sheet, and icons for well-known images MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The native app had no way to create a container. A + button beside the Containers title opens a sheet like docker run -d: image, name, published TCP ports (127.0.0.1), environment variables, an optional command, and whether to start it. Templates fill in PostgreSQL, Redis, MySQL, MongoDB, Nginx and Node.js. The core's new DockerService.CreateContainer takes the whole request, passes Env to Dockiva Engine, and pulls the image first when the engine does not have it ("Image is not cached" / "No such image"). Each container row shows an icon for its image (postgres, redis, node, nginx, mysql, mongo, python, go, …) with the running dot on its corner; unknown images keep a plain box. Checked: go test -race; swift test (image-name parsing, icon choice, and the request JSON against the Go struct); and against the running engine, DOCKIVA_LIVE=1 go test -run TestLiveCreateContainer: busybox removed first, so the sheet's path pulled it, created it with an env var and a published port, started it and removed it. --- live_create_test.go | 29 +++ macos/Sources/Dockiva/AppModel.swift | 12 ++ macos/Sources/Dockiva/ContainersView.swift | 10 +- macos/Sources/Dockiva/ImageIcon.swift | 72 +++++++ macos/Sources/Dockiva/NewContainerSheet.swift | 189 ++++++++++++++++++ .../DockivaTests/NewContainerTests.swift | 31 +++ runtime_common.go | 27 +++ runtime_vmfree.go | 3 + 8 files changed, 371 insertions(+), 2 deletions(-) create mode 100644 live_create_test.go create mode 100644 macos/Sources/Dockiva/ImageIcon.swift create mode 100644 macos/Sources/Dockiva/NewContainerSheet.swift create mode 100644 macos/Tests/DockivaTests/NewContainerTests.swift diff --git a/live_create_test.go b/live_create_test.go new file mode 100644 index 0000000..26d035f --- /dev/null +++ b/live_create_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "context" + "os" + "strings" + "testing" +) + +// DOCKIVA_LIVE=1: against the running Dockiva Engine, create a container from an +// image the engine lacks (so CreateContainer pulls it), with an env var, then remove it. +func TestLiveCreateContainer(t *testing.T) { + if os.Getenv("DOCKIVA_LIVE") == "" { + t.Skip("set DOCKIVA_LIVE=1") + } + s := &DockerService{} + s.replaceRuntime(newVMFreeRuntime()) + c, err := s.CreateContainer(RuntimeCreateContainerRequest{Name: "dkv-live-create", Image: "busybox:1.36.1", + Command: []string{"sh", "-c", "echo $GREETING; sleep 30"}, Env: []string{"GREETING=hello-env"}, AutoStart: true, + PortMappings: []RuntimePortMapping{{HostPort: 18555, ContainerPort: 80, Protocol: "tcp", HostIP: "127.0.0.1"}}}) + if err != nil { + t.Fatal(err) + } + defer s.currentRuntime().RemoveContainer(context.Background(), c.ID, true) + data, err := newVMFreeRuntime().request(context.Background(), "GET", vmfreeContainerPath(c.ID)+"/json", nil) + if err != nil || !strings.Contains(string(data), "GREETING=hello-env") || !strings.Contains(string(data), "18555") { + t.Fatalf("inspect: %v %.400s", err, data) + } +} diff --git a/macos/Sources/Dockiva/AppModel.swift b/macos/Sources/Dockiva/AppModel.swift index ffb9e50..8bb88ca 100644 --- a/macos/Sources/Dockiva/AppModel.swift +++ b/macos/Sources/Dockiva/AppModel.swift @@ -163,6 +163,18 @@ final class AppModel { } } + /// Creates (and by default starts) a container; returns the error message, if any. + func createContainer(_ request: CreateContainerRequest) async -> String? { + guard let core else { return "Dockiva's core is not running" } + do { + _ = try await core.call("DockerService.CreateContainer", [request], as: ContainerInfo.self) + } catch { + return error.localizedDescription + } + await refreshResources() + return nil + } + func engineAction(start: Bool) async { guard let core, let settings else { return } engineBusy = true diff --git a/macos/Sources/Dockiva/ContainersView.swift b/macos/Sources/Dockiva/ContainersView.swift index b882a7c..6bf07f8 100644 --- a/macos/Sources/Dockiva/ContainersView.swift +++ b/macos/Sources/Dockiva/ContainersView.swift @@ -8,6 +8,7 @@ struct ContainersView: View { @State private var search = "" @State private var filter = "all" @State private var hovered: ContainerInfo.ID? + @State private var creating = false private let accent = SidebarItem.containers.accent @@ -43,7 +44,7 @@ struct ContainersView: View { ScrollView { EmptyStateCard(eyebrow: "PICK ONE", title: model.containers.isEmpty ? "No containers yet" : "Select a container", detail: model.containers.isEmpty - ? "Run one with docker run or docker compose up; it shows up here right away." + ? "Press + to run an image, or use docker run or docker compose up; it shows up here right away." : "See its live usage, logs and a terminal, and start, stop or remove it.", symbol: "shippingbox.fill", accent: accent) .padding(28) @@ -68,8 +69,13 @@ struct ContainersView: View { Text("Containers").font(.title2.bold()) Text("\(model.runningCount) running · \(model.containers.count) total").font(.caption).foregroundStyle(.secondary) } + Spacer() + Button { creating = true } label: { Image(systemName: "plus") } + .buttonStyle(SecondaryButtonStyle()) + .help("New container") } .padding(.top, 14) + .sheet(isPresented: $creating) { NewContainerSheet() } SearchField(prompt: "Search containers", text: $search) FilterPills(choices: [("All", "all"), ("Running", "running"), ("Stopped", "stopped")], selection: $filter) ScrollView { @@ -104,7 +110,7 @@ struct ContainersView: View { let isSelected = selection == c.id return Button { selection = c.id } label: { HStack(spacing: 10) { - StatusDot(running: c.isRunning) + ImageIcon(image: c.image, running: c.isRunning) VStack(alignment: .leading, spacing: 1) { Text(c.composeService ?? c.name).font(.system(size: 13, weight: .semibold, design: .rounded)).lineLimit(1) Text(c.image).font(.caption).foregroundStyle(.secondary).lineLimit(1) diff --git a/macos/Sources/Dockiva/ImageIcon.swift b/macos/Sources/Dockiva/ImageIcon.swift new file mode 100644 index 0000000..9e1397a --- /dev/null +++ b/macos/Sources/Dockiva/ImageIcon.swift @@ -0,0 +1,72 @@ +import SwiftUI + +/// A recognisable glyph and colour for well-known images (postgres, redis, node, …), +/// so a list of containers reads at a glance. Unknown images get a plain box. +struct ImageIcon: View { + let image: String + var running = false + var size: CGFloat = 30 + + var body: some View { + let style = ImageStyle.of(image) + ZStack(alignment: .bottomTrailing) { + RoundedRectangle(cornerRadius: size * 0.3, style: .continuous) + .fill(LinearGradient(colors: [style.color.opacity(0.95), style.color.opacity(0.6)], startPoint: .topLeading, endPoint: .bottomTrailing)) + .overlay(RoundedRectangle(cornerRadius: size * 0.3, style: .continuous).stroke(.white.opacity(0.18))) + .overlay(Image(systemName: style.symbol).font(.system(size: size * 0.46, weight: .semibold)).foregroundStyle(.white)) + .frame(width: size, height: size) + .opacity(running ? 1 : 0.55) + StatusDot(running: running) + .overlay(Circle().stroke(DockivaPalette.deepNavy, lineWidth: 2)) + .offset(x: 3, y: 3) + } + .accessibilityHidden(true) + } +} + +struct ImageStyle { + let symbol: String + let color: Color + + /// The image's short name: "docker.io/library/postgres:16-alpine" → "postgres". + static func name(_ image: String) -> String { + var last = image.split(separator: "/").last.map(String.init) ?? image + if let at = last.firstIndex(of: "@") { last = String(last[.. ImageStyle { + let name = name(image) + for (keys, style) in known where keys.contains(where: { name.hasPrefix($0) }) { + return style + } + return ImageStyle(symbol: "shippingbox.fill", color: .gray) + } + + private static func rgb(_ hex: UInt32) -> Color { + Color(red: Double(hex >> 16 & 0xFF) / 255, green: Double(hex >> 8 & 0xFF) / 255, blue: Double(hex & 0xFF) / 255) + } + + private static let known: [([String], ImageStyle)] = [ + (["postgres", "postgis", "timescale"], ImageStyle(symbol: "cylinder.split.1x2.fill", color: rgb(0x336791))), + (["mysql", "mariadb", "percona"], ImageStyle(symbol: "cylinder.fill", color: rgb(0x00758F))), + (["mongo"], ImageStyle(symbol: "leaf.fill", color: rgb(0x47A248))), + (["redis", "valkey", "keydb", "dragonfly"], ImageStyle(symbol: "square.stack.3d.up.fill", color: rgb(0xDC382D))), + (["memcached"], ImageStyle(symbol: "memorychip.fill", color: rgb(0x4E8A3E))), + (["node", "bun", "deno"], ImageStyle(symbol: "hexagon.fill", color: rgb(0x5FA04E))), + (["python"], ImageStyle(symbol: "chevron.left.forwardslash.chevron.right", color: rgb(0x3776AB))), + (["golang", "go"], ImageStyle(symbol: "g.circle.fill", color: rgb(0x00ADD8))), + (["openjdk", "eclipse-temurin", "amazoncorretto", "maven", "gradle"], ImageStyle(symbol: "cup.and.saucer.fill", color: rgb(0xE76F00))), + (["php", "wordpress"], ImageStyle(symbol: "p.circle.fill", color: rgb(0x777BB4))), + (["ruby", "rails"], ImageStyle(symbol: "diamond.fill", color: rgb(0xCC342D))), + (["nginx", "httpd", "caddy", "traefik", "haproxy", "envoy"], ImageStyle(symbol: "globe", color: rgb(0x009639))), + (["rabbitmq"], ImageStyle(symbol: "envelope.fill", color: rgb(0xFF6600))), + (["kafka", "zookeeper", "nats"], ImageStyle(symbol: "arrow.triangle.branch", color: rgb(0x231F20))), + (["elasticsearch", "opensearch", "kibana", "meilisearch"], ImageStyle(symbol: "magnifyingglass", color: rgb(0x00BFB3))), + (["minio", "localstack"], ImageStyle(symbol: "externaldrive.fill", color: rgb(0xC72E49))), + (["grafana", "prometheus"], ImageStyle(symbol: "chart.xyaxis.line", color: rgb(0xF46800))), + (["dockiva-gh-runner", "actions-runner", "runner"], ImageStyle(symbol: "gearshape.2.fill", color: rgb(0x24292F))), + (["alpine", "ubuntu", "debian", "busybox", "fedora", "centos", "archlinux", "shell"], ImageStyle(symbol: "terminal.fill", color: rgb(0x52606D))), + ] +} diff --git a/macos/Sources/Dockiva/NewContainerSheet.swift b/macos/Sources/Dockiva/NewContainerSheet.swift new file mode 100644 index 0000000..1a20639 --- /dev/null +++ b/macos/Sources/Dockiva/NewContainerSheet.swift @@ -0,0 +1,189 @@ +import SwiftUI + +/// The request DockerService.CreateContainer takes (RuntimeCreateContainerRequest). +struct CreateContainerRequest: Encodable { + struct Port: Encodable { var hostPort: Int; var containerPort: Int; var `protocol` = "tcp"; var hostIp = "127.0.0.1" } + var name: String + var image: String + var command: [String] + var autoStart: Bool + var portMappings: [Port] + var env: [String] +} + +/// Runs an image as a new container, like `docker run -d`: image, name, published +/// ports, environment and an optional command. Templates fill in common services. +struct NewContainerSheet: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + + struct PortRow: Identifiable { let id = UUID(); var host = ""; var container = "" } + struct EnvRow: Identifiable { let id = UUID(); var key = ""; var value = "" } + + @State private var image = "" + @State private var name = "" + @State private var command = "" + @State private var ports: [PortRow] = [] + @State private var env: [EnvRow] = [] + @State private var start = true + @State private var creating = false + @State private var error: String? + + private let accent = SidebarItem.containers.accent + + struct Template: Identifiable { + var id: String { title } + let title: String, image: String, name: String + var ports: [(Int, Int)] = [] + var env: [(String, String)] = [] + var command = "" + } + + private let templates: [Template] = [ + Template(title: "PostgreSQL", image: "postgres:16-alpine", name: "postgres", ports: [(5432, 5432)], env: [("POSTGRES_PASSWORD", "postgres")]), + Template(title: "Redis", image: "redis:7-alpine", name: "redis", ports: [(6379, 6379)]), + Template(title: "MySQL", image: "mysql:8", name: "mysql", ports: [(3306, 3306)], env: [("MYSQL_ROOT_PASSWORD", "mysql")]), + Template(title: "MongoDB", image: "mongo:7", name: "mongo", ports: [(27017, 27017)]), + Template(title: "Nginx", image: "nginx:alpine", name: "nginx", ports: [(8080, 80)]), + Template(title: "Node.js", image: "node:22-alpine", name: "node", command: "sleep infinity"), + ] + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + HStack(spacing: 12) { + ImageIcon(image: image.isEmpty ? "box" : image, running: true, size: 36) + VStack(alignment: .leading, spacing: 1) { + Text("New container").font(.title2.bold()) + Text("Runs an image, like docker run -d. Ports publish on 127.0.0.1.").font(.caption).foregroundStyle(.secondary) + } + } + + ScrollView(.horizontal) { + HStack(spacing: 8) { + ForEach(templates) { t in + Button { apply(t) } label: { + HStack(spacing: 6) { + ImageIcon(image: t.image, running: true, size: 18) + Text(t.title) + } + } + .buttonStyle(SecondaryButtonStyle()) + } + } + } + .scrollIndicators(.hidden) + + Form { + TextField("Image", text: $image, prompt: Text("e.g. postgres:16-alpine")) + TextField("Name", text: $name, prompt: Text("e.g. postgres")) + TextField("Command", text: $command, prompt: Text("Optional, e.g. sleep infinity")) + + Section { + ForEach($ports) { $row in + HStack { + TextField("Host", text: $row.host, prompt: Text("Host port")) + Image(systemName: "arrow.right").foregroundStyle(.secondary) + TextField("Container", text: $row.container, prompt: Text("Container port")) + removeButton { ports.removeAll { $0.id == row.id } } + } + .labelsHidden() + } + Button { ports.append(PortRow()) } label: { Label("Add port", systemImage: "plus") }.buttonStyle(.borderless) + } header: { Text("Ports (TCP, on 127.0.0.1)") } + + Section { + ForEach($env) { $row in + HStack { + TextField("Key", text: $row.key, prompt: Text("KEY")) + Text("=").foregroundStyle(.secondary) + TextField("Value", text: $row.value, prompt: Text("value")) + removeButton { env.removeAll { $0.id == row.id } } + } + .labelsHidden() + } + Button { env.append(EnvRow()) } label: { Label("Add variable", systemImage: "plus") }.buttonStyle(.borderless) + } header: { Text("Environment") } + + Toggle("Start the container after creating it", isOn: $start) + } + .formStyle(.grouped) + .frame(minHeight: 320) + + if let error { + Label(error, systemImage: "exclamationmark.triangle.fill").font(.callout).foregroundStyle(.red).textSelection(.enabled) + } + + HStack { + if creating { + ProgressView().controlSize(.small) + Text("Pulling the image if needed…").font(.caption).foregroundStyle(.secondary) + } + Spacer() + Button("Cancel") { dismiss() }.buttonStyle(SecondaryButtonStyle()).keyboardShortcut(.cancelAction) + Button(action: create) { Label("Create", systemImage: "plus") } + .buttonStyle(PrimaryButtonStyle(color: accent)) + .keyboardShortcut(.defaultAction) + .disabled(creating || image.trimmingCharacters(in: .whitespaces).isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty) + } + } + .padding(22) + .frame(width: 560) + .onChange(of: image) { old, new in + // Suggest a name from the image while the name still follows it. + if name.isEmpty || name == ImageStyle.name(old) { name = ImageStyle.name(new) } + } + } + + private func removeButton(_ action: @escaping () -> Void) -> some View { + Button(action: action) { Image(systemName: "minus.circle.fill").foregroundStyle(.secondary) }.buttonStyle(.plain) + } + + private func apply(_ t: Template) { + image = t.image + name = t.name + command = t.command + ports = t.ports.map { PortRow(host: String($0.0), container: String($0.1)) } + env = t.env.map { EnvRow(key: $0.0, value: $0.1) } + error = nil + } + + /// The request, or a message saying which field is wrong. + private func request() -> Result { + struct Invalid: LocalizedError { let errorDescription: String? } + var mappings: [CreateContainerRequest.Port] = [] + for row in ports where !(row.host.isEmpty && row.container.isEmpty) { + guard let host = Int(row.host.trimmingCharacters(in: .whitespaces)), (1...65535).contains(host), + let container = Int(row.container.trimmingCharacters(in: .whitespaces)), (1...65535).contains(container) + else { return .failure(Invalid(errorDescription: "Ports must be numbers from 1 to 65535: \(row.host) → \(row.container)")) } + mappings.append(.init(hostPort: host, containerPort: container)) + } + var variables: [String] = [] + for row in env where !row.key.isEmpty { + guard !row.key.contains("=") && !row.key.contains(" ") else { + return .failure(Invalid(errorDescription: "Environment names cannot contain = or spaces: \(row.key)")) + } + variables.append("\(row.key)=\(row.value)") + } + // ponytail: splits on spaces; quoted arguments need a JSON-array field if users ask. + let args = command.split(separator: " ", omittingEmptySubsequences: true).map(String.init) + return .success(CreateContainerRequest(name: name.trimmingCharacters(in: .whitespaces), image: image.trimmingCharacters(in: .whitespaces), + command: args, autoStart: start, portMappings: mappings, env: variables)) + } + + private func create() { + switch request() { + case .failure(let failure): error = failure.localizedDescription + case .success(let request): + creating = true + error = nil + Task { + defer { creating = false } + if let message = await model.createContainer(request) { + error = message + } else { + dismiss() + } + } + } + } +} diff --git a/macos/Tests/DockivaTests/NewContainerTests.swift b/macos/Tests/DockivaTests/NewContainerTests.swift new file mode 100644 index 0000000..b7c756b --- /dev/null +++ b/macos/Tests/DockivaTests/NewContainerTests.swift @@ -0,0 +1,31 @@ +import Foundation +import XCTest +@testable import Dockiva + +final class NewContainerTests: XCTestCase { + func testImageShortNames() { + XCTAssertEqual(ImageStyle.name("postgres:16-alpine"), "postgres") + XCTAssertEqual(ImageStyle.name("docker.io/library/redis:7"), "redis") + XCTAssertEqual(ImageStyle.name("ghcr.io/org/node@sha256:abc"), "node") + XCTAssertEqual(ImageStyle.name("localhost:5000/app"), "app") + } + + func testKnownImagesGetTheirIcon() { + XCTAssertEqual(ImageStyle.of("postgres:16-alpine").symbol, "cylinder.split.1x2.fill") + XCTAssertEqual(ImageStyle.of("bitnami/redis").symbol, "square.stack.3d.up.fill") + XCTAssertEqual(ImageStyle.of("node:22-alpine").symbol, "hexagon.fill") + XCTAssertEqual(ImageStyle.of("sha256:7e92bb0dd372").symbol, "shippingbox.fill") + } + + /// The JSON must match the Go core's RuntimeCreateContainerRequest. + func testCreateRequestJSON() throws { + let request = CreateContainerRequest(name: "pg", image: "postgres:16-alpine", command: [], autoStart: true, + portMappings: [.init(hostPort: 5432, containerPort: 5432)], env: ["POSTGRES_PASSWORD=x"]) + let object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(request)) as! [String: Any] + XCTAssertEqual(Set(object.keys), ["name", "image", "command", "autoStart", "portMappings", "env"]) + let port = (object["portMappings"] as! [[String: Any]])[0] + XCTAssertEqual(port["hostPort"] as? Int, 5432) + XCTAssertEqual(port["protocol"] as? String, "tcp") + XCTAssertEqual(port["hostIp"] as? String, "127.0.0.1") + } +} diff --git a/runtime_common.go b/runtime_common.go index b027f9a..e525ef2 100644 --- a/runtime_common.go +++ b/runtime_common.go @@ -68,6 +68,7 @@ type RuntimeCreateContainerRequest struct { Command []string `json:"command"` AutoStart bool `json:"autoStart"` PortMappings []RuntimePortMapping `json:"portMappings"` + Env []string `json:"env"` // KEY=VALUE } // ContainerRuntime is the runtime-neutral lifecycle seam. @@ -268,6 +269,32 @@ func (s *DockerService) RuntimePullImage( return puller.PullRuntimeImage(ctx, reference) } +// CreateContainer runs an image as a new container, as `docker run -d` does: when +// the runtime does not have the image yet, it pulls it and tries again. +func (s *DockerService) CreateContainer(request RuntimeCreateContainerRequest) (ContainerInfo, error) { + request.Name, request.Image = strings.TrimSpace(request.Name), strings.TrimSpace(request.Image) + if request.Name == "" || request.Image == "" { + return ContainerInfo{}, errors.New("an image and a container name are required") + } + runtime := s.currentRuntime() + creator, ok := runtime.(runtimeContainerCreator) + if !ok { + return ContainerInfo{}, errors.New("the active runtime cannot create containers from Dockiva") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) // a first pull can be large + defer cancel() + created, err := creator.CreateRuntimeContainer(ctx, request) + puller, canPull := runtime.(runtimeImagePuller) + missing := err != nil && (strings.Contains(strings.ToLower(err.Error()), "no such image") || strings.Contains(err.Error(), "is not cached")) + if !missing || !canPull { + return created, err + } + if _, err = puller.PullRuntimeImage(ctx, request.Image); err != nil { + return ContainerInfo{}, fmt.Errorf("pull %s: %w", request.Image, err) + } + return creator.CreateRuntimeContainer(ctx, request) +} + func (s *DockerService) RuntimeCreateContainer( name string, image string, diff --git a/runtime_vmfree.go b/runtime_vmfree.go index d1c264e..db9b0f7 100644 --- a/runtime_vmfree.go +++ b/runtime_vmfree.go @@ -255,6 +255,9 @@ func (r *vmfreeRuntime) CreateRuntimeContainer(ctx context.Context, q RuntimeCre if len(q.Command) > 0 { body["Cmd"] = q.Command } + if len(q.Env) > 0 { + body["Env"] = q.Env + } data, err := r.request(ctx, "POST", "/containers/create?name="+url.QueryEscape(q.Name), body) if err != nil { return ContainerInfo{}, err