Kubernetes k8s'中的exec示例;使用go客户端实现pod
我想在pod中使用k8s go client to exec命令。然而,我找不到任何关于这方面的例子。因此,我阅读了Kubernetes k8s'中的exec示例;使用go客户端实现pod,kubernetes,Kubernetes,我想在pod中使用k8s go client to exec命令。然而,我找不到任何关于这方面的例子。因此,我阅读了kubectl exec源代码,并编写了如下代码。而且err=exec.Stream(sopt)总是在没有任何消息的情况下获取错误。谁能告诉我如何调试这个问题,或给我一个正确的例子 config := &restclient.Config{ Host: "http://192.168.8.175:8080", Insecure: true, } config.Conte
kubectl exec
源代码,并编写了如下代码。而且err=exec.Stream(sopt)
总是在没有任何消息的情况下获取错误。谁能告诉我如何调试这个问题,或给我一个正确的例子
config := &restclient.Config{
Host: "http://192.168.8.175:8080",
Insecure: true,
}
config.ContentConfig.GroupVersion = &api.Unversioned
config.ContentConfig.NegotiatedSerializer = api.Codecs
restClient, err := restclient.RESTClientFor(config)
if err != nil {
panic(err.Error())
}
req := restClient.Post().Resource("pods").Name("wordpress-mysql-213049546-29s7d").Namespace("default").SubResource("exec").Param("container", "mysql")
req.VersionedParams(&api.PodExecOptions{
Container: "mysql",
Command: []string{"ls"},
Stdin: true,
Stdout: true,
}, api.ParameterCodec)
exec, err := remotecommand.NewExecutor(config, "POST", req.URL())
if err != nil {
panic(err.Error())
}
sopt := remotecommand.StreamOptions{
SupportedProtocols: remotecommandserver.SupportedStreamingProtocols,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
}
err = exec.Stream(sopt)
if err != nil {
panic(err.Error())
}
您可能会感兴趣,看看我在
exec
中长期使用Kubernetes的客户端go
进入Pod时遇到了这个问题。但最后我找到了一个办法让它发挥作用。我已经编写了一个简单的代码来在我的repo中执行这个任务。我请你检查一下。我相信它会有帮助。当命令是以/bin/sh
开头的字符串数组时,它对我很有用:
[]string{"/bin/sh", "-c", "ls", "-ll", "."}
它对我很有用。在创建请求时,您错过了
.CoreV1()
是的,最近也有同样的问题。通过在创建请求时添加.CoreV1()
进行修复<代码>请求:=restClient..CoreV1().Post().Resource(“pods”)…
package k8s
import (
"io"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
)
// ExecCmd exec command on specific pod and wait the command's output.
func ExecCmdExample(client kubernetes.Interface, config *restclient.Config, podName string,
command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
cmd := []string{
"sh",
"-c",
command,
}
req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
Namespace("default").SubResource("exec")
option := &v1.PodExecOptions{
Command: cmd,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}
if stdin == nil {
option.Stdin = false
}
req.VersionedParams(
option,
scheme.ParameterCodec,
)
exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
return err
}
err = exec.Stream(remotecommand.StreamOptions{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
})
if err != nil {
return err
}
return nil
}