描述:
当 pod 中只有一个容器时,通过 client-go/remotecommand.NewSPDYExecutor 登录容器/pod 是没有问题的。
但是当一个 pod 中有很多容器时,我无法通过容器 id 点登录。
任何人都可以帮助或给我解决方案吗?提前致谢。
注意:
我正在使用 client-go 连接到 k8s,并使用 remotecommand.NewSPDYExecutor 登录容器。
代码:
这是我用于登录/连接到 pod/容器的代码
func (s *ShellService) BuildConnection(shellVo vo.ShellContainerVo) error {
clu := cluster.GetCluster(shellVo.Cluster)
if clu == nil {
logs.Error("cannot find cluster: ", shellVo.Cluster)
return errors.New("cannot find cluster: " + shellVo.Cluster)
}
if shellVo.Command == "" {
shellVo.Command = "/bin/sh"
}
config := clu.Config
groupversion := schema.GroupVersion{
Group: "",
Version: "v1",
}
config.GroupVersion = &groupversion
config.APIPath = "/api"
config.ContentType = runtime.ContentTypeJSON
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
restclient, err := rest.RESTClientFor(config)
if err != nil {
return err
}
fn := func() error {
req := restclient.Post().
Resource("pods").
Name(shellVo.Container).
Namespace(shellVo.Namespace).
SubResource("exec").
Param("container", shellVo.Container).
Param("stdin", "true").
Param("stdout", "true").
Param("stderr", "true").
Param("command", shellVo.Command).Param("tty", "true")
c := make(chan *remotecommand.TerminalSize)
t := &terminalsize{shellVo.Conn, c}
req.VersionedParams(
&v1.PodExecOptions{
Container: shellVo.Container,
Command: []string{},
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
},
scheme.ParameterCodec,
)
executor, err := remotecommand.NewSPDYExecutor(
config, http.MethodPost, req.URL(),
)
if err != nil {
return err
}
return executor.Stream(remotecommand.StreamOptions{
//SupportedProtocols: remotecommandconsts.SupportedStreamingProtocols,
Stdin: t,
Stdout: shellVo.Conn,
Stderr: shellVo.Conn,
Tty: true,
TerminalSizeQueue: t,
})
//return nil
}
inFd, isTerminal := term.GetFdInfo(shellVo.Conn)
beego.Info(isTerminal)
state, err := term.SaveState(inFd)
return interrupt.Chain(nil, func() {
term.RestoreTerminal(inFd, state)
}).Run(fn)
//kubeShell := &pod.Shell{}
return nil
}
我的 pod 与几个边车一起运行。所以一个pod中有多个容器。我希望我可以通过提供容器 id 来登录指定的容器。