在客户端中读取kubernetes pod的日志时找不到资源

首先创建pod部署

if pod, err = clientset.CoreV1().Pods(namespace).Create(&v1.Pod{
        TypeMeta: metav1.TypeMeta{
            Kind:       "Deployment",
            APIVersion: "apps/v1",
        },
        ObjectMeta: metav1.ObjectMeta{
            Name:      "mithu",
            Namespace: namespace,
        },
        Spec: v1.PodSpec{
            Containers: []v1.Container{
                v1.Container{
                    Name:            "mithu",
                    Image:           "test-app",
                    ImagePullPolicy: "IfNotPresent",
                    Ports: []v1.ContainerPort{
                        v1.ContainerPort{
                            Name:          "local",
                            HostPort:      8081,
                            ContainerPort: 8081,
                            Protocol:      v1.ProtocolTCP,
                        },
                    },
                    Env: []v1.EnvVar{
                        v1.EnvVar{
                            Name:  "ASD",
                            Value: "",
                        },
                    },
                },
            },
            RestartPolicy: v1.RestartPolicyOnFailure,
        },
}); err == nil {
    fmt.Println("Pod created succesfuly with status", pod.Name)
} else {
    fmt.Println("Error1: ", err)
}

time.Sleep(5000)

现在已经部署了pod,我现在正在阅读日志

req := clientset.RESTClient().Get().
    Namespace(namespace).
    Name(pod.Name).
    Resource("pods").
    SubResource("log").
    Param("follow", "").
    Param("container", "").
    Param("previous", "").
    Param("timestamps", "")

readCloser, err := req.Stream()
if err != nil {
    fmt.Println("Error2: ", err)
} else {
    buf := new(bytes.Buffer)
    _, err = io.Copy(buf, readCloser)
    fmt.Println("log : ", buf.String())
}

随后从here读取日志
Pod正在成功创建,但客户端似乎无法找到获取错误的资源,如Error2:服务器无法找到所请求的资源(获取pods.meta.k8s.io mithu)

如果我尝试从命令行获取日志,则没有问题.我认为主要问题是pods.meta.k8s.io和命令行args pods之间

最佳答案 这对我有用:

req := clientset.CoreV1().Pods(namespace).GetLogs(
    pod.Name, 
    &v1.PodLogOptions{},
)

readCloser, err := req.Stream()
if err != nil {
        fmt.Println("Error2: ", err)
} else {
        buf := new(bytes.Buffer)
        _, err = io.Copy(buf, readCloser)
        fmt.Println("log : ", buf.String())
}
点赞