This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const sourceLabel = "io.knowledge-governance.freeze-source"
|
||||
const environmentLabel = "io.knowledge-governance.environment"
|
||||
const roleLabel = "io.knowledge-governance.freeze-role"
|
||||
|
||||
type DockerController struct {
|
||||
source string
|
||||
timeout time.Duration
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
func NewDockerController(socket, source string, timeout time.Duration) (*DockerController, error) {
|
||||
if !filepath.IsAbs(socket) || !validID(source) || timeout <= 0 || timeout > 5*time.Minute {
|
||||
return nil, errors.New("invalid test Docker controller configuration")
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local Docker socket unavailable")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
client := &http.Client{Transport: transport, Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("Docker redirects prohibited") }}
|
||||
return &DockerController{source: source, timeout: timeout, client: client, transport: transport}, nil
|
||||
}
|
||||
func (d *DockerController) Close() { d.transport.CloseIdleConnections() }
|
||||
func (d *DockerController) request(ctx context.Context, method, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil)
|
||||
if err != nil {
|
||||
return errors.New("invalid Docker request")
|
||||
}
|
||||
resp, err := d.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("test Docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("test Docker request rejected")
|
||||
}
|
||||
if out != nil {
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
|
||||
if err != nil || len(data) > 1024*1024 || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid Docker response")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func dockerID(id string) bool {
|
||||
b, err := hex.DecodeString(id)
|
||||
return err == nil && len(b) == 32 && strings.ToLower(id) == id
|
||||
}
|
||||
|
||||
type dockerInspection struct {
|
||||
ID string `json:"Id"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
} `json:"Config"`
|
||||
State struct {
|
||||
Running bool
|
||||
Paused bool
|
||||
Restarting bool
|
||||
Dead bool
|
||||
Status string
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
}
|
||||
|
||||
func (d *DockerController) inspect(ctx context.Context, id string) (Service, error) {
|
||||
if !dockerID(id) {
|
||||
return Service{}, errors.New("immutable Docker ID required")
|
||||
}
|
||||
var data dockerInspection
|
||||
if err := d.request(ctx, "GET", "/containers/"+id+"/json", &data); err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
labels := data.Config.Labels
|
||||
if data.ID != id || labels[sourceLabel] != d.source || labels[environmentLabel] != "test" || labels[roleLabel] != "writer" {
|
||||
return Service{}, errors.New("container is not an approved test writer")
|
||||
}
|
||||
if data.State.Paused || data.State.Restarting || data.State.Dead {
|
||||
return Service{}, errors.New("test writer has unstable runtime state")
|
||||
}
|
||||
if data.State.Status != "running" && data.State.Status != "exited" && data.State.Status != "created" {
|
||||
return Service{}, errors.New("unknown test writer runtime state")
|
||||
}
|
||||
if data.State.Running != (data.State.Status == "running") {
|
||||
return Service{}, errors.New("contradictory test writer state")
|
||||
}
|
||||
healthy := data.State.Running && data.State.Health != nil && data.State.Health.Status == "healthy"
|
||||
return Service{ID: id, Running: data.State.Running, Healthy: healthy}, nil
|
||||
}
|
||||
func (d *DockerController) Inventory(ctx context.Context) ([]Service, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {sourceLabel + "=" + d.source}})
|
||||
var containers []struct {
|
||||
ID string `json:"Id"`
|
||||
}
|
||||
if err := d.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &containers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(containers) == 0 || len(containers) > 256 {
|
||||
return nil, errors.New("empty or oversized test writer group")
|
||||
}
|
||||
items := make([]Service, 0, len(containers))
|
||||
seen := map[string]bool{}
|
||||
for _, container := range containers {
|
||||
if seen[container.ID] {
|
||||
return nil, errors.New("duplicate Docker instance")
|
||||
}
|
||||
seen[container.ID] = true
|
||||
s, err := d.inspect(ctx, container.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, s)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
func (d *DockerController) wait(ctx context.Context, id string, running bool) error {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s, err := d.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Running == running && (!running || s.Healthy) {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("test writer state did not settle before deadline")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only SIGTERM is sent. There is no delayed SIGKILL timer which could fire after
|
||||
// recovery starts the service again. An unresolved graceful stop remains pending
|
||||
// in the coordinator journal; running-now is not evidence of recovery.
|
||||
func (d *DockerController) Stop(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, d.timeout)
|
||||
defer cancel()
|
||||
s, err := d.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
return nil
|
||||
}
|
||||
if err = d.request(bounded, "POST", "/containers/"+id+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.wait(bounded, id, false)
|
||||
}
|
||||
func (d *DockerController) Start(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, d.timeout)
|
||||
defer cancel()
|
||||
s, err := d.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
if err = d.request(bounded, "POST", "/containers/"+id+"/start", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return d.wait(bounded, id, true)
|
||||
}
|
||||
Reference in New Issue
Block a user