feat: Docker container checks
ci / build (pull_request) Successful in 5m21s
ci / image (pull_request) Successful in 6m43s
ci / lint (pull_request) Successful in 10m3s
ci / test (pull_request) Successful in 12m5s

A Docker monitor asks the Docker Engine API for a container's state: up
while it runs and its health check, if any, is not unhealthy; exited,
paused or missing containers are reported as such. The API is reached
over the checker host's Unix socket, allowed only on checkers that may
see private networks, or over plain TCP through the network guard. The
README lists all check types and notification services and explains
mounting the socket.

Closes #97

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 17:03:50 +01:00
1 parent 36301ed146
commit 0b7f48a609
12 files changed
+1474 -1202

No files matched your search

+2 -1
View File
@@ -34,7 +34,7 @@ const (
)
// Types lists every check type.
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, GRPC, SMTP, RADIUS, SNMP, Steam, Minecraft, Heartbeat, Alertmanager}
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, GRPC, SMTP, RADIUS, SNMP, Steam, Minecraft, Docker, Heartbeat, Alertmanager}
// Passive reports whether t is reported to us rather than run by checkers.
func Passive(t Type) bool { return t == Heartbeat || t == Alertmanager }
@@ -111,6 +111,7 @@ var impls = map[Type]impl{
SNMP: snmpCheck{},
Steam: gameCheck{Steam},
Minecraft: gameCheck{Minecraft},
Docker: dockerCheck{},
Heartbeat: heartbeatCheck{},
Alertmanager: alertmanagerCheck{},
}
+124
View File
@@ -0,0 +1,124 @@
package check
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
)
// Docker checks a container through the Docker Engine API.
const Docker Type = "docker"
// DefaultDockerHost is the checker's own Docker socket.
const DefaultDockerHost = "unix:///var/run/docker.sock"
// DockerConfig configures a container check; the target is the container
// name or ID.
type DockerConfig struct {
// Host is a Unix socket ("unix:///var/run/docker.sock") or a plain
// TCP endpoint ("tcp://docker.internal:2375").
Host string `json:"host"`
}
var containerName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$`)
type dockerCheck struct{}
func (dockerCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
if !containerName.MatchString(target) {
return nil, invalid("invalid_target")
}
c := DockerConfig{Host: DefaultDockerHost}
if err := json.Unmarshal(config, &c); err != nil {
return nil, invalid("invalid_config")
}
if c.Host == "" {
c.Host = DefaultDockerHost
}
u, err := url.Parse(c.Host)
switch {
case err != nil:
return nil, invalid("invalid_config")
case u.Scheme == "unix" && u.Host == "" && strings.HasPrefix(u.Path, "/") && len(u.Path) < 200:
case u.Scheme == "tcp" && validHostPort(u.Host) && (u.Path == "" || u.Path == "/"):
default:
return nil, invalid("invalid_config")
}
return encode(c), nil
}
func (dockerCheck) run(ctx context.Context, s Spec) Outcome {
c, err := decode[DockerConfig](s.Config)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
u, err := url.Parse(c.Host)
if err != nil {
return Outcome{Error: "invalid configuration"}
}
d := netguard.Dialer(s.AllowPrivate, s.Timeout)
var dial func(ctx context.Context, _, _ string) (net.Conn, error)
if u.Scheme == "unix" {
// The socket controls the checker's own host; shared checkers
// may not use it.
if !s.AllowPrivate {
return Outcome{Error: "this checker does not allow Docker sockets"}
}
dial = func(ctx context.Context, _, _ string) (net.Conn, error) { return d.DialContext(ctx, "unix", u.Path) }
} else {
dial = func(ctx context.Context, _, _ string) (net.Conn, error) { return d.DialContext(ctx, "tcp", u.Host) }
}
client := &http.Client{Transport: &http.Transport{DialContext: dial, DisableKeepAlives: true}}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker/containers/"+url.PathEscape(s.Target)+"/json", nil)
resp, err := client.Do(req)
if err != nil {
var op *net.OpError
if errors.As(err, &op) {
return Outcome{Error: describeNetErr(op)}
}
return Outcome{Error: truncate(err.Error(), 300)}
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
switch {
case resp.StatusCode == http.StatusNotFound:
return Outcome{Error: "no container named " + s.Target}
case resp.StatusCode != http.StatusOK:
var e struct {
Message string `json:"message"`
}
_ = json.Unmarshal(body, &e)
return Outcome{Error: fmt.Sprintf("Docker API answered %d %s", resp.StatusCode, truncate(e.Message, 200))}
}
var info struct {
State struct {
Status string `json:"Status"`
ExitCode int `json:"ExitCode"`
Health *struct {
Status string `json:"Status"`
} `json:"Health"`
} `json:"State"`
}
if err := json.Unmarshal(body, &info); err != nil {
return Outcome{Error: "not a Docker API answer"}
}
st := info.State
switch {
case st.Status == "exited":
return Outcome{Error: fmt.Sprintf("container exited with code %d", st.ExitCode)}
case st.Status != "running":
return Outcome{Error: "container is " + st.Status}
case st.Health != nil && st.Health.Status == "unhealthy":
return Outcome{Error: "container is unhealthy"}
}
return Outcome{OK: true}
}
+90
View File
@@ -0,0 +1,90 @@
package check
import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
)
// dockerAPI serves container states like the Docker Engine API, on a Unix
// socket and on TCP.
func dockerAPI(t *testing.T) (socket, tcp string) {
states := map[string]any{
"web": map[string]any{"Status": "running"},
"api": map[string]any{"Status": "running", "Health": map[string]any{"Status": "healthy"}},
"worker": map[string]any{"Status": "running", "Health": map[string]any{"Status": "unhealthy"}},
"migrate": map[string]any{"Status": "exited", "ExitCode": 3},
"paused-1": map[string]any{"Status": "paused"},
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/containers/"), "/json")
st, ok := states[name]
if !ok {
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "No such container: " + name})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"Name": "/" + name, "State": st})
})
socket = filepath.Join(t.TempDir(), "docker.sock")
l, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewUnstartedServer(h)
srv.Listener = l
srv.Start()
t.Cleanup(srv.Close)
ts := httptest.NewServer(h)
t.Cleanup(ts.Close)
return socket, strings.TrimPrefix(ts.URL, "http://")
}
func TestDockerCheck(t *testing.T) {
socket, tcp := dockerAPI(t)
for _, host := range []string{"unix://" + socket, "tcp://" + tcp} {
cfg := `{"host":"` + host + `"}`
for target, want := range map[string]string{
"web": "",
"api": "",
"worker": "container is unhealthy",
"migrate": "container exited with code 3",
"paused-1": "container is paused",
"gone": "no container named gone",
} {
o := runShort(t, Docker, target, cfg)
if want == "" && !o.OK || want != "" && (o.OK || o.Error != want) {
t.Errorf("%s %s: %+v, want %q", host, target, o, want)
}
}
}
// Shared checkers may use neither their socket nor private addresses.
for _, host := range []string{"unix://" + socket, "tcp://" + tcp} {
c, _ := Validate(Docker, "web", []byte(`{"host":"`+host+`"}`))
if o := Run(t.Context(), Spec{Type: Docker, Target: "web", Timeout: 2 * time.Second, Config: c}); o.OK {
t.Errorf("%s reached by a shared checker", host)
}
}
}
func TestDockerValidate(t *testing.T) {
got, err := Validate(Docker, "web", []byte(`{}`))
if err != nil || string(got) != `{"host":"unix:///var/run/docker.sock"}` {
t.Errorf("default = %s, %v", got, err)
}
for _, tc := range []struct{ target, cfg string }{
{"../etc", `{}`},
{"web", `{"host":"http://docker:2375"}`},
{"web", `{"host":"tcp://docker"}`},
{"web", `{"host":"unix://relative.sock"}`},
} {
if _, err := Validate(Docker, tc.target, []byte(tc.cfg)); err == nil {
t.Errorf("Validate(%s, %s) accepted", tc.target, tc.cfg)
}
}
}