How to use GetPodLogs method of client Package

Best Testkube code snippet using client.GetPodLogs

downwardapi_volume.go

Source:downwardapi_volume.go Github

copy

Full Screen

1/*2Copyright 2015 The Kubernetes Authors All rights reserved.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package e2e14import (15 "fmt"16 "strings"17 "time"18 "k8s.io/kubernetes/pkg/api"19 client "k8s.io/kubernetes/pkg/client/unversioned"20 "k8s.io/kubernetes/pkg/util"21 . "github.com/onsi/ginkgo"22 . "github.com/onsi/gomega"23)24// How long to wait for a log pod to be displayed25const podLogTimeout = 45 * time.Second26// utility function for gomega Eventually27func getPodLogs(c *client.Client, namespace, podName, containerName string) (string, error) {28 logs, err := c.Get().Resource("pods").Namespace(namespace).Name(podName).SubResource("log").Param("container", containerName).Do().Raw()29 if err != nil {30 return "", err31 }32 if err == nil && strings.Contains(string(logs), "Internal Error") {33 return "", fmt.Errorf("Internal Error")34 }35 return string(logs), err36}37var _ = Describe("Downward API volume", func() {38 f := NewFramework("downward-api")39 It("should provide podname only [Conformance]", func() {40 podName := "downwardapi-volume-" + string(util.NewUUID())41 pod := downwardAPIVolumePod(podName, map[string]string{}, map[string]string{}, "/etc/podname")42 testContainerOutput("downward API volume plugin", f.Client, pod, 0, []string{43 fmt.Sprintf("%s\n", podName),44 }, f.Namespace.Name)45 })46 It("should provide podname as non-root with fsgroup [Conformance] [Skipped]", func() {47 podName := "metadata-volume-" + string(util.NewUUID())48 uid := int64(1001)49 gid := int64(1234)50 pod := downwardAPIVolumePod(podName, map[string]string{}, map[string]string{}, "/etc/podname")51 pod.Spec.SecurityContext = &api.PodSecurityContext{52 RunAsUser: &uid,53 FSGroup: &gid,54 }55 testContainerOutput("downward API volume plugin", f.Client, pod, 0, []string{56 fmt.Sprintf("%s\n", podName),57 }, f.Namespace.Name)58 })59 It("should update labels on modification [Conformance]", func() {60 labels := map[string]string{}61 labels["key1"] = "value1"62 labels["key2"] = "value2"63 podName := "labelsupdate" + string(util.NewUUID())64 pod := downwardAPIVolumePod(podName, labels, map[string]string{}, "/etc/labels")65 containerName := "client-container"66 defer func() {67 By("Deleting the pod")68 f.Client.Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0))69 }()70 By("Creating the pod")71 _, err := f.Client.Pods(f.Namespace.Name).Create(pod)72 Expect(err).NotTo(HaveOccurred())73 expectNoError(waitForPodRunningInNamespace(f.Client, pod.Name, f.Namespace.Name))74 pod, err = f.Client.Pods(f.Namespace.Name).Get(pod.Name)75 Expect(err).NotTo(HaveOccurred())76 Eventually(func() (string, error) {77 return getPodLogs(f.Client, f.Namespace.Name, pod.Name, containerName)78 },79 podLogTimeout, poll).Should(ContainSubstring("key1=\"value1\"\n"))80 //modify labels81 pod.Labels["key3"] = "value3"82 _, err = f.Client.Pods(f.Namespace.Name).Update(pod)83 Expect(err).NotTo(HaveOccurred())84 Eventually(func() (string, error) {85 return getPodLogs(f.Client, f.Namespace.Name, pod.Name, containerName)86 },87 podLogTimeout, poll).Should(ContainSubstring("key3=\"value3\"\n"))88 })89 It("should update annotations on modification [Conformance]", func() {90 annotations := map[string]string{}91 annotations["builder"] = "bar"92 podName := "annotationupdate" + string(util.NewUUID())93 pod := downwardAPIVolumePod(podName, map[string]string{}, annotations, "/etc/annotations")94 containerName := "client-container"95 defer func() {96 By("Deleting the pod")97 f.Client.Pods(f.Namespace.Name).Delete(pod.Name, api.NewDeleteOptions(0))98 }()99 By("Creating the pod")100 _, err := f.Client.Pods(f.Namespace.Name).Create(pod)101 Expect(err).NotTo(HaveOccurred())102 expectNoError(waitForPodRunningInNamespace(f.Client, pod.Name, f.Namespace.Name))103 pod, err = f.Client.Pods(f.Namespace.Name).Get(pod.Name)104 Expect(err).NotTo(HaveOccurred())105 Eventually(func() (string, error) {106 return getPodLogs(f.Client, f.Namespace.Name, pod.Name, containerName)107 },108 podLogTimeout, poll).Should(ContainSubstring("builder=\"bar\"\n"))109 //modify annotations110 pod.Annotations["builder"] = "foo"111 _, err = f.Client.Pods(f.Namespace.Name).Update(pod)112 Expect(err).NotTo(HaveOccurred())113 Eventually(func() (string, error) {114 return getPodLogs(f.Client, f.Namespace.Name, pod.Name, containerName)115 },116 podLogTimeout, poll).Should(ContainSubstring("builder=\"foo\"\n"))117 })118})119func downwardAPIVolumePod(name string, labels, annotations map[string]string, filePath string) *api.Pod {120 pod := &api.Pod{121 ObjectMeta: api.ObjectMeta{122 Name: name,123 Labels: labels,124 Annotations: annotations,125 },126 Spec: api.PodSpec{127 Containers: []api.Container{128 {129 Name: "client-container",130 Image: "gcr.io/google_containers/mounttest:0.6",131 Command: []string{"/mt", "--break_on_expected_content=false", "--retry_time=120", "--file_content_in_loop=" + filePath},132 VolumeMounts: []api.VolumeMount{133 {134 Name: "podinfo",135 MountPath: "/etc",136 ReadOnly: false,137 },138 },139 },140 },141 Volumes: []api.Volume{142 {143 Name: "podinfo",144 VolumeSource: api.VolumeSource{145 DownwardAPI: &api.DownwardAPIVolumeSource{146 Items: []api.DownwardAPIVolumeFile{147 {148 Path: "podname",149 FieldRef: api.ObjectFieldSelector{150 APIVersion: "v1",151 FieldPath: "metadata.name",152 },153 },154 },155 },156 },157 },158 },159 RestartPolicy: api.RestartPolicyNever,160 },161 }162 if len(labels) > 0 {163 pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, api.DownwardAPIVolumeFile{164 Path: "labels",165 FieldRef: api.ObjectFieldSelector{166 APIVersion: "v1",167 FieldPath: "metadata.labels",168 },169 })170 }171 if len(annotations) > 0 {172 pod.Spec.Volumes[0].DownwardAPI.Items = append(pod.Spec.Volumes[0].DownwardAPI.Items, api.DownwardAPIVolumeFile{173 Path: "annotations",174 FieldRef: api.ObjectFieldSelector{175 APIVersion: "v1",176 FieldPath: "metadata.annotations",177 },178 })179 }180 return pod181}182// TODO: add test-webserver example as pointed out in https://github.com/kubernetes/kubernetes/pull/5093#discussion-diff-37606771...

Full Screen

Full Screen

watch.go

Source:watch.go Github

copy

Full Screen

1package pkg2import (3 "bytes"4 "fmt"5 "io"6 "strings"7 "time"8 "github.com/litmuschaos/litmus-e2e/pkg/environment"9 "github.com/litmuschaos/litmus-e2e/pkg/log"10 "github.com/litmuschaos/litmus-e2e/pkg/types"11 "github.com/pkg/errors"12 v1 "k8s.io/api/core/v1"13 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"14)15// ChaosPodLogs will print the experiment and helper pod logs16func ChaosPodLogs(testsDetails *types.TestDetails, clients environment.ClientSets) error {17 if err := printChaosPodLogs(testsDetails, clients); err != nil {18 return err19 }20 uid, err := GetUID(testsDetails.EngineName, testsDetails.ChaosNamespace, clients)21 if err != nil {22 return errors.Errorf("Failed to get uid from experiment label,err: %v", err)23 }24 if err = printHelperPodLogs(testsDetails.ExperimentName, testsDetails.ChaosNamespace, uid, clients); err != nil {25 return errors.Errorf("Failed to get the helper pod", err)26 }27 return nil28}29// printChaosPodLogs will wait for the chaosPod to get completed and then prints the logs of it.30func printChaosPodLogs(testsDetails *types.TestDetails, clients environment.ClientSets) error {31 chaosEngine, err := clients.LitmusClient.ChaosEngines(testsDetails.AppNS).Get(testsDetails.EngineName, metav1.GetOptions{})32 if err != nil {33 return errors.Errorf("Failed to get the chaosengine %v err: %v", testsDetails.EngineName, err)34 }35 if len(chaosEngine.Status.Experiments) == 0 {36 return errors.Errorf("Failed to get the chaos pod for the test")37 }38 for count := 0; count < 3000; count++ {39 chaosPod, err := clients.KubeClient.CoreV1().Pods(testsDetails.AppNS).Get(chaosEngine.Status.Experiments[0].ExpPod, metav1.GetOptions{})40 if err != nil {41 return errors.Errorf("Failed to get the chaos pod err: %v", err)42 }43 if chaosPod.Status.Phase != "Succeeded" {44 if chaosPod.Status.Phase != "Running" && chaosPod.Status.Phase != "Pending" {45 return errors.Errorf("chaos pod is in %v state", chaosPod.Status.Phase)46 }47 time.Sleep(10 * time.Second)48 log.Infof("[Status]: Currently, the Chaos Pod is in %v State, Please Wait for its completion", chaosPod.Status.Phase)49 } else {50 break51 }52 }53 //Getting the jobList after the job gets completed54 chaosPodName := (chaosEngine.Status.Experiments[0].ExpPod)55 log.Infof("[Info]: chaos pod name is: %v ", chaosPodName)56 if err = getPodLogs(chaosPodName, testsDetails.ChaosNamespace, clients); err != nil {57 return err58 }59 return nil60}61//printHelperPodLogs will print the helper pod logs when the experiment is not passed62func printHelperPodLogs(experimentName, namespace, UID string, clients environment.ClientSets) error {63 podList, err := clients.KubeClient.CoreV1().Pods(namespace).List(metav1.ListOptions{})64 if err != nil || len(podList.Items) == 0 {65 return errors.Errorf("Failed to get the pods in chaos ns, err:%v", err)66 }67 for _, pod := range podList.Items {68 if strings.Contains(pod.Name, experimentName+"-helper") && pod.Labels["chaosUID"] == UID {69 if err = getPodLogs(pod.Name, namespace, clients); err != nil {70 log.Errorf("Failed to get the logs of helper pod %v, err: %v", pod.Name, err)71 }72 }73 }74 return nil75}76//getPodLogs will print the logs of the given pod77func getPodLogs(podName, namespace string, clients environment.ClientSets) error {78 req := clients.KubeClient.CoreV1().Pods(namespace).GetLogs(podName, &v1.PodLogOptions{})79 readCloser, err := req.Stream()80 if err != nil {81 return errors.Errorf("Failed to print the logs of %v pod", podName, err)82 }83 buf := new(bytes.Buffer)84 _, err = io.Copy(buf, readCloser)85 if err != nil {86 return errors.Errorf("Failed to read the logs, err: %v", err)87 }88 fmt.Println("\n"+podName+" logs : \n\n", buf.String())89 return nil90}...

Full Screen

Full Screen

cluster_operations.go

Source:cluster_operations.go Github

copy

Full Screen

1package test2import (3 "bytes"4 "context"5 "flag"6 "fmt"7 "io"8 "log"9 "path/filepath"10 batchv1 "k8s.io/api/batch/v1"11 apiv1 "k8s.io/api/core/v1"12 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"13 "k8s.io/client-go/kubernetes"14 "k8s.io/client-go/tools/clientcmd"15 "k8s.io/client-go/util/homedir"16)17func NewK8s(kubeConfigPath string) (*kubernetes.Clientset, error) {18 var clientSet *kubernetes.Clientset19 var kubeconfig *string20 if len(kubeConfigPath) > 0 {21 kubeconfig = &kubeConfigPath22 } else if home := homedir.HomeDir(); home != "" {23 kc := filepath.Join(home, ".kube", "config")24 kubeconfig = &kc25 } else {26 return nil, fmt.Errorf("kube config path not specified and could not be found in home directory")27 }28 flag.Parse()29 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)30 if err != nil {31 return nil, err32 }33 clientSet, err = kubernetes.NewForConfig(config)34 if err != nil {35 return nil, err36 }37 return clientSet, nil38}39func ExecuteJob(jobName string, imageName string, containerArgs []string, labels map[string]string, clientSet *kubernetes.Clientset) (int32, string, error) {40 ctx := generateDefaultContext(KubernetesTimeout)41 jobsClient := clientSet.BatchV1().Jobs("default")42 var ttl int32 = 043 job := &batchv1.Job{44 ObjectMeta: metav1.ObjectMeta{45 Name: jobName,46 },47 Spec: batchv1.JobSpec{48 TTLSecondsAfterFinished: &ttl,49 Template: apiv1.PodTemplateSpec{50 ObjectMeta: metav1.ObjectMeta{51 Name: jobName,52 Labels: labels,53 },54 Spec: apiv1.PodSpec{55 RestartPolicy: apiv1.RestartPolicyNever,56 Containers: []apiv1.Container{57 {58 Name: jobName,59 Image: imageName,60 Args: containerArgs,61 },62 },63 },64 },65 },66 }67 podWatchList, err := clientSet.CoreV1().Pods("default").Watch(ctx, metav1.ListOptions{68 LabelSelector: fmt.Sprintf("job-name=%s", jobName),69 })70 if err != nil {71 return 0, "", fmt.Errorf("error creating pod watch: %w", err)72 }73 _, _ = jobsClient.Create(ctx, job, metav1.CreateOptions{})74 var lastPodLog string75 for event := range podWatchList.ResultChan() {76 p, ok := event.Object.(*apiv1.Pod)77 if !ok {78 log.Fatal("unexpected type")79 }80 if p.Status.Phase == apiv1.PodSucceeded {81 logs := getPodLogs(ctx, clientSet, *p)82 return p.Status.ContainerStatuses[0].State.Terminated.ExitCode, logs, nil83 } else if p.Status.Phase == apiv1.PodFailed {84 logs := getPodLogs(ctx, clientSet, *p)85 log.Printf("job pod failed - logs are: %s", logs)86 }87 lastPodLog = getPodLogs(ctx, clientSet, *p)88 }89 return -1, lastPodLog, fmt.Errorf("error waiting for pod to complete")90}91func getPodLogs(ctx context.Context, clientSet *kubernetes.Clientset, pod apiv1.Pod) string {92 podLogOpts := apiv1.PodLogOptions{}93 req := clientSet.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &podLogOpts)94 podLogs, err := req.Stream(ctx)95 if err != nil {96 return "error in opening stream"97 }98 defer podLogs.Close()99 buf := new(bytes.Buffer)100 _, err = io.Copy(buf, podLogs)101 if err != nil {102 return "error in copy information from podLogs to buf"103 }104 str := buf.String()105 return str106}...

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err = clientcmd.BuildConfigFromFlags("", "/home/username/.kube/config")4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 logs, err := clientset.CoreV1().Pods("default").GetLogs("my-pod", &v1.PodLogOptions{}).Stream()12 if err != nil {13 panic(err.Error())14 }15 defer logs.Close()16 buf := new(bytes.Buffer)17 _, err = io.Copy(buf, logs)18 if err != nil {19 panic(err.Error())20 }21 str := buf.String()22 fmt.Println(str)23}

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := clientcmd.BuildConfigFromFlags("", "/home/ashish/.kube/config")4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 clientset.ExtensionsV1beta1().Deployments("default").Get("testdeployment")12 deployment := &v1beta1.Deployment{13 ObjectMeta: v1.ObjectMeta{14 },15 Spec: v1beta1.DeploymentSpec{16 Replicas: int32Ptr(1),17 Template: v1.PodTemplateSpec{18 ObjectMeta: v1.ObjectMeta{19 Labels: map[string]string{"app": "nginx"},20 },21 Spec: v1.PodSpec{22 Containers: []v1.Container{23 {24 },25 },26 },27 },28 },29 }30 fmt.Println("Creating deployment...")31 result, err := clientset.ExtensionsV1beta1().Deployments("default").Create(deployment)32 if err != nil {33 panic(err)34 }35 fmt.Printf("Created deployment %q.\n", result.GetObjectMeta().GetName())36 fmt.Println("Listing pods...")37 pods, err := clientset.CoreV1().Pods("default").List(v1.ListOptions{})38 if err != nil {39 panic(err.Error())40 }41 fmt.Printf("There are %d pods in the cluster42", len(pods.Items))

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := clientcmd.BuildConfigFromFlags("", "/home/ashish/.kube/config")4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 podLogs, err := clientset.CoreV1().Pods("default").GetLogs("nginx-deployment-5d6c5b8f7b-2d2z7", &corev1.PodLogOptions{12 }).Stream()13 if err != nil {14 panic(err.Error())15 }16 defer podLogs.Close()17 buf := new(bytes.Buffer)18 _, err = io.Copy(buf, podLogs)19 if err != nil {20 panic(err.Error())21 }22 str := buf.String()23 fmt.Println(str)24}

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if home := homeDir(); home != "" {4 kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")5 } else {6 kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")7 }8 flag.Parse()9 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)10 if err != nil {11 panic(err.Error())12 }13 clientset, err := kubernetes.NewForConfig(config)14 if err != nil {15 panic(err.Error())16 }17 pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{})18 if err != nil {19 panic(err.Error())20 }21 fmt.Printf("There are %d pods in the cluster22", len(pods.Items))23 for _, pod := range pods.Items {24 fmt.Printf("Pod Name: %s, Namespace: %s, Image: %s, Node: %s25 }26 podLogs, err := clientset.CoreV1().Pods("default").GetLogs(podName, &v1.PodLogOptions{}).Stream()27 if err != nil {28 panic(err.Error())29 }30 defer podLogs.Close()31 buf := new(bytes.Buffer)32 _, err = io.Copy(buf, podLogs)33 if err != nil {34 panic(err.Error())35 }36 str := buf.String()37 fmt.Println(str)38}39func homeDir() string {40 if h := os.Getenv("HOME"); h != "" {41 }42}

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := rest.InClusterConfig()4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 logs, err := clientset.CoreV1().Pods("default").GetLogs("nginx-pod", &kubernetes.PodLogOptions{}).DoRaw(context.Background())12 if err != nil {13 panic(err.Error())14 }15 fmt.Fprintf(os.Stdout, "%s", logs)16}

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := clientcmd.BuildConfigFromFlags("", "/home/ashish/.kube/config")4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 podLogs, err := clientset.CoreV1().Pods("default").GetLogs("myapp-pod", &corev1.PodLogOptions{}).Stream()12 if err != nil {13 panic(err.Error())14 }15 defer podLogs.Close()16 buf := new(bytes.Buffer)17 _, err = io.Copy(buf, podLogs)18 if err != nil {19 panic(err.Error())20 }21 str := buf.String()22 fmt.Println(str)23}

Full Screen

Full Screen

GetPodLogs

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if home := homeDir(); home != "" {4 kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")5 } else {6 kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")7 }8 flag.Parse()9 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)10 if err != nil {11 panic(err.Error())12 }13 clientset, err := kubernetes.NewForConfig(config)14 if err != nil {15 panic(err.Error())16 }17 podLogOpts := v1.PodLogOptions{}18 req := clientset.CoreV1().Pods("default").GetLogs("nginx", &podLogOpts)19 podLogs, err := req.Stream()20 if err != nil {21 panic(err.Error())22 }23 defer podLogs.Close()24 buf := new(bytes.Buffer)25 _, err = io.Copy(buf, podLogs)26 if err != nil {27 panic(err.Error())28 }29 str := buf.String()30 fmt.Println(str)31}32func homeDir() string {33 if h := os.Getenv("HOME"); h != "" {34 }35}36import (37func main() {38 if home := homeDir(); home != "" {39 kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")40 } else {41 kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")42 }43 flag.Parse()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful