mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 12:24:44 +00:00
- Each worker and proxy pod gets a new name per generation (artex-w-<hash>-<6 hex>). Exec targets the exact pod of the task state, so an exec delayed at the API server fails with 404 instead of running in a replacement pod before that pod passed its network probes. - setupTask lists the task's pods by label and deletes every pod except the ones it keeps, with a UID precondition, before it creates new ones. Same-named pods are no longer deleted without an ownership check. - Recover adopts only pods whose name matches artex-[wp]-<32 hex>-<6 hex> and whose name, labels and task annotation agree. - podAlive returns an error for API failures. Only 404, a UID mismatch, a deletion timestamp, or a pod that is not running and ready count as dead. On other errors (a cancelled request too) the exec fails and the task's pods and policies stay. - waitPodReady fails fast on CrashLoopBackOff and on exited containers. - The deny probes print one token per outcome. Only timed out, refused or unroutable connections count as blocked. Any other result (missing timeout binary, failed fork, no API env) fails setup at once. - Probe output, stderr and HTTP client errors go to the runner log only. The returned errors are generic. A cancelled API request returns a cancellation error, not "runner unavailable". - Add fd20:ce::254/128 (GCE IPv6 metadata) to the never-reachable ranges. - Document that ARTEX_KUBE_CLUSTER_CIDRS must also list the API server endpoint addresses when they lie outside the cluster ranges (managed clusters). - Exec, Kill and Delete reject task IDs with surrounding whitespace. - go.mod: gopkg.in/yaml.v3 back to indirect (go mod tidy). - Test: a cancelled exec keeps the task. The scope and probe tests move to the test PR to stay inside the size limit.
386 lines
12 KiB
Go
386 lines
12 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
// Container names in the task pods of the Kubernetes backend.
|
|
const (
|
|
kubeWorkerName = "worker"
|
|
kubeProxyName = "egress-proxy"
|
|
)
|
|
|
|
// kubeClient is the minimal Kubernetes API client of the Kubernetes sandbox
|
|
// backend: JSON requests on one namespace and pods/exec over WebSocket, with the
|
|
// in-cluster service-account token (re-read on every request: bound tokens
|
|
// rotate).
|
|
type kubeClient struct {
|
|
apiServer string
|
|
tokenPath string
|
|
namespace string
|
|
plainHTTP bool // tests only: http:// API server
|
|
http *http.Client
|
|
tls *tls.Config
|
|
}
|
|
|
|
// newKubeClient builds a client for apiServer. An https:// server is verified
|
|
// against the CA in caPath. An http:// server is refused unless allowPlainHTTP
|
|
// (set only by tests): the token would travel in clear.
|
|
func newKubeClient(apiServer, tokenPath, caPath, namespace string, allowPlainHTTP bool) (*kubeClient, error) {
|
|
apiServer = strings.TrimRight(apiServer, "/")
|
|
tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
|
|
if !strings.HasPrefix(apiServer, "https://") && !allowPlainHTTP {
|
|
return nil, fmt.Errorf("kubernetes backend: API server %q must use https:// (the service-account token would be sent in clear)", apiServer)
|
|
}
|
|
if strings.HasPrefix(apiServer, "https://") {
|
|
ca, err := os.ReadFile(caPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", caPath, err)
|
|
}
|
|
pool := x509.NewCertPool()
|
|
if !pool.AppendCertsFromPEM(ca) {
|
|
return nil, fmt.Errorf("kubernetes backend: no certificates in %s", caPath)
|
|
}
|
|
tlsCfg.RootCAs = pool
|
|
}
|
|
return &kubeClient{
|
|
apiServer: apiServer,
|
|
tokenPath: tokenPath,
|
|
namespace: namespace,
|
|
plainHTTP: allowPlainHTTP && strings.HasPrefix(apiServer, "http://"),
|
|
tls: tlsCfg,
|
|
http: &http.Client{
|
|
Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg},
|
|
Timeout: 30 * time.Second,
|
|
// Never follow a redirect: it could carry the bearer token elsewhere.
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func (c *kubeClient) token() (string, error) {
|
|
raw, err := os.ReadFile(c.tokenPath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: read service account token: %v", ErrDockerUnavailable, err)
|
|
}
|
|
return strings.TrimSpace(string(raw)), nil
|
|
}
|
|
|
|
// kubeAPIError carries the HTTP status and the metav1.Status reason of a failed
|
|
// API call. The response body is never forwarded: it can echo object specs or
|
|
// exec commands.
|
|
type kubeAPIError struct {
|
|
Code int
|
|
Reason string
|
|
}
|
|
|
|
func (e *kubeAPIError) Error() string {
|
|
return fmt.Sprintf("kubernetes API HTTP %d %s", e.Code, e.Reason)
|
|
}
|
|
|
|
var kubeReasonRE = regexp.MustCompile(`^[A-Za-z]{1,64}$`)
|
|
|
|
func newKubeAPIError(code int, body io.Reader) (*kubeAPIError, string) {
|
|
raw, _ := io.ReadAll(io.LimitReader(body, 4096))
|
|
var st struct {
|
|
Reason string `json:"reason"`
|
|
}
|
|
_ = json.Unmarshal(raw, &st)
|
|
if !kubeReasonRE.MatchString(st.Reason) {
|
|
st.Reason = ""
|
|
}
|
|
return &kubeAPIError{Code: code, Reason: st.Reason}, string(raw)
|
|
}
|
|
|
|
func isKubeStatus(err error, code int) bool {
|
|
var ae *kubeAPIError
|
|
return errors.As(err, &ae) && ae.Code == code
|
|
}
|
|
|
|
func (c *kubeClient) do(ctx context.Context, method, apiPath string, body, out any) error {
|
|
var r io.Reader
|
|
if body != nil {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r = bytes.NewReader(raw)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, c.apiServer+apiPath, r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tok, err := c.token()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
req.Header.Set("Accept", "application/json")
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
// The error holds the API URL and namespace: log it, return a generic one.
|
|
if ctx.Err() != nil {
|
|
return fmt.Errorf("kubernetes API request cancelled: %w", ctx.Err())
|
|
}
|
|
log.Printf("[runner] kubernetes API %s %s: %v", method, apiPath, err)
|
|
return fmt.Errorf("%w: kubernetes API request failed", ErrDockerUnavailable)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode >= 300 {
|
|
ae, raw := newKubeAPIError(resp.StatusCode, resp.Body)
|
|
if ae.Code != http.StatusNotFound && ae.Code != http.StatusConflict {
|
|
log.Printf("[runner] kubernetes API %s %s: HTTP %d: %.512s", method, apiPath, ae.Code, raw)
|
|
}
|
|
return ae
|
|
}
|
|
if out != nil {
|
|
return json.NewDecoder(resp.Body).Decode(out)
|
|
}
|
|
_, _ = io.Copy(io.Discard, resp.Body)
|
|
return nil
|
|
}
|
|
|
|
func (c *kubeClient) nsPath(kind string) string {
|
|
switch kind {
|
|
case "networkpolicies":
|
|
return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(c.namespace) + "/networkpolicies"
|
|
default:
|
|
return "/api/v1/namespaces/" + url.PathEscape(c.namespace) + "/" + kind
|
|
}
|
|
}
|
|
|
|
func (c *kubeClient) create(ctx context.Context, kind string, obj, out any) error {
|
|
return c.do(ctx, http.MethodPost, c.nsPath(kind), obj, out)
|
|
}
|
|
|
|
// deleteObj deletes an object and reports whether it existed. Pods get a 1s
|
|
// grace, not 0: a zero grace force-removes the API object before the kubelet has
|
|
// stopped the containers, while with a grace the pod stays (terminating) until
|
|
// they are dead, so waiting for 404 proves its processes are gone. A non-empty
|
|
// uid makes the API server refuse (409) to delete a different object reusing the name.
|
|
func (c *kubeClient) deleteObj(ctx context.Context, kind, name, uid string) (bool, error) {
|
|
body := map[string]any{"propagationPolicy": "Background"}
|
|
if kind == "pods" {
|
|
body["gracePeriodSeconds"] = 1
|
|
}
|
|
if uid != "" {
|
|
body["preconditions"] = map[string]any{"uid": uid}
|
|
}
|
|
err := c.do(ctx, http.MethodDelete, c.nsPath(kind)+"/"+url.PathEscape(name), body, nil)
|
|
if isKubeStatus(err, http.StatusNotFound) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
}
|
|
|
|
type kubeObjectMeta struct {
|
|
Name string `json:"name"`
|
|
UID string `json:"uid,omitempty"`
|
|
ResourceVersion string `json:"resourceVersion,omitempty"`
|
|
Labels map[string]string `json:"labels"`
|
|
Annotations map[string]string `json:"annotations"`
|
|
Deletion *string `json:"deletionTimestamp,omitempty"`
|
|
}
|
|
|
|
type kubePod struct {
|
|
Metadata kubeObjectMeta `json:"metadata"`
|
|
Status struct {
|
|
Phase string `json:"phase"`
|
|
ContainerStatuses []struct {
|
|
Ready bool `json:"ready"`
|
|
State struct {
|
|
Waiting *struct {
|
|
Reason string `json:"reason"`
|
|
Message string `json:"message"`
|
|
} `json:"waiting"`
|
|
Terminated *struct {
|
|
Reason string `json:"reason"`
|
|
} `json:"terminated"`
|
|
} `json:"state"`
|
|
} `json:"containerStatuses"`
|
|
} `json:"status"`
|
|
}
|
|
|
|
func (c *kubeClient) getPod(ctx context.Context, name string) (*kubePod, error) {
|
|
var p kubePod
|
|
if err := c.do(ctx, http.MethodGet, c.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil {
|
|
return nil, err
|
|
}
|
|
return &p, nil
|
|
}
|
|
|
|
// kubeExecStatus is the metav1.Status sent on the exec error channel.
|
|
type kubeExecStatus struct {
|
|
Status string `json:"status"`
|
|
Reason string `json:"reason"`
|
|
Details struct {
|
|
Causes []struct {
|
|
Reason string `json:"reason"`
|
|
Message string `json:"message"`
|
|
} `json:"causes"`
|
|
} `json:"details"`
|
|
}
|
|
|
|
// cappedBuffer keeps the first max bytes written and records truncation.
|
|
type cappedBuffer struct {
|
|
buf bytes.Buffer
|
|
max int
|
|
truncated bool
|
|
}
|
|
|
|
func (c *cappedBuffer) Write(p []byte) {
|
|
rem := c.max - c.buf.Len()
|
|
if rem <= 0 {
|
|
if len(p) > 0 {
|
|
c.truncated = true
|
|
}
|
|
return
|
|
}
|
|
if len(p) > rem {
|
|
p = p[:rem]
|
|
c.truncated = true
|
|
}
|
|
c.buf.Write(p)
|
|
}
|
|
|
|
// kubeExecReadLimit caps one exec WebSocket message. The API server forwards
|
|
// output in frames of at most a few tens of KiB; a larger frame means a broken or
|
|
// hostile peer and fails the exec before its payload is read into memory.
|
|
const kubeExecReadLimit = 4 << 20
|
|
|
|
// podExec runs argv in the pod's worker container over the Kubernetes exec
|
|
// WebSocket (channel.k8s.io v5/v4) and returns stdout, stderr and the exit code.
|
|
func (c *kubeClient) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
|
|
return c.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes)
|
|
}
|
|
|
|
// containerExec runs argv over pods/exec. The API only takes the command as
|
|
// command= query parameters, so the URL carries argv (and the env(1) arguments):
|
|
// it is never put in an error or a log line, and API error bodies are dropped.
|
|
func (c *kubeClient) containerExec(ctx context.Context, pod, container string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
|
|
q := url.Values{}
|
|
q.Set("container", container)
|
|
q.Set("stdout", "true")
|
|
q.Set("stderr", "true")
|
|
for _, a := range argv {
|
|
q.Add("command", a)
|
|
}
|
|
u := "wss" + strings.TrimPrefix(c.apiServer, "https")
|
|
if c.plainHTTP && strings.HasPrefix(c.apiServer, "http://") {
|
|
u = "ws" + strings.TrimPrefix(c.apiServer, "http")
|
|
}
|
|
u += c.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode()
|
|
tok, err := c.token()
|
|
if err != nil {
|
|
return "", "", false, -1, err
|
|
}
|
|
dialer := websocket.Dialer{
|
|
Proxy: nil,
|
|
TLSClientConfig: c.tls,
|
|
HandshakeTimeout: 30 * time.Second,
|
|
Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"},
|
|
}
|
|
hdr := http.Header{}
|
|
hdr.Set("Authorization", "Bearer "+tok)
|
|
conn, resp, err := dialer.DialContext(ctx, u, hdr)
|
|
if err != nil {
|
|
if resp != nil {
|
|
ae, _ := newKubeAPIError(resp.StatusCode, resp.Body)
|
|
resp.Body.Close()
|
|
if ae.Code == http.StatusNotFound {
|
|
return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod)
|
|
}
|
|
return "", "", false, -1, ae
|
|
}
|
|
if ctx.Err() != nil {
|
|
return "", "", false, -1, ctx.Err()
|
|
}
|
|
return "", "", false, -1, fmt.Errorf("%w: exec dial to pod %s failed", ErrDockerUnavailable, pod)
|
|
}
|
|
defer conn.Close()
|
|
proto := conn.Subprotocol()
|
|
if proto != "v5.channel.k8s.io" && proto != "v4.channel.k8s.io" {
|
|
return "", "", false, -1, fmt.Errorf("exec: API server negotiated unsupported subprotocol %q", proto)
|
|
}
|
|
conn.SetReadLimit(kubeExecReadLimit)
|
|
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
|
|
defer stop()
|
|
|
|
out := &cappedBuffer{max: maxBytes}
|
|
errb := &cappedBuffer{max: maxBytes}
|
|
closed := map[byte]bool{}
|
|
var status *kubeExecStatus
|
|
for {
|
|
_, msg, rerr := conn.ReadMessage()
|
|
if rerr != nil {
|
|
if ctx.Err() != nil {
|
|
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, ctx.Err()
|
|
}
|
|
if errors.Is(rerr, websocket.ErrReadLimit) {
|
|
return "", "", false, -1, fmt.Errorf("exec: message larger than %d bytes", kubeExecReadLimit)
|
|
}
|
|
break
|
|
}
|
|
if len(msg) == 0 || closed[msg[0]] {
|
|
continue
|
|
}
|
|
switch msg[0] {
|
|
case 1:
|
|
out.Write(msg[1:])
|
|
case 2:
|
|
errb.Write(msg[1:])
|
|
case 3:
|
|
var st kubeExecStatus
|
|
if json.Unmarshal(msg[1:], &st) == nil {
|
|
status = &st
|
|
}
|
|
case 255: // v5 CLOSE: [255, stream]; that stream sends nothing more.
|
|
if proto == "v5.channel.k8s.io" && len(msg) == 2 {
|
|
closed[msg[1]] = true
|
|
}
|
|
}
|
|
}
|
|
res := func(code int, err error) (string, string, bool, int, error) {
|
|
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, code, err
|
|
}
|
|
switch {
|
|
case status == nil:
|
|
return res(-1, errors.New("exec stream ended without a status"))
|
|
case status.Status == "Success":
|
|
return res(0, nil)
|
|
case status.Reason == "NonZeroExitCode":
|
|
for _, c := range status.Details.Causes {
|
|
if n, perr := strconv.Atoi(c.Message); c.Reason == "ExitCode" && perr == nil {
|
|
return res(n, nil)
|
|
}
|
|
}
|
|
return res(-1, errors.New("exec failed without an exit code"))
|
|
}
|
|
// status.Message can quote the command: report only the reason.
|
|
reason := status.Reason
|
|
if !kubeReasonRE.MatchString(reason) {
|
|
reason = "unknown"
|
|
}
|
|
return res(-1, fmt.Errorf("exec failed: %s", reason))
|
|
}
|