|
| 1 | +// Command supervisord-shim is a tiny supervisord eventlistener that |
| 2 | +// translates PROCESS_STATE_EXITED (expected=0) and PROCESS_STATE_FATAL |
| 3 | +// events into BrowserServiceCrashedEvent payloads and POSTs them to the |
| 4 | +// local kernel-images-api telemetry endpoint. |
| 5 | +// |
| 6 | +// All schema-mapping and event publishing logic lives here; lib/sysmon |
| 7 | +// does not handle supervisord events. Keeping the shim as the sole owner |
| 8 | +// of the supervisord protocol means lib/sysmon stays single-purpose |
| 9 | +// (kmsg only). |
| 10 | +// |
| 11 | +// Wire protocol per supervisord docs (http://supervisord.org/events.html): |
| 12 | +// |
| 13 | +// stdout: "READY\n" |
| 14 | +// stdin: header line ("ver:3.0 ... eventname:PROCESS_STATE_EXITED len:54\n") |
| 15 | +// stdin: payload of `len` bytes (no trailing newline) |
| 16 | +// stdout: "RESULT 2\nOK" (always; ACK regardless of downstream success) |
| 17 | +// |
| 18 | +// The result frame intentionally has NO trailing newline: supervisord |
| 19 | +// reads exactly the declared number of bytes after the header newline, |
| 20 | +// and a trailing newline would leak into the buffer and corrupt the |
| 21 | +// subsequent READY token, deadlocking the listener after one event. |
| 22 | +// |
| 23 | +// We always ACK with OK so supervisord doesn't quarantine us when the |
| 24 | +// downstream HTTP target is briefly unavailable. The events are |
| 25 | +// best-effort; if the API is down, we drop and log. |
| 26 | +// |
| 27 | +// All logging goes to stderr — stdout is the supervisord protocol channel. |
| 28 | +package main |
| 29 | + |
| 30 | +import ( |
| 31 | + "bufio" |
| 32 | + "bytes" |
| 33 | + "context" |
| 34 | + "fmt" |
| 35 | + "io" |
| 36 | + "log" |
| 37 | + "net/http" |
| 38 | + "os" |
| 39 | + "os/signal" |
| 40 | + "strconv" |
| 41 | + "strings" |
| 42 | + "syscall" |
| 43 | + "time" |
| 44 | + |
| 45 | + oapi "github.com/kernel/kernel-images/server/lib/oapi" |
| 46 | +) |
| 47 | + |
| 48 | +const ( |
| 49 | + defaultAPIBaseURL = "http://127.0.0.1:10001" |
| 50 | + httpTimeout = 2 * time.Second |
| 51 | +) |
| 52 | + |
| 53 | +func main() { |
| 54 | + log.SetOutput(os.Stderr) |
| 55 | + log.SetFlags(log.LstdFlags | log.Lmicroseconds) |
| 56 | + |
| 57 | + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) |
| 58 | + defer stop() |
| 59 | + go func() { |
| 60 | + <-ctx.Done() |
| 61 | + _ = os.Stdin.Close() |
| 62 | + }() |
| 63 | + |
| 64 | + baseURL := os.Getenv("KERNEL_IMAGES_API_BASE_URL") |
| 65 | + if baseURL == "" { |
| 66 | + baseURL = defaultAPIBaseURL |
| 67 | + } |
| 68 | + |
| 69 | + client, err := oapi.NewClientWithResponses(baseURL, oapi.WithHTTPClient(&http.Client{Timeout: httpTimeout})) |
| 70 | + if err != nil { |
| 71 | + log.Fatalf("init oapi client: %v", err) |
| 72 | + } |
| 73 | + |
| 74 | + in := bufio.NewReader(os.Stdin) |
| 75 | + out := bufio.NewWriter(os.Stdout) |
| 76 | + |
| 77 | + for { |
| 78 | + if _, err := out.WriteString("READY\n"); err != nil { |
| 79 | + log.Fatalf("write READY: %v", err) |
| 80 | + } |
| 81 | + if err := out.Flush(); err != nil { |
| 82 | + log.Fatalf("flush READY: %v", err) |
| 83 | + } |
| 84 | + |
| 85 | + header, payload, err := readEvent(in) |
| 86 | + if err != nil { |
| 87 | + if err == io.EOF { |
| 88 | + return |
| 89 | + } |
| 90 | + log.Fatalf("read event: %v", err) |
| 91 | + } |
| 92 | + |
| 93 | + // Try to publish but always ACK supervisord. |
| 94 | + ev, ok := mapEvent(header, payload) |
| 95 | + switch { |
| 96 | + case ok: |
| 97 | + if perr := publish(ctx, client, ev); perr != nil { |
| 98 | + log.Printf("publish telemetry event: %v", perr) |
| 99 | + } |
| 100 | + case isCrashEvent(header["eventname"]): |
| 101 | + // We subscribed to this event type but couldn't map it. |
| 102 | + // Most likely cause: supervisord emitted a from_state we |
| 103 | + // don't have a public phase for. Logging means a future |
| 104 | + // supervisord behavior change shows up in stderr instead |
| 105 | + // of silent telemetry loss. |
| 106 | + log.Printf("skipped crash event: eventname=%q from_state=%q processname=%q expected=%q", |
| 107 | + header["eventname"], payload["from_state"], payload["processname"], payload["expected"]) |
| 108 | + } |
| 109 | + |
| 110 | + if err := writeResultOK(out); err != nil { |
| 111 | + log.Fatalf("write RESULT: %v", err) |
| 112 | + } |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +// writeResultOK ACKs a single event. See the file header for why the |
| 117 | +// frame body has no trailing newline. |
| 118 | +func writeResultOK(out *bufio.Writer) error { |
| 119 | + if _, err := out.WriteString("RESULT 2\nOK"); err != nil { |
| 120 | + return err |
| 121 | + } |
| 122 | + return out.Flush() |
| 123 | +} |
| 124 | + |
| 125 | +// readEvent reads one supervisord event: a header line followed by a |
| 126 | +// payload of declared length. |
| 127 | +func readEvent(in *bufio.Reader) (map[string]string, map[string]string, error) { |
| 128 | + headerLine, err := in.ReadString('\n') |
| 129 | + if err != nil { |
| 130 | + return nil, nil, err |
| 131 | + } |
| 132 | + header := parseFields(strings.TrimRight(headerLine, "\n")) |
| 133 | + |
| 134 | + lenStr, ok := header["len"] |
| 135 | + if !ok { |
| 136 | + return nil, nil, fmt.Errorf("missing len in header: %q", headerLine) |
| 137 | + } |
| 138 | + n, err := strconv.Atoi(lenStr) |
| 139 | + if err != nil { |
| 140 | + return nil, nil, fmt.Errorf("invalid len %q: %w", lenStr, err) |
| 141 | + } |
| 142 | + |
| 143 | + buf := make([]byte, n) |
| 144 | + if _, err := io.ReadFull(in, buf); err != nil { |
| 145 | + return nil, nil, fmt.Errorf("read payload: %w", err) |
| 146 | + } |
| 147 | + payload := parseFields(string(buf)) |
| 148 | + return header, payload, nil |
| 149 | +} |
| 150 | + |
| 151 | +// parseFields parses supervisord's "key:value key:value" tokenization. |
| 152 | +// Values are split on the first colon; supervisord does not escape colons |
| 153 | +// in values, but in practice the values we care about (process names, |
| 154 | +// states, ints) never contain them. |
| 155 | +func parseFields(s string) map[string]string { |
| 156 | + out := make(map[string]string) |
| 157 | + for _, tok := range strings.Fields(s) { |
| 158 | + i := strings.IndexByte(tok, ':') |
| 159 | + if i < 0 { |
| 160 | + continue |
| 161 | + } |
| 162 | + out[tok[:i]] = tok[i+1:] |
| 163 | + } |
| 164 | + return out |
| 165 | +} |
| 166 | + |
| 167 | +// phaseForExited maps the supervisord state a process exited from to the |
| 168 | +// public lifecycle phase. EXITED in supervisord always originates from |
| 169 | +// RUNNING (post-startsecs); STARTING-during-startsecs-violation routes |
| 170 | +// through BACKOFF→FATAL, not EXITED. We still defend against STARTING |
| 171 | +// here in case a future supervisord version changes the state machine, |
| 172 | +// and we treat anything else as "unknown" so the caller logs and skips |
| 173 | +// rather than inventing a phase. |
| 174 | +func phaseForExited(fromState string) (oapi.BrowserServiceCrashedEventDataPhase, bool) { |
| 175 | + switch fromState { |
| 176 | + case "RUNNING": |
| 177 | + return oapi.BrowserServiceCrashedEventDataPhaseRunning, true |
| 178 | + case "STARTING": |
| 179 | + return oapi.BrowserServiceCrashedEventDataPhaseStartup, true |
| 180 | + default: |
| 181 | + return "", false |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +// isCrashEvent reports whether the supervisord eventname is one we |
| 186 | +// subscribed to. Used by the main loop to log when a target event was |
| 187 | +// dropped instead of silently skipping it. |
| 188 | +func isCrashEvent(eventName string) bool { |
| 189 | + return eventName == "PROCESS_STATE_EXITED" || eventName == "PROCESS_STATE_FATAL" |
| 190 | +} |
| 191 | + |
| 192 | +// mapEvent decides whether to publish and constructs the event payload. |
| 193 | +// Returns ok=false for events we deliberately skip (intentional stops, |
| 194 | +// non-crash event types, or unknown lifecycle transitions). |
| 195 | +func mapEvent(header, payload map[string]string) (oapi.PublishEventRequest, bool) { |
| 196 | + var phase oapi.BrowserServiceCrashedEventDataPhase |
| 197 | + switch header["eventname"] { |
| 198 | + case "PROCESS_STATE_EXITED": |
| 199 | + // expected=0 means the exit was not in `exitcodes` — i.e. a |
| 200 | + // crash. expected=1 means clean shutdown (operator-initiated |
| 201 | + // stop, or a configured exit code). Skip the latter. |
| 202 | + if payload["expected"] != "0" { |
| 203 | + return oapi.PublishEventRequest{}, false |
| 204 | + } |
| 205 | + p, ok := phaseForExited(payload["from_state"]) |
| 206 | + if !ok { |
| 207 | + return oapi.PublishEventRequest{}, false |
| 208 | + } |
| 209 | + phase = p |
| 210 | + case "PROCESS_STATE_FATAL": |
| 211 | + // FATAL is reached exclusively by the BACKOFF→FATAL edge after |
| 212 | + // supervisord exhausts startretries. The from_state is always |
| 213 | + // BACKOFF here, and the semantic is "gave up trying to start". |
| 214 | + phase = oapi.BrowserServiceCrashedEventDataPhaseGaveUp |
| 215 | + default: |
| 216 | + return oapi.PublishEventRequest{}, false |
| 217 | + } |
| 218 | + |
| 219 | + name := payload["processname"] |
| 220 | + if name == "" { |
| 221 | + return oapi.PublishEventRequest{}, false |
| 222 | + } |
| 223 | + |
| 224 | + data := oapi.BrowserServiceCrashedEventData{ |
| 225 | + ServiceName: name, |
| 226 | + Phase: phase, |
| 227 | + } |
| 228 | + if pidStr := payload["pid"]; pidStr != "" { |
| 229 | + if pid, err := strconv.Atoi(pidStr); err == nil { |
| 230 | + data.Pid = &pid |
| 231 | + } |
| 232 | + } |
| 233 | + |
| 234 | + category := oapi.PublishEventRequestCategory(oapi.TelemetryEventCategorySystem) |
| 235 | + sourceEvent := "service.crashed" |
| 236 | + return oapi.PublishEventRequest{ |
| 237 | + Type: string(oapi.ServiceCrashed), |
| 238 | + Category: &category, |
| 239 | + Source: &oapi.BrowserEventSource{ |
| 240 | + Kind: oapi.LocalProcess, |
| 241 | + Event: &sourceEvent, |
| 242 | + }, |
| 243 | + Data: data, |
| 244 | + }, true |
| 245 | +} |
| 246 | + |
| 247 | +func publish(ctx context.Context, client *oapi.ClientWithResponses, body oapi.PublishEventRequest) error { |
| 248 | + resp, err := client.PublishTelemetryEventWithResponse(ctx, body) |
| 249 | + if err != nil { |
| 250 | + return err |
| 251 | + } |
| 252 | + if resp.StatusCode() >= 300 { |
| 253 | + return fmt.Errorf("status %d: %s", resp.StatusCode(), bytes.TrimSpace(resp.Body)) |
| 254 | + } |
| 255 | + return nil |
| 256 | +} |
0 commit comments