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

时间:2018-09-28 07:22:10

标签: kubernetes kubernetes-go-client

首先创建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)

现在吊舱已经部署好了,我现在正在阅读日志

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: the server could not find the requested resource (get pods.meta.k8s.io mithu)

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

1 个答案:

答案 0 :(得分:1)

这对我有用:

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())
}
相关问题