Files
toolshed-extensions/docker/init.lua
T

783 lines
34 KiB
Lua

-- Docker: "docker" lists compose projects and containers, "docker web" finds them by name, image,
-- project or service. A container's details, logs and stats are pages a level down; Docker
-- Dashboard shows every container, with what the running ones use, updating as it goes; Docker
-- Prune frees space, saying how much each kind would free first. Everything goes through the docker command, so Podman or Colima
-- work too, by setting their command. Its text is in locales/.
local function docker(settings)
local command = settings.command
return (command and command ~= "") and command or "docker"
end
local function run(settings, ...)
return toolshed.exec({ docker(settings), ... })
end
local function lines(text)
local out = {}
for line in text:gmatch("[^\n]+") do table.insert(out, line) end
return out
end
-- Each line docker prints with --format '{{json .}}' is one JSON object.
local function json_lines(text)
local out = {}
for _, line in ipairs(lines(text)) do table.insert(out, toolshed.json.decode(line)) end
return out
end
local escape = toolshed.escape
-- Numbers worked out here are written as the language writes them: 1.5 in English, 1,5 in Norwegian.
local function localised(text)
return (text:gsub("%.", toolshed.t("decimal")))
end
-- A compose label's value. Labels are "k=v,k=v", and only these, whose values hold no commas, are read.
local function label(labels, key)
return (labels or ""):match("com%.docker%.compose%." .. key:gsub("%.", "%%.") .. "=([^,]*)")
end
-- The ports a container publishes on this Mac, once each: "0.0.0.0:3000->3000/tcp, :::3000->3000/tcp".
local function published(ports)
local out, seen = {}, {}
for host, inside, proto in (ports or ""):gmatch(":(%d+)%->(%d+)/(%a+)") do
if not seen[host] then
seen[host] = true
table.insert(out, { host = host, inside = inside, proto = proto })
end
end
return out
end
local function containers(settings)
local out = {}
for _, c in ipairs(json_lines(run(settings, "ps", "-a", "--no-trunc", "--format", "{{json .}}"))) do
table.insert(out, {
id = c.ID:sub(1, 12), name = c.Names, image = c.Image, state = c.State, status = c.Status,
ports = published(c.Ports),
project = label(c.Labels, "project"), service = label(c.Labels, "service"),
folder = label(c.Labels, "project.working_dir"),
})
end
table.sort(out, function(a, b)
if (a.state == "running") ~= (b.state == "running") then return a.state == "running" end
return a.name < b.name
end)
return out
end
local function projects(list)
local out, by = {}, {}
for _, c in ipairs(list) do
if c.project then
local p = by[c.project]
if not p then
p = { name = c.project, folder = c.folder, containers = {}, running = 0 }
by[c.project] = p
table.insert(out, p)
end
table.insert(p.containers, c)
if c.state == "running" then p.running = p.running + 1 end
end
end
table.sort(out, function(a, b) return a.name < b.name end)
return out
end
local function ports_text(c)
local out = {}
for _, p in ipairs(c.ports) do table.insert(out, ":" .. p.host) end
return table.concat(out, " ")
end
-- The jig for a container, offering the actions that fit its state.
local function container_jig(c)
local actions = { "details", "logs", "copy-id", "remove" }
if c.state == "running" then
for _, a in ipairs({ "shell", "stop", "restart", "follow-logs" }) do table.insert(actions, a) end
if #c.ports > 0 then table.insert(actions, "open-port") end
else
table.insert(actions, "start")
end
local where = c.project and (toolshed.t("service-in", { service = c.service, project = c.project }) .. ", ") or ""
local ports = ports_text(c)
return {
title = c.name, icon = "container", tool = "containers", actions = actions,
subtitle = where .. c.status .. (ports ~= "" and (" " .. ports) or ""),
data = { id = c.id, name = c.name },
}
end
local function project_jig(p)
return {
title = p.name, icon = "boxes", tool = "project",
subtitle = toolshed.t("running-of", { running = p.running, total = #p.containers }),
data = { name = p.name, folder = p.folder },
}
end
-- What to show when docker can't be asked: usually Docker Desktop isn't running.
local function unavailable(err)
local reason = tostring(err):match("[^\n]+") or ""
return {
title = toolshed.t("not-running"), icon = "container", tool = "desktop",
subtitle = reason ~= "" and reason or toolshed.t("open-desktop"),
}
end
-- Opens a Terminal window running command: a .command file, which macOS opens in Terminal
-- without asking for permission to control it.
local function in_terminal(name, command)
local path = toolshed.cache_dir() .. "/" .. name:gsub("[^%w%-_]", "_") .. ".command"
local f = assert(io.open(path, "w"))
f:write("#!/bin/sh\nclear\nexec " .. command .. "\n")
f:close()
toolshed.exec({ "chmod", "+x", path })
toolshed.open(path)
end
local quoted = toolshed.shell_quote
-- Runs a docker command that may take longer than an action may (pulling images), and returns
-- straight away: it shows in Active while it runs, titled as said, and says why if it fails;
-- Docker shows the outcome in the list.
local function compose_key(project) return "compose-" .. project:lower():gsub("[^%w_-]", "-") end
local function in_background(settings, key, title, ...)
toolshed.activities.set {
key = key, title = title, icon = "container", timeout = 1800,
run = { docker(settings), ... }, ending = { failed = title },
}
end
-- Sizes as docker prints them ("20.5MiB", "1.2GB") in bytes, to add them up.
local units = { B = 1, kB = 1e3, KB = 1e3, MB = 1e6, GB = 1e9, TB = 1e12, KiB = 1024, MiB = 1024 ^ 2, GiB = 1024 ^ 3, TiB = 1024 ^ 4 }
local function bytes(text)
local n, unit = (text or ""):match("([%d%.]+)%s*(%a+)")
return (tonumber(n or "") or 0) * (units[unit or ""] or 0)
end
-- decimal writes bytes as docker does: "1.2GB", "300MB".
local function decimal(n)
for _, u in ipairs({ { "TB", 1e12 }, { "GB", 1e9 }, { "MB", 1e6 }, { "kB", 1e3 } }) do
if n >= u[2] then return localised(string.format("%.3g", n / u[2])) .. u[1] end
end
return string.format("%dB", n)
end
-- What dangling images take, the ones no tag points to.
local function dangling_images(settings)
local total = 0
local ok, out = pcall(run, settings, "images", "-f", "dangling=true", "--format", "{{.Size}}")
for _, line in ipairs(ok and lines(out) or {}) do total = total + bytes(line) end
return total
end
local function size(n)
for _, u in ipairs({ { "GiB", 1024 ^ 3 }, { "MiB", 1024 ^ 2 }, { "KiB", 1024 } }) do
if n >= u[2] then return localised(string.format("%.1f %s", n / u[2], u[1])) end
end
return string.format("%d B", n)
end
-- Pages are drawn in the launcher's own terms: its type sizes, colours and rounded rows, no
-- Pages use the launcher's page classes (docs/extensions.md), so they look like the rest of the
-- app: its icons by name, its tints, sparklines drawn from their values.
local function page(body)
return '<div class="page">' .. body .. "</div>"
end
local function tile(icon, small)
return '<span class="tile' .. (small and " small" or "") .. '" data-icon="' .. icon .. '"></span>'
end
-- sparkline is how values went, the latest last; percentages are drawn from zero.
local function sparkline(values, from_zero)
if not values or #values < 2 then return "" end
local text = {}
for _, v in ipairs(values) do table.insert(text, string.format("%.4g", v)) end
return '<svg class="spark" data-values="' .. table.concat(text, " ") .. '"' .. (from_zero and " data-from-zero" or "") .. "></svg>"
end
-- split shows how many of a whole are on: a segment each, lit for those running.
local function split(on, total)
local out = {}
for i = 1, math.min(total, 40) do table.insert(out, i <= on and '<span class="on"></span>' or "<span></span>") end
return '<div class="split">' .. table.concat(out) .. "</div>"
end
-- figures are the numbers at the top of a page, each { label, value, icon, tint, history }; the
-- value is HTML, for a quieter part like "of 4".
local function figures(list)
local out = {}
for _, f in ipairs(list) do
table.insert(out, '<div class="figure" data-tint="' .. f[4] .. '">' .. tile(f[3]) .. '<div class="value">' .. f[2] ..
'</div><div class="label">' .. escape(f[1]) .. "</div>" .. (f.under or sparkline(f[5], f.from_zero)) .. "</div>")
end
return '<div class="figures">' .. table.concat(out) .. "</div>"
end
local function dot(state)
return '<span class="dot' .. (state == "running" and " on" or "") .. '"></span>'
end
local function meter(part)
return '<span class="meter"><span style="width:' .. math.min(part, 100) .. '%"></span></span>'
end
-- The columns of the container lines: name, CPU, memory, network, ports.
local columns = "minmax(0, 1fr) 96px 104px 108px 92px"
-- Docker takes a second or two to measure what containers use, so it measures in the background
-- and pages show the latest measurement, at most one refresh old.
local stats_file = toolshed.cache_dir() .. "/stats.json"
local modified = toolshed.file.modified
local function measure(settings)
toolshed.activities.set {
key = "stats", title = toolshed.t("jobs.stats.title"), description = toolshed.t("jobs.stats.description"), quiet = true, timeout = 30,
run = { "sh", "-c", '"$0" stats --no-stream --format "{{json .}}" > "$1.part" && mv "$1.part" "$1"', docker(settings), stats_file },
}
end
local function percent(text)
return tonumber((text or ""):match("([%d%.]+)") or "") or 0
end
-- What was measured lately, a minute's worth, by what it's of ("cpu", or a container's
-- "cpu:<id>"), to draw how it changed. A measurement counts once, however often it's read;
-- without one (at), these only read what's kept.
local history = {}
local function remember(key, at, value)
local h = history[key] or { values = {} }
history[key] = h
if at and h.at ~= at then
h.at = at
table.insert(h.values, value)
if #h.values > 20 then table.remove(h.values, 1) end
end
return h.values
end
-- rates are how fast a growing total went, per second, between the measurements remembered.
local totals = {}
local function rates(key, at, total)
local h = totals[key] or {}
totals[key] = h
if at and (#h == 0 or h[#h].at ~= at) then
table.insert(h, { at = at, total = total })
if #h > 21 then table.remove(h, 1) end
end
local out = {}
for i = 2, #h do
local seconds = h[i].at - h[i - 1].at
if seconds > 0 then table.insert(out, math.max(h[i].total - h[i - 1].total, 0) / seconds) end
end
return out
end
-- in_and_out is what docker's "1.2MB / 3.4MB" adds up to.
local function in_and_out(text)
local a, b = (text or ""):match("^(.-)%s*/%s*(.-)$")
return bytes(a) + bytes(b)
end
-- latest_stats is what running containers used when last measured, by ID, and whether that's
-- recent enough to show. It starts the next measurement.
local function latest_stats(settings)
measure(settings)
local by = {}
local at = modified(stats_file)
if not at or os.time() - at > 60 then return by, false end
local f = io.open(stats_file, "r")
if not f then return by, false end
local text = f:read("*a")
f:close()
local ok, list = pcall(json_lines, text)
local cpu, memory = 0, 0
for _, s in ipairs(ok and list or {}) do
local id = s.ID:sub(1, 12)
by[id] = s
-- Kept for every container, so a page opened later already has the last minute to draw.
remember("cpu:" .. id, at, percent(s.CPUPerc))
remember("memory:" .. id, at, bytes(s.MemUsage))
rates("net:" .. id, at, in_and_out(s.NetIO))
cpu, memory = cpu + percent(s.CPUPerc), memory + bytes(s.MemUsage)
end
remember("cpu", at, cpu)
remember("memory", at, memory)
return by, true, at
end
local function find(settings, id)
for _, c in ipairs(containers(settings)) do
if c.id == id then return c end
end
error(toolshed.t("gone"))
end
local function port_jigs(c)
local out = {}
for _, p in ipairs(c.ports) do
table.insert(out, {
title = toolshed.t("open-localhost", { port = p.host }), icon = "external-link", tool = "port",
subtitle = toolshed.t("port-inside", { port = p.inside, proto = p.proto }), data = { port = p.host },
})
end
return out
end
local function logs_page(title, text)
local tail = {}
local all = lines(text)
for i = math.max(1, #all - 199), #all do table.insert(tail, all[i]) end
if #tail == 0 then return page('<div class="empty">' .. escape(toolshed.t("no-logs")) .. "</div>") end
-- Starts scrolled to the end, where the newest lines are.
return page('<div class="note">' .. escape(toolshed.t("last-lines", { count = #tail })) .. '</div><pre class="log">' .. escape(table.concat(tail, "\n")) ..
'</pre><script>requestAnimationFrame(() => { const v = document.querySelector(".view"); if (v) v.scrollTop = v.scrollHeight })</script>')
end
-- overview draws containers as Docker Dashboard does: figures for what runs, with how CPU and
-- memory went (the histories), then a line each, projects with their services hanging from them.
-- Each line is a jig the page draws itself, selected and run as the list's are. The Dashboard
-- shows every container; a project's page only its own, and is about it: its line does what's
-- done with the project, where showing its services again would only open this page.
local function overview(list, settings, cpu_history, memory_history, about)
local stats, measured = latest_stats(settings)
local function usage(c)
local s = stats[c.id] or { CPUPerc = "…", MemUsage = "…", MemPerc = "0", NetIO = "…" }
c.cpu, c.memory, c.stats = percent(s.CPUPerc), bytes(s.MemUsage), s
end
-- Running first, the busiest first; stopped ones after, by name, to start again.
local function order(a, b)
local ar, br = a.state == "running", b.state == "running"
if ar ~= br then return ar end
if ar and a.cpu ~= b.cpu then return a.cpu > b.cpu end
return a.name < b.name
end
-- Containers outside a project first, then each project with its services under it, as
-- Docker Desktop shows them.
local alone, cpu, memory, count = {}, 0, 0, 0
for _, c in ipairs(list) do
c.cpu, c.memory = 0, 0
if c.state == "running" then
usage(c)
cpu, memory, count = cpu + c.cpu, memory + c.memory, count + 1
end
if not c.project then table.insert(alone, c) end
end
table.sort(alone, order)
local measure = function(text) return measured and text or "…" end
local function metric(text, part)
return measure('<div class="metric">' .. meter(part) .. "<span>" .. text .. "</span></div>")
end
local lines, jigs, folder = {}, {}, nil
-- Each line is a jig the page draws itself (data-jig), selected and run as the list's are.
-- A stopped one uses nothing, so it shows a dash where the numbers go.
local function add(jig, class, running, name, extra, cpu_text, cpu, memory, part, net, ports)
table.insert(jigs, jig)
local none = '<span class="none">—</span>'
local classes = ("line " .. class .. (running and "" or " muted")):gsub("%s+", " ")
table.insert(lines, '<div class="' .. classes .. '" data-jig="' .. #jigs ..
'"><div class="name">' .. dot(running and "running" or "stopped") .. '<span class="text">' .. name .. "</span>" .. extra ..
'</div><div class="num">' .. (running and metric(cpu_text, cpu) or none) ..
'</div><div class="num">' .. (running and metric(size(memory), part) or none) ..
'</div><div class="num dim">' .. (running and net or none) .. '</div><div class="dim">' .. ports .. "</div></div>")
end
local function container(c, class, name)
local running = c.state == "running"
add(container_jig(c), class, running, escape(name), "", running and escape(c.stats.CPUPerc), c.cpu, c.memory,
running and percent(c.stats.MemPerc), running and measure(escape(c.stats.NetIO)), escape(ports_text(c)))
end
for _, c in ipairs(alone) do container(c, "", c.name) end
for _, p in ipairs(projects(list)) do
local services, pcpu, pmemory, part = {}, 0, 0, 0
for _, c in ipairs(p.containers) do
table.insert(services, c)
if c.state == "running" then
pcpu, pmemory, part = pcpu + c.cpu, pmemory + c.memory, part + percent(c.stats.MemPerc)
end
end
table.sort(services, order)
local jig, extra = project_jig(p), '<span class="count">' .. escape(toolshed.t("count-of", { running = p.running, total = #p.containers })) .. "</span>"
if p.name == about then
jig.action, jig.actions = "logs", { "logs", "restart", "up", "down", "open-folder", "copy-name" }
folder = p.folder
end
add(jig, "parent", p.running > 0, escape(p.name), extra, localised(string.format("%.2f%%", pcpu)), pcpu, pmemory, part, "", "")
for i, c in ipairs(services) do
-- Under its project a container is its service: "db", not "shop-db-1".
container(c, i == #services and "child last" or "child", c.service or c.name)
end
end
if #list == 0 then return { html = page('<div class="empty">' .. escape(toolshed.t("no-containers")) .. "</div>"), refresh = 3 } end
local top = figures({
{ toolshed.t("running"), count .. (#list > count and ("<small> " .. escape(toolshed.t("of", { total = #list })) .. "</small>") or ""), "container", "green", under = split(count, #list) },
{ toolshed.t("cpu"), measured and localised(string.format("%.1f%%", cpu)) or "…", "cpu", "blue", measured and cpu_history, from_zero = true },
{ toolshed.t("memory"), measured and size(memory) or "…", "memory-stick", "purple", measured and memory_history },
})
local head = '<div class="head"><div>' .. escape(toolshed.t("name")) .. '</div><div class="num">' .. escape(toolshed.t("cpu")) ..
'</div><div class="num">' .. escape(toolshed.t("memory")) .. '</div><div class="num">' .. escape(toolshed.t("net-in-out")) ..
"</div><div>" .. escape(toolshed.t("ports")) .. "</div></div>"
-- A project's folder has a line of its own: in its line it would crowd out the name.
local home = os.getenv("HOME") or ""
local place = (folder and folder ~= "") and ('<div class="note" data-tint="gray">' .. tile("folder", true) .. "<span>" ..
escape(home ~= "" and folder:sub(1, #home) == home and ("~" .. folder:sub(#home + 1)) or folder) .. "</span></div>") or ""
return {
html = page(top .. place .. '<div style="--columns: ' .. columns .. '">' .. head .. table.concat(lines) .. "</div>"),
jigs = jigs, refresh = measured and 3 or 1,
}
end
-- Each prune's title and question are in locales/, under its key.
local prunes = {
{ key = "containers", args = { "container", "prune", "-f" } },
{ key = "dangling", args = { "image", "prune", "-f" } },
{ key = "images", args = { "image", "prune", "-a", "-f" } },
{ key = "volumes", args = { "volume", "prune", "-a", "-f" } },
{ key = "cache", args = { "builder", "prune", "-f" } },
{ key = "everything", args = { "system", "prune", "-f" } },
}
-- The kinds of space docker system df reports, each a jig whose Enter runs its own prune; ⌘K
-- offers the others that fit it, and Everything, which covers them all.
local kinds = {
["Images"] = { key = "images", icon = "layers", prunes = { "dangling", "images" } },
["Containers"] = { key = "containers", icon = "container", prunes = { "containers" } },
["Local Volumes"] = { key = "volumes", icon = "hard-drive", prunes = { "volumes" } },
["Build Cache"] = { key = "cache", icon = "boxes", prunes = { "cache" } },
}
local show_space = {
{
key = "show", title = "i18n:action.prune.show", icon = "hard-drive",
run = function(ctx)
local dangling = dangling_images(ctx.settings)
-- What Everything frees: stopped containers, dangling images and the build cache. Unused
-- networks take no space to speak of.
local everything = dangling
local jigs = {}
for _, d in ipairs(json_lines(run(ctx.settings, "system", "df", "--format", "{{json .}}"))) do
local kind = kinds[d.Type]
if kind then
local actions = { unpack(kind.prunes) }
table.insert(actions, "everything")
-- Only what its prunes would remove: what stays isn't the question here.
local reclaimable = bytes(d.Reclaimable)
local unused = (tonumber(d.TotalCount) or 0) - (tonumber(d.Active) or 0)
local freed
if d.Type == "Images" then
-- df counts every unused image; Enter on Images prunes only the dangling ones.
freed = (dangling + reclaimable > 0) and toolshed.t("free-images", { dangling = decimal(dangling), unused = decimal(reclaimable) })
elseif reclaimable > 0 then
local counted = ({ ["Containers"] = "free-stopped", ["Local Volumes"] = "free-unused" })[d.Type] or "free"
freed = toolshed.t(counted, { count = unused, size = decimal(reclaimable) })
end
if d.Type == "Containers" or d.Type == "Build Cache" then everything = everything + reclaimable end
table.insert(jigs, {
title = toolshed.t("kind." .. kind.key), icon = kind.icon, tool = "space", action = kind.prunes[1], actions = actions,
subtitle = freed or toolshed.t("nothing-to-free"),
})
end
end
table.insert(jigs, 1, {
title = toolshed.t("kind.everything"), icon = "eraser", tool = "space", action = "everything", actions = { "everything" },
subtitle = toolshed.t("free-everything", { size = decimal(everything) }),
})
return { jigs = jigs }
end,
},
}
local function prune_action(p)
return {
key = p.key, title = "i18n:action.space." .. p.key, icon = "eraser", confirm = "i18n:confirm.space." .. p.key, never_default = true,
run = function(ctx)
local out = run(ctx.settings, unpack(p.args))
local freed = out:match("Total reclaimed space:%s*([^\n]+)") or "0B"
return toolshed.t("freed", { size = freed })
end,
}
end
-- The prunes are the actions of a kind of space, not of Docker Prune, which shows them.
local prune_actions = {}
for _, p in ipairs(prunes) do table.insert(prune_actions, prune_action(p)) end
return toolshed.toolbox {
key = "docker",
title = "Docker",
description = "i18n:toolbox.description",
icon = "container",
tint = "blue",
settings = {
{ key = "command", title = "i18n:setting.command.title", description = "i18n:setting.command.description",
type = "text", default = "docker", placeholder = "docker" },
},
requires = { { command = "docker", setting = "command" } },
tools = {
{
key = "containers",
title = "Docker",
description = "i18n:tool.containers.description",
words = { "docker" },
examples = { "docker", "docker web" },
keywords = { "containers", "compose", "containere" },
items = true,
search = function(rest, settings)
local ok, list = pcall(containers, settings)
if not ok then return { unavailable(list) } end
local jigs = {}
for _, p in ipairs(projects(list)) do
if toolshed.match(rest, p.name) > 0 then table.insert(jigs, project_jig(p)) end
end
for _, c in ipairs(list) do
local text = table.concat({ c.name, c.image, c.project or "", c.service or "" }, " ")
-- Without a search, a project's containers are found inside it rather than listed again.
if (rest ~= "" or not c.project) and toolshed.match(rest, text) > 0 then
table.insert(jigs, container_jig(c))
end
end
return jigs
end,
actions = {
{
key = "details", title = "i18n:action.containers.details", icon = "info",
run = function(ctx)
local c = find(ctx.settings, ctx.data.id)
local running = c.state == "running"
local s, at
if running then
local by, _, measured_at = latest_stats(ctx.settings)
s, at = by[c.id], measured_at
end
local top = ""
if running then
local cpu, memory, network = remember("cpu:" .. c.id), remember("memory:" .. c.id), rates("net:" .. c.id)
top = figures({
{ toolshed.t("cpu"), s and escape(s.CPUPerc) or "…", "cpu", "blue", cpu, from_zero = true },
{ toolshed.t("memory"), s and size(bytes(s.MemUsage)) or "…", "memory-stick", "purple", memory },
{ toolshed.t("network"), #network > 0 and (decimal(network[#network]) .. "/s") or "…", "network", "teal", network, from_zero = true },
})
end
local function card(title, icon, tint, facts, wide)
local rows = {}
for _, f in ipairs(facts) do table.insert(rows, "<dt>" .. escape(toolshed.t(f[1])) .. "</dt><dd>" .. f[2] .. "</dd>") end
return '<div class="card' .. (wide and " wide" or "") .. '" data-tint="' .. tint .. '"><div class="card-head">' ..
tile(icon, true) .. escape(toolshed.t(title)) .. '</div><dl class="kv">' .. table.concat(rows) .. "</dl></div>"
end
local long = function(text) return '<span class="ellipsis" title="' .. escape(text) .. '">' .. escape(text) .. "</span>" end
local split_io = function(text) return (text or ""):match("^(.-)%s*/%s*(.-)$") end
-- Titles and labels are keys in locales/.
local cards = { card("container", "info", "gray", {
{ "state", dot(c.state) .. escape(c.status) }, { "image", long(c.image) }, { "id", escape(c.id) },
}, not c.project) }
if c.project then
table.insert(cards, card("compose", "boxes", "orange", { { "project", escape(c.project) }, { "service", escape(c.service or "") } }))
end
local received, sent = split_io(s and s.NetIO)
local net = { { "ports", #c.ports > 0 and escape(ports_text(c)) or escape(toolshed.t("none-published")) } }
if s then
table.insert(net, { "received", escape(received) })
table.insert(net, { "sent", escape(sent) })
end
table.insert(cards, card("network", "network", "teal", net, not s))
if s then
local read, written = split_io(s.BlockIO)
table.insert(cards, card("storage", "hard-drive", "yellow", { { "read", escape(read) }, { "written", escape(written) } }))
end
-- What to do with the container is in ⌘K: a page without jigs of its own is about the
-- jig that opened it.
return {
html = page(top .. '<div class="cards">' .. table.concat(cards) .. "</div>"),
refresh = (running and not s) and 1 or 5,
}
end,
},
{
key = "logs", title = "i18n:action.containers.logs", icon = "scroll-text",
run = function(ctx)
-- Containers log to stderr as often as stdout, so both are read.
local text = toolshed.exec({ "sh", "-c", '"$0" logs --tail 200 "$1" 2>&1', docker(ctx.settings), ctx.data.id })
return { html = logs_page(ctx.data.name, text), refresh = 2 }
end,
},
{
key = "open-port", title = "i18n:action.containers.open-port", icon = "external-link",
run = function(ctx)
local c = find(ctx.settings, ctx.data.id)
if #c.ports == 0 then error(toolshed.t("no-ports", { name = c.name })) end
if #c.ports == 1 then
toolshed.open("http://localhost:" .. c.ports[1].host)
return
end
return { jigs = port_jigs(c) }
end,
},
{
key = "shell", title = "i18n:action.containers.shell", icon = "terminal",
run = function(ctx)
in_terminal("shell-" .. ctx.data.name, quoted(docker(ctx.settings)) .. " exec -it " .. quoted(ctx.data.id) ..
" sh -c 'command -v bash >/dev/null && exec bash || exec sh'")
end,
},
{
key = "follow-logs", title = "i18n:action.containers.follow-logs", icon = "scroll-text",
run = function(ctx)
in_terminal("logs-" .. ctx.data.name, quoted(docker(ctx.settings)) .. " logs -f --tail 100 " .. quoted(ctx.data.id))
end,
},
{ key = "start", title = "i18n:action.containers.start", icon = "play", run = function(ctx) run(ctx.settings, "start", ctx.data.id); return toolshed.t("started", { name = ctx.data.name }) end },
{ key = "stop", title = "i18n:action.containers.stop", icon = "square", run = function(ctx) run(ctx.settings, "stop", ctx.data.id); return toolshed.t("stopped", { name = ctx.data.name }) end },
{ key = "restart", title = "i18n:action.containers.restart", icon = "rotate-cw", run = function(ctx) run(ctx.settings, "restart", ctx.data.id); return toolshed.t("restarted", { name = ctx.data.name }) end },
{
key = "remove", title = "i18n:action.containers.remove", icon = "trash-2", never_default = true,
confirm = "i18n:confirm.containers.remove",
run = function(ctx) run(ctx.settings, "rm", "-f", ctx.data.id); return toolshed.t("removed", { name = ctx.data.name }) end,
},
{
key = "copy-id", title = "i18n:action.containers.copy-id", icon = "copy",
run = function(ctx) toolshed.clipboard.copy(ctx.data.id); return toolshed.t("copied", { text = ctx.data.id }) end,
},
},
},
{
key = "project",
title = "i18n:tool.project.title",
hidden = true,
items = true,
actions = {
{
key = "details", title = "i18n:action.project.details", icon = "boxes",
run = function(ctx)
local list = {}
for _, c in ipairs(containers(ctx.settings)) do
if c.project == ctx.data.name then table.insert(list, c) end
end
-- Its figures' lines add up what its containers did, measurement by measurement.
local function summed(what)
local out = {}
for _, c in ipairs(list) do
local values = remember(what .. ":" .. c.id)
for i = 1, #values do
local at = #out - #values + i
if at < 1 then table.insert(out, 1, 0); at = 1 end
out[at] = out[at] + values[i]
end
end
return out
end
return overview(list, ctx.settings, summed("cpu"), summed("memory"), ctx.data.name)
end,
},
{
key = "logs", title = "i18n:action.project.logs", icon = "scroll-text",
run = function(ctx)
local text = toolshed.exec({ "sh", "-c", '"$0" compose -p "$1" logs --tail 200 --no-color 2>&1', docker(ctx.settings), ctx.data.name })
return { html = logs_page(ctx.data.name, text), refresh = 2 }
end,
},
{
key = "up", title = "i18n:action.project.up", icon = "play",
run = function(ctx)
if not ctx.data.folder or ctx.data.folder == "" then error(toolshed.t("no-folder", { name = ctx.data.name })) end
local said = toolshed.t("starting", { name = ctx.data.name })
in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "--project-directory", ctx.data.folder, "up", "-d")
return said
end,
},
{
key = "restart", title = "i18n:action.project.restart", icon = "rotate-cw",
run = function(ctx)
local said = toolshed.t("restarting", { name = ctx.data.name })
in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "restart")
return said
end,
},
{
key = "down", title = "i18n:action.project.down", icon = "square", never_default = true,
confirm = "i18n:confirm.project.down",
run = function(ctx)
local said = toolshed.t("taking-down", { name = ctx.data.name })
in_background(ctx.settings, compose_key(ctx.data.name), said, "compose", "-p", ctx.data.name, "down")
return said
end,
},
{
key = "open-folder", title = "i18n:action.project.open-folder", icon = "folder-open",
run = function(ctx)
if not ctx.data.folder or ctx.data.folder == "" then error(toolshed.t("no-folder", { name = ctx.data.name })) end
toolshed.open(ctx.data.folder)
end,
},
{
key = "copy-name", title = "i18n:action.project.copy-name", icon = "copy",
run = function(ctx) toolshed.clipboard.copy(ctx.data.name); return toolshed.t("copied", { text = ctx.data.name }) end,
},
},
},
{
key = "port",
title = "i18n:tool.port.title",
hidden = true,
items = true,
actions = {
{ key = "open", title = "i18n:action.port.open", icon = "external-link", run = function(ctx) toolshed.open("http://localhost:" .. ctx.data.port) end },
{
key = "copy-address", title = "i18n:action.port.copy-address", icon = "copy",
run = function(ctx)
toolshed.clipboard.copy("http://localhost:" .. ctx.data.port)
return toolshed.t("copied", { text = "localhost:" .. ctx.data.port })
end,
},
},
},
{
key = "desktop",
title = "Docker Desktop",
hidden = true,
actions = {
{ key = "open", title = "i18n:action.desktop.open", icon = "container", run = function() toolshed.exec({ "open", "-a", "Docker" }) end },
},
},
{
key = "dashboard",
title = "i18n:tool.dashboard.title",
description = "i18n:tool.dashboard.description",
icon = "gauge",
keywords = { "docker", "containers", "stats", "cpu", "memory", "usage", "overview", "oversikt", "minne" },
actions = {
{
key = "show", title = "i18n:action.dashboard.show", icon = "gauge",
run = function(ctx)
local ok, list = pcall(containers, ctx.settings)
if not ok then return { jigs = { unavailable(list) } } end
return overview(list, ctx.settings, remember("cpu"), remember("memory"))
end,
},
},
},
{
key = "prune",
title = "i18n:tool.prune.title",
description = "i18n:tool.prune.description",
icon = "eraser",
keywords = { "docker", "clean", "space", "disk", "remove", "rydd", "plass" },
actions = show_space,
},
{
key = "space",
title = "i18n:tool.space.title",
hidden = true,
items = true,
actions = prune_actions,
},
},
}