package instanceexec import ( "encoding/json" "errors" "flag" "fmt" "log" "os" "path/filepath" "regexp" "time" "github.com/carlosframework/platform/internal/cliflag" "github.com/carlosframework/platform/internal/instancectl" "github.com/carlosframework/platform/internal/instancefs" "github.com/carlosframework/platform/internal/provision" ) // invocationShape is systemd's 128-bit invocation id as 32 hex digits. The // id becomes part of a file name, so anything else is refused before it can // name a path. var invocationShape = regexp.MustCompile(`^[0-9a-f]{32}$`) // RunExit is `carlos instance-exit `, the ExecStopPost= of every // template unit. It runs inside the namespace as carlos with systemd's // $INVOCATION_ID, $SERVICE_RESULT, $EXIT_CODE and $EXIT_STATUS, and leaves // the advisory exit record in the instance's own run directory (design // ยง6.5). It never fails the unit: a stop that could not be recorded is // still a stop, and the agent proves termination from unit state and the // cgroup, not from this file. func RunExit(args []string) { fs := flag.NewFlagSet("instance-exit", flag.ExitOnError) runDir := fs.String("run-dir", provision.SocketDir, "run directory holding instances/") fs.Usage = cliflag.Usage(fs, "usage: carlos instance-exit ") _ = fs.Parse(args) if fs.NArg() != 2 { fs.Usage() os.Exit(2) } role, ok := instancectl.ParseRole(fs.Arg(0)) if !ok { log.Printf("instance-exit: role %q is not run, seed, sidecar or cmd", fs.Arg(0)) return } if err := writeExitRecord(*runDir, role, fs.Arg(1), os.Getenv, time.Now()); err != nil { log.Printf("instance-exit: %v", err) } } // writeExitRecord writes exit...json with O_EXCL into // /instances/. A missing invocation id is a no-op (the // variables are systemd's to provide); a malformed one is an error. func writeExitRecord(runDir string, role instancectl.Role, inst string, env func(string) string, now time.Time) error { inv := env("INVOCATION_ID") if inv == "" { return nil } if !invocationShape.MatchString(inv) { return fmt.Errorf("INVOCATION_ID %q is not 32 hex digits", inv) } iid, name, err := recordTarget(role, inst, inv) if err != nil { return err } rec := instancectl.ExitRecord{ Invocation: inv, Result: env("SERVICE_RESULT"), Code: env("EXIT_CODE"), Status: env("EXIT_STATUS"), At: now.UTC(), } raw, err := json.MarshalIndent(rec, "", " ") if err != nil { return err } raw = append(raw, '\n') dir := filepath.Join(runDir, "instances", iid) // 0600: this record carries SERVICE_RESULT/EXIT_CODE/EXIT_STATUS from // systemd, which is diagnostic detail about the instance's own process, // not something every reader of the instance directory needs (final // review, plan 2, item 6). f, err := instancefs.OpenBeneath(dir, name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { if errors.Is(err, os.ErrExist) { return fmt.Errorf("record for invocation %s already exists", inv) } return err } if _, err := f.Write(raw); err != nil { f.Close() return err } return f.Close() }