Something went wrong. Try again.
Monorepo for Tangled tangled.org
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091package nsapi
import ( "context" "errors" "io" "regexp" "strconv"
computegrpc "buf.build/gen/go/namespace/cloud/grpc/go/proto/namespace/cloud/compute/v1beta/computev1betagrpc" computepb "buf.build/gen/go/namespace/cloud/protocolbuffers/go/proto/namespace/cloud/compute/v1beta")
// Run runs a command on an instance and streams its output//// in a container the shim reports a failed exec on stderr and exits 1, so Run// hides that line and returns the exit code it givesfunc (c *Client) Run(ctx context.Context, tok Token, inst Instance, cmd Command, stdout, stderr io.Writer) (int32, error) { if inst.CommandEndpoint == nil { return 0, errors.New("The instance has no command endpoint.") } ctx, cancel := context.WithCancel(ctx) defer cancel() ctx, err := bearer(ctx, tok) if err != nil { return 0, err } conn, err := c.conns.get(inst.CommandEndpoint) if err != nil { return 0, err } vars := make([]*computepb.EnvironmentVariable, 0, len(cmd.Env)) for name, value := range cmd.Env { vars = append(vars, &computepb.EnvironmentVariable{Name: name, Value: value}) } shim := &shimWriter{w: stderr} if cmd.Container != "" { stderr = shim } stream, err := computegrpc.NewCommandServiceClient(conn).RunCommand(ctx, &computepb.RunCommandRequest{ InstanceId: string(inst.ID), TargetContainerName: string(cmd.Container), Command: &computepb.Command{Command: cmd.Args, EnvVars: vars, Cwd: cmd.Cwd}, }) if err != nil { return 0, computeError(err) } for { resp, err := stream.Recv() if errors.Is(err, io.EOF) { return 0, errors.New("Namespace ended the command without an exit status.") } if err != nil { return 0, computeError(err) } if data := resp.GetData(); len(data) > 0 { out := stdout if resp.GetStream() == computepb.RunCommandResponse_STDERR { out = stderr } if _, err := out.Write(data); err != nil { return 0, err } } if exit := resp.GetExitStatus(); exit != nil { if code := exit.GetExitCode(); code != 1 || !shim.seen { return code, nil } return shim.code, nil } }}
var shimExit = regexp.MustCompile(`^time="[^"]*" level=fatal msg="exec failed with exit code (\d+)"\s*$`)
type shimWriter struct { w io.Writer code int32 seen bool}
func (s *shimWriter) Write(p []byte) (int, error) { if m := shimExit.FindSubmatch(p); m != nil { if code, err := strconv.ParseInt(string(m[1]), 10, 32); err == nil { s.code, s.seen = int32(code), true return len(p), nil } } return s.w.Write(p)}