Last active
January 20, 2022 11:39
-
-
Save ezodude/d1909447816a868c448ece24fecd7baa to your computer and use it in GitHub Desktop.
Pod logs in K8s Operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (r *AReconciler) publishMetrics(ctx context.Context, v *lt.LoadTest, logger logr.Logger) (*ctrl.Result, error) { | |
found := &v1.Job{} | |
err := r.Get(ctx, types.NamespacedName{ | |
Name: v.Name, | |
Namespace: v.Namespace, | |
}, found) | |
if err != nil { | |
// The job may not have been created yet, so requeue | |
return &ctrl.Result{RequeueAfter: 5 * time.Second}, err | |
} | |
err = retry.RetryOnConflict(retry.DefaultRetry, func() error { | |
if observedStatus(found.Status) != LoadTestCompleted { | |
return nil | |
} | |
restConfig, err := ctrl.GetConfig() | |
if err != nil { | |
return err | |
} | |
clientset, err := kubernetes.NewForConfig(restConfig) | |
if err != nil { | |
return err | |
} | |
podList, err := getPods(ctx, v, r.Client) | |
if err != nil { | |
return err | |
} | |
tailLines := int64(23) // no of lines for summary | |
logger.Info("Pod list items", "podList.Items.Len", len(podList.Items)) | |
for _, pod := range podList.Items { | |
req := clientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &core.PodLogOptions{TailLines: &tailLines}) | |
podLogs, err := req.Stream(ctx) | |
if err != nil { | |
return fmt.Errorf("Error in opening stream, err:\n%s", err.Error()) | |
} | |
buf := new(bytes.Buffer) | |
if _, err := io.Copy(buf, podLogs); err != nil { | |
return fmt.Errorf("Error in copy information from podLogs to buf, err:\n%s", err.Error()) | |
} | |
logger.Info(fmt.Sprintf("Logs for Pod: [%s]\n%s\n-----------------\n", pod.Name, buf.String())) | |
if err := podLogs.Close(); err != nil { | |
return err | |
} | |
} | |
return nil | |
}) | |
if err != nil { | |
return &ctrl.Result{}, err | |
} | |
// status updated successfully | |
return nil, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment