k8s exec command terminated but the remote command does not

105 views Asked by At

I am using k8s remote exec command to run a http server (via cmd). When the host program terminated (Ctrl+C), the remote command still running at the remote container.

How to terminate the remote command cmd also? Many thanks.

This is part of the k8s remote exec code:

remoteExecute(ctx context.Context, pod *k8sCore.Pod, containerName string, cmd []string,
    ioIn io.Reader, ioOut, ioErr io.Writer, tty bool,
) error {
    req := kClientSet.CoreV1().RESTClient().Post().
        Resource("pods").
        Name(pod.GetName()).
        Namespace(pod.GetNamespace()).
        SubResource("exec").
        VersionedParams(&k8sCore.PodExecOptions{
            Container: containerName,
            Command:   cmd,
            Stdin:     ioIn != nil,
            Stdout:    ioOut != nil,
            Stderr:    ioErr != nil,
            TTY:       tty,
        }, scheme.ParameterCodec)

    executor, err := remotecommand.NewSPDYExecutor(s.kRestCfg, "POST", req.URL())
    if err != nil {
        return fmt.Errorf("new spdy executor: %w", err)
    }

    // run the command
    err = executor.StreamWithContext(ctx, remotecommand.StreamOptions{
        Stdin:  ioIn,
        Stdout: ioOut,
        Stderr: ioErr,
        Tty:    tty,
    })

    if err != nil {
        return fmt.Errorf("stream with context: %w", err)
    }

    return nil
}

The context captured signal correct already

    ctx, cancel := context.WithCancel(ctx)

    c := make(chan os.Signal, 1)
    // Notify the signal channel for SIGINT (Ctrl+C) and SIGTERM (termination)
    signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-c
        cancel()
    }()
0

There are 0 answers