Skip to content
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
128 changes: 58 additions & 70 deletions docker_platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
29 changes: 29 additions & 0 deletions live_create_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
12 changes: 12 additions & 0 deletions macos/Sources/Dockiva/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions macos/Sources/Dockiva/ContainersView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
72 changes: 72 additions & 0 deletions macos/Sources/Dockiva/ImageIcon.swift
Original file line number Diff line number Diff line change
@@ -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[..<at]) }
if let colon = last.firstIndex(of: ":") { last = String(last[..<colon]) }
return last.lowercased()
}

static func of(_ image: String) -> 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))),
]
}
Loading
Loading