Système d’orchestration Docker en Lua via API HTTP, gestion des conteneurs avec serveur RESTful, idéal pour environnements embarqués et serveurs légers.
-- Docker container orchestration system via HTTP API using Lua
-- Requirements: Lua 5.3+, luasocket, lua-cjson
local socket = require("socket")
local unix = require("socket.unix")
local cjson = require("cjson.safe")
-- Docker socket path
local DOCKER_SOCKET_PATH = "/var/run/docker.sock"
-- Function to send HTTP requests over Unix socket (Docker API)
local function http_request_unix_socket(method, path, body, headers)
headers = headers or {}
body = body or ""
-- Create Unix socket
local client, err = unix() -- socket.unix()
if not client then return nil, "Impossible de créer la socket Unix : " .. tostring(err) end
local ok, err = client:connect(DOCKER_SOCKET_PATH)
if not ok then return nil, "Impossible de se connecter à la socket Docker : " .. tostring(err) end
-- Build HTTP request
local request_lines = {}
table.insert(request_lines, string.format("%s %s HTTP/1.1", method, path))
table.insert(request_lines, "Host: localhost")
table.insert(request_lines, "User-Agent: lua-docker-client/1.0")
if body ~= "" then
headers["Content-Length"] = #body
headers["Content-Type"] = headers["Content-Type"] or "application/json"
end
for k,v in pairs(headers) do
table.insert(request_lines, string.format("%s: %s", k, v))
end
table.insert(request_lines, "Connection: close")
table.insert(request_lines, "") -- empty line
table.insert(request_lines, body)
local request_str = table.concat(request_lines, "\r\n")
-- Send request
local bytes_sent, err = client:send(request_str)
if not bytes_sent then
client:close()
return nil, "Erreur envoi requête : " .. tostring(err)
end
-- Read response
local response = ""
while true do
local chunk, err, partial = client:receive(1024)
if chunk then
response = response .. chunk
elseif partial and #partial > 0 then
response = response .. partial
end
if err == "closed" then break end
if err and err ~= "timeout" and err ~= "closed" then
client:close()
return nil, "Erreur réception réponse : " .. tostring(err)
end
end
client:close()
-- Parse HTTP response
local header_end = response:find("\r\n\r\n")
if not header_end then
return nil, "Réponse HTTP mal formée"
end
local header_str = response:sub(1, header_end)
local body_str = response:sub(header_end + 4)
-- Extract status code
local status_line = header_str:match("HTTP/%d%.%d (%d%d%d) .-\r\n")
local status_code = tonumber(status_line) or 0
return {
status = status_code,
headers = header_str,
body = body_str
}
end
-- Functions to interact with Docker API
-- List containers (optional: all=true for all, false for running only)
local function docker_list_containers(all)
local path = "/containers/json"
if all then
path = path .. "?all=true"
end
local res, err = http_request_unix_socket("GET", path)
if not res then return nil, err end
if res.status ~= 200 then return nil, "Erreur Docker API : " .. tostring(res.status) end
local data, err = cjson.decode(res.body)
if not data then return nil, "Erreur parsing JSON : " .. tostring(err) end
return data
end
-- Start container given ID or name
local function docker_start_container(container_id)
local path = string.format("/containers/%s/start", container_id)
local res, err = http_request_unix_socket("POST", path)
if not res then return false, err end
if res.status == 204 then
return true
else
return false, "Erreur Docker API : " .. tostring(res.status) .. " " .. res.body
end
end
-- Stop container given ID or name
local function docker_stop_container(container_id)
local path = string.format("/containers/%s/stop", container_id)
local res, err = http_request_unix_socket("POST", path)
if not res then return false, err end
if res.status == 204 then
return true
else
return false, "Erreur Docker API : " .. tostring(res.status) .. " " .. res.body
end
end
-- Remove container given ID or name
local function docker_remove_container(container_id)
local path = string.format("/containers/%s", container_id)
local res, err = http_request_unix_socket("DELETE", path)
if not res then return false, err end
if res.status == 204 then
return true
else
return false, "Erreur Docker API : " .. tostring(res.status) .. " " .. res.body
end
end
-- Minimal HTTP server for orchestration
local function start_http_server(port)
local server = assert(socket.bind("0.0.0.0", port))
print(string.format("Serveur HTTP Docker Orchestrator à l'écoute sur le port %d", port))
while true do
local client = server:accept()
client:settimeout(5)
local request_line, err = client:receive()
if not request_line then
client:close()
goto continue
end
-- Parse request line
local method, path, http_version = request_line:match("^(%w+) (.-) HTTP/(%d%.%d)$")
if not method or not path then
client:send("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n")
client:close()
goto continue
end
-- Read headers (not used in this example, but read for completeness)
local headers = {}
while true do
local line, err = client:receive()
if not line or line == "" then break end
local k,v = line:match("^(.-):%s*(.*)$")
if k and v then headers[k:lower()] = v end
end
-- Endpoint handling
local response_body = ""
local response_code = 200
local response_headers = { ["Content-Type"] = "application/json" }
if method == "GET" and path == "/containers" then
local containers, err = docker_list_containers(true)
if containers then
response_body = cjson.encode(containers)
else
response_code = 500
response_body = cjson.encode({ error = err })
end
elseif method == "POST" then
-- Parse body (simple, assumes Content-Length and JSON)
local content_length = tonumber(headers["content-length"] or "0")
local body = ""
if content_length > 0 then
body = client:receive(content_length) or ""
end
local data = cjson.decode(body) or {}
-- /containers/start {"id":"container_id"}
if path == "/containers/start" then
if not data.id then
response_code = 400
response_body = cjson.encode({ error = "Champ 'id' manquant" })
else
local ok, err = docker_start_container(data.id)
if ok then
response_body = cjson.encode({ status = "started", id = data.id })
else
response_code = 500
response_body = cjson.encode({ error = err })
end
end
-- /containers/stop {"id":"container_id"}
elseif path == "/containers/stop" then
if not data.id then
response_code = 400
response_body = cjson.encode({ error = "Champ 'id' manquant" })
else
local ok, err = docker_stop_container(data.id)
if ok then
response_body = cjson.encode({ status = "stopped", id = data.id })
else
response_code = 500
response_body = cjson.encode({ error = err })
end
end
-- /containers/remove {"id":"container_id"}
elseif path == "/containers/remove" then
if not data.id then
response_code = 400
response_body = cjson.encode({ error = "Champ 'id' manquant" })
else
local ok, err = docker_remove_container(data.id)
if ok then
response_body = cjson.encode({ status = "removed", id = data.id })
else
response_code = 500
response_body = cjson.encode({ error = err })
end
end
else
response_code = 404
response_body = cjson.encode({ error = "Endpoint non trouvé" })
end
else
response_code = 405
response_body = cjson.encode({ error = "Méthode HTTP non supportée" })
end
-- Send response
local status_messages = {
[200] = "OK",
[400] = "Bad Request",
[404] = "Not Found",
[405] = "Method Not Allowed",
[500] = "Internal Server Error"
}
local status_message = status_messages[response_code] or "OK"
local response_lines = {}
table.insert(response_lines, string.format("HTTP/1.1 %d %s", response_code, status_message))
table.insert(response_lines, string.format("Content-Length: %d", #response_body))
for k,v in pairs(response_headers) do
table.insert(response_lines, string.format("%s: %s", k, v))
end
table.insert(response_lines, "Connection: close")
table.insert(response_lines, "")
table.insert(response_lines, response_body)
local response_str = table.concat(response_lines, "\r\n")
client:send(response_str)
client:close()
::continue::
end
end
-- Start server on port 8080
start_http_server(8080)Matériel : PC ou serveur avec Docker Engine installé et accès à la socket Docker (typiquement /var/run/docker.sock).
Logiciel : Docker Engine (version 20.10+), Lua 5.3+.
Bibliothèques Lua : luasocket (pour client et serveur HTTP), cjson (pour parsing JSON), lua-http (alternative optionnelle pour client/serveur HTTP).
Configuration Docker : activer l'accès à la socket Unix /var/run/docker.sock pour le processus Lua (permissions lecture/écriture).
Configuration Lua : installer les bibliothèques via LuaRocks (ex. luarocks install luasocket, luarocks install lua-cjson).
Pinout/Câblage : non applicable (logiciel pur).
Configuration réseau : le serveur Lua expose un endpoint HTTP (ex. port 8080) pour recevoir des commandes REST.
Connexions : le client HTTP interne de Lua communique avec Docker via la socket Unix /var/run/docker.sock en utilisant HTTP over Unix socket.