Initial upload

This commit is contained in:
antonn committed 2026-06-10 17:04:11 +00:00
1 parent b0bf3b7167
commit a022f29e34
65 files changed
+46484 -4339

No files matched your search

+249 -3
View File
@@ -1,6 +1,7 @@
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
@@ -95,6 +96,22 @@ type dockerPullProgress struct {
Error string `json:"error"`
}
type dockerAttachOptions struct {
Stdin bool
Stdout bool
Stderr bool
Logs bool
}
type dockerHijackedConn struct {
net.Conn
reader *bufio.Reader
}
func (c *dockerHijackedConn) Read(p []byte) (int, error) {
return c.reader.Read(p)
}
type dockerImageInspectConfig struct {
Entrypoint []string `json:"Entrypoint"`
Cmd []string `json:"Cmd"`
@@ -232,6 +249,80 @@ func (d Docker) engineRequest(ctx context.Context, method, rawPath string, query
return respBody, resp.StatusCode, nil
}
func (d Docker) attachContainerAPI(ctx context.Context, name string, opts dockerAttachOptions) (io.ReadWriteCloser, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return nil, fmt.Errorf("missing container name")
}
if !opts.Stdin && !opts.Stdout && !opts.Stderr {
return nil, fmt.Errorf("no attach streams requested")
}
var dialer net.Dialer
conn, err := dialer.DialContext(ctx, "unix", dockerEngineSocketPath)
if err != nil {
return nil, err
}
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
query := url.Values{}
query.Set("stream", "1")
if opts.Stdin {
query.Set("stdin", "1")
}
if opts.Stdout {
query.Set("stdout", "1")
}
if opts.Stderr {
query.Set("stderr", "1")
}
if opts.Logs {
query.Set("logs", "1")
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
"http://docker"+dockerAPIPath("/containers/"+url.PathEscape(dockerName)+"/attach", query),
nil,
)
if err != nil {
_ = conn.Close()
return nil, err
}
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "tcp")
if err := req.Write(conn); err != nil {
_ = conn.Close()
return nil, err
}
reader := bufio.NewReader(conn)
resp, err := http.ReadResponse(reader, req)
if err != nil {
_ = conn.Close()
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK {
detail := ""
if resp.Body != nil {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
detail = decodeDockerAPIError(body)
}
_ = conn.Close()
if detail == "" {
detail = resp.Status
}
return nil, fmt.Errorf("failed to attach container %s: %s", dockerName, detail)
}
_ = conn.SetDeadline(time.Time{})
return &dockerHijackedConn{Conn: conn, reader: reader}, nil
}
func splitDockerImageRef(ref string) (string, string) {
clean := strings.TrimSpace(ref)
if clean == "" {
@@ -249,6 +340,47 @@ func splitDockerImageRef(ref string) (string, string) {
}
func (d Docker) pullImageAPI(ctx context.Context, ref string) error {
var lastErr error
for attempt := 1; attempt <= 3; attempt++ {
err := d.pullImageAPIOnce(ctx, ref)
if err == nil {
return nil
}
lastErr = err
if ctx.Err() != nil || !isTransientDockerPullError(err) || attempt == 3 {
break
}
delay := time.Duration(attempt*attempt) * time.Second
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
return lastErr
}
func (d Docker) ensureImageAvailableAPI(ctx context.Context, ref string) error {
imageRef := strings.TrimSpace(ref)
if imageRef == "" {
return fmt.Errorf("missing image reference")
}
if d.imageExistsLocally(ctx, imageRef) {
return nil
}
if err := d.pullImageAPI(ctx, imageRef); err != nil {
if isTransientDockerPullError(err) && d.imageExistsLocally(ctx, imageRef) {
fmt.Printf("[docker] pull failed for %s with transient error, using cached image: %v\n", imageRef, err)
return nil
}
return err
}
return nil
}
func (d Docker) pullImageAPIOnce(ctx context.Context, ref string) error {
image, tag := splitDockerImageRef(ref)
if image == "" {
return fmt.Errorf("missing image reference")
@@ -290,12 +422,63 @@ func (d Docker) pullImageAPI(ctx context.Context, ref string) error {
return nil
}
func isTransientDockerPullError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
nonTransient := []string{
"manifest unknown",
"not found",
"pull access denied",
"repository does not exist",
"requested access to the resource is denied",
"unauthorized",
"authentication required",
"invalid reference format",
}
for _, marker := range nonTransient {
if strings.Contains(msg, marker) {
return false
}
}
transient := []string{
"tls: bad record mac",
"unexpected eof",
"connection reset",
"connection refused",
"connection timed out",
"i/o timeout",
"net/http",
"httpreadseeker",
"failed to copy",
"failed to do request",
"tls handshake timeout",
"temporary failure",
"503",
"502",
"504",
"too many requests",
}
for _, marker := range transient {
if strings.Contains(msg, marker) {
return true
}
}
return false
}
func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{}
query.Set("v", "1")
if force {
query.Set("force", "1")
}
body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(name), query, nil)
body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(dockerName), query, nil)
if err != nil {
return err
}
@@ -303,11 +486,74 @@ func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool)
return nil
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to remove container %s: %s", name, decodeDockerAPIError(body))
return fmt.Errorf("failed to remove container %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) killContainerAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{}
query.Set("signal", "SIGKILL")
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/kill", query, nil)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status == http.StatusConflict {
msg := strings.ToLower(decodeDockerAPIError(body))
if strings.Contains(msg, "not running") || strings.Contains(msg, "is not running") {
return nil
}
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to kill container %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) updateRestartNoAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
req := dockerHostConfig{RestartPolicy: dockerRestartPolicy{Name: "no"}}
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/update", nil, req)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to disable restart policy for %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) containerExistsAPI(ctx context.Context, name string) (bool, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return false, fmt.Errorf("missing container name")
}
body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil)
if err != nil {
return false, err
}
if status == http.StatusNotFound {
return false, nil
}
if status < 200 || status >= 300 {
return false, fmt.Errorf("failed to inspect container %s: %s", dockerName, decodeDockerAPIError(body))
}
return true, nil
}
func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) {
query := url.Values{}
query.Set("name", name)
@@ -362,7 +608,7 @@ func (d Docker) runContainerAPI(ctx context.Context, name string, req dockerCont
removeCancel()
pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute)
if err := d.pullImageAPI(pullCtx, req.Image); err != nil {
if err := d.ensureImageAvailableAPI(pullCtx, req.Image); err != nil {
pullCancel()
return err
}