Merged
fix(cube): cap ExecSync output and harden cube-verify stop/quota (#67/#68/#70) #287
zhoudong01Add on 1 day ago
fix(cube): cap ExecSync output and harden cube-verify stop/quota (#67/#68/#70) #287
Merged
Total: 4 files changed+188-25
| @@ -47,18 +47,80 @@ cube_multiplex_ready() { | |||
| 47 | [[ -S "${SOCKET}" ]] | 47 | [[ -S "${SOCKET}" ]] |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | +# True only when argv0 is our cri-multiplex and cmdline mentions SOCKET. | ||
| 51 | +is_our_multiplex_pid() { | ||
| 52 | + local pid="$1" | ||
| 53 | + [[ -n "${pid}" && "${pid}" =~ ^[0-9]+$ ]] || return 1 | ||
| 54 | + [[ -r "/proc/${pid}/cmdline" ]] || return 1 | ||
| 55 | + local argv0 cmd base | ||
| 56 | + # First NUL-separated field is argv0 — do not match multiplex path only as an arg. | ||
| 57 | + argv0="$(tr '\0' '\n' <"/proc/${pid}/cmdline" 2>/dev/null | head -n1 || true)" | ||
| 58 | + [[ -n "${argv0}" ]] || return 1 | ||
| 59 | + base="$(basename -- "${MULTIPLEX_BIN}")" | ||
| 60 | + # basename -- avoids argv0 values like "-bash" being parsed as options. | ||
| 61 | + if [[ "${argv0}" != "${MULTIPLEX_BIN}" && "${argv0}" != "${base}" && "$(basename -- "${argv0}")" != "${base}" ]]; then | ||
| 62 | + return 1 | ||
| 63 | + fi | ||
| 64 | + cmd="$(tr '\0' ' ' <"/proc/${pid}/cmdline" 2>/dev/null || true)" | ||
| 65 | + [[ "${cmd}" == *"${SOCKET}"* ]] || return 1 | ||
| 66 | + return 0 | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +_kill_multiplex_pid() { | ||
| 70 | + local pid="$1" | ||
| 71 | + is_our_multiplex_pid "${pid}" || return 1 | ||
| 72 | + kill "${pid}" 2>/dev/null || true | ||
| 73 | + local i=0 | ||
| 74 | + while kill -0 "${pid}" 2>/dev/null && [[ $i -lt 50 ]]; do | ||
| 75 | + sleep 0.1 | ||
| 76 | + i=$((i + 1)) | ||
| 77 | + done | ||
| 78 | + if kill -0 "${pid}" 2>/dev/null; then | ||
| 79 | + kill -9 "${pid}" 2>/dev/null || true | ||
| 80 | + fi | ||
| 81 | + return 0 | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +_unix_socket_in_use() { | ||
| 85 | + local sock="$1" | ||
| 86 | + [[ -e "${sock}" ]] || return 1 | ||
| 87 | + # Prefer ss; fall back to fuser. Any hit means leave the path alone. | ||
| 88 | + if command -v ss >/dev/null 2>&1; then | ||
| 89 | + ss -xlH 2>/dev/null | grep -Fq -- "${sock}" && return 0 | ||
| 90 | + fi | ||
| 91 | + if command -v fuser >/dev/null 2>&1; then | ||
| 92 | + fuser "${sock}" >/dev/null 2>&1 && return 0 | ||
| 93 | + fi | ||
| 94 | + return 1 | ||
| 95 | +} | ||
| 96 | + | ||
| 50 | stop_cube_multiplex() { | 97 | stop_cube_multiplex() { |
| 98 | + local pid="" | ||
| 51 | if [[ -f "${PID_FILE}" ]]; then | 99 | if [[ -f "${PID_FILE}" ]]; then |
| 52 | - local pid | ||
| 53 | pid="$(cat "${PID_FILE}" 2>/dev/null || true)" | 100 | pid="$(cat "${PID_FILE}" 2>/dev/null || true)" |
| 54 | - if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then | 101 | + if [[ -n "${pid}" ]]; then |
| 55 | - kill "${pid}" 2>/dev/null || true | 102 | + if ! _kill_multiplex_pid "${pid}"; then |
| 56 | - wait "${pid}" 2>/dev/null || true | 103 | + log_info "skip kill pid=${pid}: not our cri-multiplex for ${SOCKET}" |
| 104 | + fi | ||
| 57 | fi | 105 | fi |
| 58 | rm -f "${PID_FILE}" | 106 | rm -f "${PID_FILE}" |
| 59 | fi | 107 | fi |
| 60 | - pkill -f "${MULTIPLEX_BIN} .*${SOCKET}" 2>/dev/null || true | 108 | + # No pkill -f: scan /proc and require binary+socket match (KASandbox #70). |
| 61 | - rm -f "${SOCKET}" "${ADMIN_SOCKET}" | 109 | + local proc |
| 110 | + for proc in /proc/[0-9]*; do | ||
| 111 | + pid="${proc#/proc/}" | ||
| 112 | + _kill_multiplex_pid "${pid}" || true | ||
| 113 | + done | ||
| 114 | + if _unix_socket_in_use "${SOCKET}"; then | ||
| 115 | + log_info "leave in-use socket ${SOCKET}" | ||
| 116 | + else | ||
| 117 | + rm -f "${SOCKET}" | ||
| 118 | + fi | ||
| 119 | + if _unix_socket_in_use "${ADMIN_SOCKET}"; then | ||
| 120 | + log_info "leave in-use socket ${ADMIN_SOCKET}" | ||
| 121 | + else | ||
| 122 | + rm -f "${ADMIN_SOCKET}" | ||
| 123 | + fi | ||
| 62 | } | 124 | } |
| 63 | 125 | ||
| 64 | build_multiplex() { | 126 | build_multiplex() { |
| @@ -18,6 +18,10 @@ | |||
| 18 | # ENSURE_OE_XFS=1 mount opencloudos-home → /mnt/oc9-xfs → /home/data (33468 OE profile) | 18 | # ENSURE_OE_XFS=1 mount opencloudos-home → /mnt/oc9-xfs → /home/data (33468 OE profile) |
| 19 | # CUBELET_ADDR override cubelet address for cri-multiplex | 19 | # CUBELET_ADDR override cubelet address for cri-multiplex |
| 20 | # (default: unix:///data/cubelet/cubelet.sock if sock exists, else 127.0.0.1:9999) | 20 | # (default: unix:///data/cubelet/cubelet.sock if sock exists, else 127.0.0.1:9999) |
| 21 | +# PATCH_CUBELET_QUOTA=1 | ||
| 22 | +# Explicitly allow rewriting Cubelet dynamicconf quotas for the | ||
| 23 | +# run. Default is off (KASandbox #68). When enabled, conf.yaml is | ||
| 24 | +# backed up first and restored on EXIT (including failure). | ||
| 21 | # | 25 | # |
| 22 | set -euo pipefail | 26 | set -euo pipefail |
| 23 | 27 | ||
| @@ -48,13 +52,48 @@ ensure_oe_xfs_data() { | |||
| 48 | cp --reflink=always /data/.oe-cube-xfs-ok /data/.reflink-stab-check 2>/dev/null && echo REFLINK_OK || true | 52 | cp --reflink=always /data/.oe-cube-xfs-ok /data/.reflink-stab-check 2>/dev/null && echo REFLINK_OK || true |
| 49 | } | 53 | } |
| 50 | 54 | ||
| 55 | +QUOTA_CFG="${QUOTA_CFG:-/usr/local/services/cubetoolbox/Cubelet/dynamicconf/conf.yaml}" | ||
| 56 | +QUOTA_BAK="" | ||
| 57 | +QUOTA_STATUS="" | ||
| 58 | + | ||
| 59 | +restore_quota() { | ||
| 60 | + if [[ -z "${QUOTA_BAK}" || ! -f "${QUOTA_BAK}" ]]; then | ||
| 61 | + return 0 | ||
| 62 | + fi | ||
| 63 | + if [[ ! -f "${QUOTA_CFG}" ]]; then | ||
| 64 | + log "WARN quota backup present but cfg missing: ${QUOTA_CFG}" | ||
| 65 | + return 0 | ||
| 66 | + fi | ||
| 67 | + cp -a "${QUOTA_BAK}" "${QUOTA_CFG}" | ||
| 68 | + rm -f "${QUOTA_BAK}" | ||
| 69 | + QUOTA_BAK="" | ||
| 70 | + if command -v systemctl >/dev/null 2>&1; then | ||
| 71 | + systemctl restart cube-sandbox-cubelet.service || true | ||
| 72 | + fi | ||
| 73 | + log "quota restored from backup" | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +# Mutates QUOTA_STATUS / QUOTA_BAK in the *current* shell. Do not call via | ||
| 77 | +# $(ensure_quota) when PATCH_CUBELET_QUOTA=1 — that would run the backup/trap | ||
| 78 | +# in a subshell and restore immediately (KASandbox #68). | ||
| 51 | ensure_quota() { | 79 | ensure_quota() { |
| 52 | - local CFG=/usr/local/services/cubetoolbox/Cubelet/dynamicconf/conf.yaml | 80 | + local CFG="${QUOTA_CFG}" |
| 53 | - [[ -f "$CFG" ]] || { echo "quota_skip_no_cfg"; return 0; } | 81 | + QUOTA_STATUS="quota_skip_no_cfg" |
| 54 | - python3 - <<'PY' | 82 | + [[ -f "$CFG" ]] || { echo "${QUOTA_STATUS}"; return 0; } |
| 83 | + if [[ "${PATCH_CUBELET_QUOTA:-0}" != "1" ]]; then | ||
| 84 | + QUOTA_STATUS="quota_skip_need_PATCH_CUBELET_QUOTA=1" | ||
| 85 | + echo "${QUOTA_STATUS}" | ||
| 86 | + return 0 | ||
| 87 | + fi | ||
| 88 | + QUOTA_BAK="${CFG}.stability.bak.$$" | ||
| 89 | + cp -a "$CFG" "${QUOTA_BAK}" | ||
| 90 | + # Restore even on early failure / Ctrl-C. | ||
| 91 | + trap restore_quota EXIT | ||
| 92 | + QUOTA_STATUS="$(python3 - "$CFG" <<'PY' | ||
| 55 | from pathlib import Path | 93 | from pathlib import Path |
| 56 | import re | 94 | import re |
| 57 | -p = Path("/usr/local/services/cubetoolbox/Cubelet/dynamicconf/conf.yaml") | 95 | +import sys |
| 96 | +p = Path(sys.argv[1]) | ||
| 58 | text = p.read_text(encoding="utf-8") | 97 | text = p.read_text(encoding="utf-8") |
| 59 | text2 = text | 98 | text2 = text |
| 60 | text2 = re.sub(r'(?m)^(\s*mcpu_limit:\s*).*$', r'\g<1>1000000', text2, count=1) | 99 | text2 = re.sub(r'(?m)^(\s*mcpu_limit:\s*).*$', r'\g<1>1000000', text2, count=1) |
| @@ -66,6 +105,8 @@ if text2 != text: | |||
| 66 | else: | 105 | else: |
| 67 | print("quota_ok") | 106 | print("quota_ok") |
| 68 | PY | 107 | PY |
| 108 | +)" | ||
| 109 | + echo "${QUOTA_STATUS}" | ||
| 69 | } | 110 | } |
| 70 | 111 | ||
| 71 | wait_cubelet_ready() { | 112 | wait_cubelet_ready() { |
| @@ -387,9 +428,10 @@ mkdir -p "$OUT" "$ROOT/rounds" /tmp/cube-verify/state | |||
| 387 | echo -e "kind\tround\tmetric\tvalue" >> "$SUMMARY" | 428 | echo -e "kind\tround\tmetric\tvalue" >> "$SUMMARY" |
| 388 | : > "$ROOT/run.log" | 429 | : > "$ROOT/run.log" |
| 389 | log "START rounds=$ROUNDS node=$NODE root=$ROOT" | 430 | log "START rounds=$ROUNDS node=$NODE root=$ROOT" |
| 390 | -qout=$(ensure_quota) | 431 | +ensure_quota >/dev/null |
| 432 | +qout="${QUOTA_STATUS}" | ||
| 391 | log "quota: $qout" | 433 | log "quota: $qout" |
| 392 | -if echo "$qout" | grep -q quota_patched; then | 434 | +if [[ "$qout" == "quota_patched" ]]; then |
| 393 | systemctl restart cube-sandbox-cubelet.service || true | 435 | systemctl restart cube-sandbox-cubelet.service || true |
| 394 | fi | 436 | fi |
| 395 | systemctl is-active cube-sandbox-cubelet.service cube-sandbox-cube-api.service cube-sandbox-cubemaster.service || true | 437 | systemctl is-active cube-sandbox-cubelet.service cube-sandbox-cube-api.service cube-sandbox-cubemaster.service || true |
| @@ -24,10 +24,17 @@ const ( | |||
| 24 | envdConnectEndStream = byte(0x02) | 24 | envdConnectEndStream = byte(0x02) |
| 25 | envdConnectCompressed = byte(0x01) | 25 | envdConnectCompressed = byte(0x01) |
| 26 | envdMaxEnvelopeSize = 64 * 1024 * 1024 | 26 | envdMaxEnvelopeSize = 64 * 1024 * 1024 |
| 27 | - envdDefaultUser = "root" | 27 | + // Default cap for combined stdout+stderr retained in memory for ExecSync. |
| 28 | - envdDefaultTimeout = 60 * time.Second | 28 | + // Matches the default gRPC max message size so a runaway guest command |
| 29 | + // cannot OOM cri-multiplex (KASandbox #67). | ||
| 30 | + envdMaxExecOutputBytesDefault = 16 * 1024 * 1024 | ||
| 31 | + envdDefaultUser = "root" | ||
| 32 | + envdDefaultTimeout = 60 * time.Second | ||
| 29 | ) | 33 | ) |
| 30 | 34 | ||
| 35 | +// Overridable in tests. | ||
| 36 | +var envdMaxExecOutputBytes = envdMaxExecOutputBytesDefault | ||
| 37 | + | ||
| 31 | type envdStartRequest struct { | 38 | type envdStartRequest struct { |
| 32 | Process envdProcessConfig `json:"process"` | 39 | Process envdProcessConfig `json:"process"` |
| 33 | Stdin *bool `json:"stdin,omitempty"` | 40 | Stdin *bool `json:"stdin,omitempty"` |
| @@ -140,6 +147,27 @@ func parseEnvdProcessStream(r io.Reader) (*envdExecResult, error) { | |||
| 140 | var stdout, stderr strings.Builder | 147 | var stdout, stderr strings.Builder |
| 141 | var exitCode int32 = -1 | 148 | var exitCode int32 = -1 |
| 142 | sawEnd := false | 149 | sawEnd := false |
| 150 | + truncated := false | ||
| 151 | + retained := 0 | ||
| 152 | + | ||
| 153 | + appendCapped := func(dst *strings.Builder, text string) { | ||
| 154 | + if text == "" || truncated { | ||
| 155 | + return | ||
| 156 | + } | ||
| 157 | + remain := envdMaxExecOutputBytes - retained | ||
| 158 | + if remain <= 0 { | ||
| 159 | + truncated = true | ||
| 160 | + return | ||
| 161 | + } | ||
| 162 | + if len(text) > remain { | ||
| 163 | + dst.WriteString(text[:remain]) | ||
| 164 | + retained += remain | ||
| 165 | + truncated = true | ||
| 166 | + return | ||
| 167 | + } | ||
| 168 | + dst.WriteString(text) | ||
| 169 | + retained += len(text) | ||
| 170 | + } | ||
| 143 | 171 | ||
| 144 | for { | 172 | for { |
| 145 | flags, payload, err := readConnectEnvelope(r) | 173 | flags, payload, err := readConnectEnvelope(r) |
| @@ -167,19 +195,23 @@ func parseEnvdProcessStream(r io.Reader) (*envdExecResult, error) { | |||
| 167 | continue | 195 | continue |
| 168 | } | 196 | } |
| 169 | if msg.Event.Data != nil { | 197 | if msg.Event.Data != nil { |
| 170 | - if msg.Event.Data.Stdout != "" { | 198 | + // Once capped, skip decoding further data chunks to avoid |
| 171 | - text, err := decodeEnvdBytes(msg.Event.Data.Stdout) | 199 | + // allocating huge temporary strings while draining to End. |
| 172 | - if err != nil { | 200 | + if !truncated { |
| 173 | - return nil, status.Errorf(codes.Internal, "decode stdout: %v", err) | 201 | + if msg.Event.Data.Stdout != "" { |
| 202 | + text, err := decodeEnvdBytes(msg.Event.Data.Stdout) | ||
| 203 | + if err != nil { | ||
| 204 | + return nil, status.Errorf(codes.Internal, "decode stdout: %v", err) | ||
| 205 | + } | ||
| 206 | + appendCapped(&stdout, text) | ||
| 174 | } | 207 | } |
| 175 | - stdout.WriteString(text) | 208 | + if msg.Event.Data.Stderr != "" { |
| 176 | - } | 209 | + text, err := decodeEnvdBytes(msg.Event.Data.Stderr) |
| 177 | - if msg.Event.Data.Stderr != "" { | 210 | + if err != nil { |
| 178 | - text, err := decodeEnvdBytes(msg.Event.Data.Stderr) | 211 | + return nil, status.Errorf(codes.Internal, "decode stderr: %v", err) |
| 179 | - if err != nil { | 212 | + } |
| 180 | - return nil, status.Errorf(codes.Internal, "decode stderr: %v", err) | 213 | + appendCapped(&stderr, text) |
| 181 | } | 214 | } |
| 182 | - stderr.WriteString(text) | ||
| 183 | } | 215 | } |
| 184 | } | 216 | } |
| 185 | if msg.Event.End != nil { | 217 | if msg.Event.End != nil { |
| @@ -128,6 +128,33 @@ func TestParseEnvdProcessStreamExitZeroOmitted(t *testing.T) { | |||
| 128 | } | 128 | } |
| 129 | } | 129 | } |
| 130 | 130 | ||
| 131 | +func TestParseEnvdProcessStreamCapsOutput(t *testing.T) { | ||
| 132 | + prev := envdMaxExecOutputBytes | ||
| 133 | + envdMaxExecOutputBytes = 8 | ||
| 134 | + t.Cleanup(func() { envdMaxExecOutputBytes = prev }) | ||
| 135 | + | ||
| 136 | + chunk := base64.StdEncoding.EncodeToString([]byte("abcdefghij")) // 10 bytes | ||
| 137 | + var buf bytes.Buffer | ||
| 138 | + _, _ = buf.Write(connectEnvelope(0, `{"event":{"data":{"stdout":"`+chunk+`"}}}`)) | ||
| 139 | + _, _ = buf.Write(connectEnvelope(0, `{"event":{"data":{"stdout":"`+chunk+`"}}}`)) | ||
| 140 | + _, _ = buf.Write(connectEnvelope(0, `{"event":{"end":{"exitCode":0,"exited":true,"status":"exit status 0"}}}`)) | ||
| 141 | + _, _ = buf.Write(connectEnvelope(envdConnectEndStream, `{}`)) | ||
| 142 | + | ||
| 143 | + result, err := parseEnvdProcessStream(&buf) | ||
| 144 | + if err != nil { | ||
| 145 | + t.Fatal(err) | ||
| 146 | + } | ||
| 147 | + if result.ExitCode != 0 { | ||
| 148 | + t.Fatalf("exit = %d", result.ExitCode) | ||
| 149 | + } | ||
| 150 | + if got := len(result.Stdout) + len(result.Stderr); got != 8 { | ||
| 151 | + t.Fatalf("retained = %d, want 8 (stdout=%q stderr=%q)", got, result.Stdout, result.Stderr) | ||
| 152 | + } | ||
| 153 | + if string(result.Stdout) != "abcdefgh" { | ||
| 154 | + t.Fatalf("stdout = %q", result.Stdout) | ||
| 155 | + } | ||
| 156 | +} | ||
| 157 | + | ||
| 131 | func TestShellQuoteArgs(t *testing.T) { | 158 | func TestShellQuoteArgs(t *testing.T) { |
| 132 | if got := shellQuoteArgs([]string{"echo", "a b"}); got != "echo 'a b'" { | 159 | if got := shellQuoteArgs([]string{"echo", "a b"}); got != "echo 'a b'" { |
| 133 | t.Fatalf("got %q", got) | 160 | t.Fatalf("got %q", got) |