feat: implement run and run:detached
This utilizes a Kubernetes Job to start a pod in order to take advantage of completed Job cleanup in Kubernetes. It also properly handles interactivity by ensuring the container has a TTY. Note that there is currently no provision for parsing docker arguments and translating them into their Kubernetes equivalents.
This commit is contained in:
1 parent
6b85374857
commit
8b8444fb1f
10 files changed
+833
-115
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
"github.com/dokku/dokku/plugins/common"
|
||||
"github.com/dokku/dokku/plugins/config"
|
||||
"github.com/fatih/color"
|
||||
"github.com/kballard/go-shellquote"
|
||||
"github.com/rancher/wharfie/pkg/registries"
|
||||
orderedmap "github.com/wk8/go-ordered-map/v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -26,9 +28,11 @@ import (
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
|
||||
"k8s.io/client-go/tools/remotecommand"
|
||||
"k8s.io/kubectl/pkg/util/term"
|
||||
"k8s.io/kubernetes/pkg/client/conditions"
|
||||
"k8s.io/utils/ptr"
|
||||
)
|
||||
|
||||
@@ -205,10 +209,9 @@ func TriggerSchedulerDeploy(scheduler string, appName string, imageTag string) e
|
||||
Env: env.Map(),
|
||||
Namespace: namespace,
|
||||
})
|
||||
err = printResource(PrintInput{
|
||||
err = writeResourceToFile(WriteResourceInput{
|
||||
Object: &secret,
|
||||
Path: filepath.Join(chartDir, "templates/secret.yaml"),
|
||||
Name: secret.Name,
|
||||
Replacements: replacements,
|
||||
AppendContents: `{{- with .Values.secrets }}
|
||||
data:
|
||||
@@ -265,6 +268,7 @@ data:
|
||||
PortMaps: portMaps,
|
||||
ProcessType: processType,
|
||||
Replicas: replicaCountPlaceholder,
|
||||
WorkingDir: common.GetWorkingDir(appName, image),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error templating deployment: %w", err)
|
||||
@@ -272,10 +276,9 @@ data:
|
||||
|
||||
replacements.Set(fmt.Sprintf("replicas: %d", replicaCountPlaceholder), fmt.Sprintf("replicas: {{.Values.processes.%s.replicas}}", processType))
|
||||
deployments[processType] = deployment
|
||||
err = printResource(PrintInput{
|
||||
err = writeResourceToFile(WriteResourceInput{
|
||||
Object: &deployment,
|
||||
Path: filepath.Join(chartDir, fmt.Sprintf("templates/deployment-%s.yaml", deployment.Name)),
|
||||
Name: deployment.Name,
|
||||
Replacements: replacements,
|
||||
})
|
||||
replacements.Delete(fmt.Sprintf("replicas: %d", replicaCountPlaceholder))
|
||||
@@ -292,10 +295,9 @@ data:
|
||||
PortMaps: portMaps,
|
||||
})
|
||||
|
||||
err := printResource(PrintInput{
|
||||
err := writeResourceToFile(WriteResourceInput{
|
||||
Object: &service,
|
||||
Path: filepath.Join(chartDir, "templates/service-web.yaml"),
|
||||
Name: service.Name,
|
||||
Replacements: replacements,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -473,27 +475,52 @@ func TriggerSchedulerEnter(scheduler string, appName string, processType string,
|
||||
}
|
||||
}
|
||||
|
||||
coreclient, err := corev1client.NewForConfig(&clientset.RestConfig)
|
||||
entrypoint := ""
|
||||
if selectedPod.Annotations["dokku.com/builder-type"] == "herokuish" {
|
||||
entrypoint = "/exec"
|
||||
}
|
||||
|
||||
return enterPod(ctx, EnterPodInput{
|
||||
AppName: appName,
|
||||
Clientset: clientset,
|
||||
Command: command,
|
||||
Entrypoint: entrypoint,
|
||||
ProcessType: processType,
|
||||
SelectedPod: selectedPod,
|
||||
})
|
||||
}
|
||||
|
||||
type EnterPodInput struct {
|
||||
AppName string
|
||||
Clientset KubernetesClient
|
||||
Command []string
|
||||
Entrypoint string
|
||||
ProcessType string
|
||||
SelectedPod v1.Pod
|
||||
}
|
||||
|
||||
func enterPod(ctx context.Context, input EnterPodInput) error {
|
||||
coreclient, err := corev1client.NewForConfig(&input.Clientset.RestConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating corev1 client: %w", err)
|
||||
}
|
||||
|
||||
req := coreclient.RESTClient().Post().
|
||||
Resource("pods").
|
||||
Namespace(selectedPod.Namespace).
|
||||
Name(selectedPod.Name).
|
||||
Namespace(input.SelectedPod.Namespace).
|
||||
Name(input.SelectedPod.Name).
|
||||
SubResource("exec")
|
||||
|
||||
req.Param("container", fmt.Sprintf("%s-%s", appName, processType))
|
||||
req.Param("container", fmt.Sprintf("%s-%s", input.AppName, input.ProcessType))
|
||||
req.Param("stdin", "true")
|
||||
req.Param("stdout", "true")
|
||||
req.Param("stderr", "true")
|
||||
req.Param("tty", "true")
|
||||
|
||||
if selectedPod.Annotations["dokku.com/builder-type"] == "herokuish" {
|
||||
req.Param("command", "/exec")
|
||||
if input.Entrypoint != "" {
|
||||
req.Param("command", input.Entrypoint)
|
||||
}
|
||||
for _, cmd := range command {
|
||||
for _, cmd := range input.Command {
|
||||
req.Param("command", cmd)
|
||||
}
|
||||
|
||||
@@ -506,7 +533,7 @@ func TriggerSchedulerEnter(scheduler string, appName string, processType string,
|
||||
sizeQueue := t.MonitorSize(size)
|
||||
|
||||
return t.Safe(func() error {
|
||||
exec, err := remotecommand.NewSPDYExecutor(&clientset.RestConfig, "POST", req.URL())
|
||||
exec, err := remotecommand.NewSPDYExecutor(&input.Clientset.RestConfig, "POST", req.URL())
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating executor: %w", err)
|
||||
}
|
||||
@@ -571,7 +598,7 @@ func TriggerSchedulerLogs(scheduler string, appName string, processType string,
|
||||
ch := make(chan bool)
|
||||
podItems := podList.Items
|
||||
|
||||
if os.Getenv("FORCE_COLOR") == "1" {
|
||||
if os.Getenv("FORCE_TTY") == "1" {
|
||||
color.NoColor = false
|
||||
}
|
||||
|
||||
@@ -692,3 +719,440 @@ func TriggerSchedulerStop(scheduler string, appName string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// TriggerSchedulerRun runs a command in an ephemeral container
|
||||
func TriggerSchedulerRun(scheduler string, appName string, envCount int, args []string) error {
|
||||
if scheduler != "k3s" {
|
||||
return nil
|
||||
}
|
||||
|
||||
extraEnv := map[string]string{}
|
||||
if envCount > 0 {
|
||||
var envPairs []string
|
||||
envPairs, args = args[0:envCount], args[envCount:]
|
||||
for _, envPair := range envPairs {
|
||||
parts := strings.SplitN(envPair, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("Invalid environment variable pair: %s", envPair)
|
||||
}
|
||||
extraEnv[parts[0]] = parts[1]
|
||||
}
|
||||
}
|
||||
|
||||
imageTag, err := common.GetRunningImageTag(appName, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting running image tag: %w", err)
|
||||
}
|
||||
imageRepo := common.GetAppImageRepo(appName)
|
||||
image, err := common.GetDeployingAppImageName(appName, imageTag, imageRepo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting deploying app image name: %w", err)
|
||||
}
|
||||
|
||||
imageStage, err := common.DockerInspect(image, "{{ index .Config.Labels \"com.dokku.image-stage\" }}")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting image stage: %w", err)
|
||||
}
|
||||
if imageStage != "release" {
|
||||
common.LogWarn("Invalid image stage detected: expected 'release', got '$IMAGE_STAGE'")
|
||||
return fmt.Errorf("Successfully deploy your app to fix dokku run calls")
|
||||
}
|
||||
|
||||
dokkuRmContainer := os.Getenv("DOKKU_RM_CONTAINER")
|
||||
if dokkuRmContainer == "" {
|
||||
appRmContainer, err := common.CallPlugnTrigger(common.PlugnTriggerInput{
|
||||
Trigger: "config-get",
|
||||
Args: []string{appName, "DOKKU_RM_CONTAINER"},
|
||||
CaptureOutput: true,
|
||||
StreamStdio: false,
|
||||
})
|
||||
if err != nil {
|
||||
globalRmContainer, err := common.CallPlugnTrigger(common.PlugnTriggerInput{
|
||||
Trigger: "config-get-global",
|
||||
Args: []string{"DOKKU_RM_CONTAINER"},
|
||||
CaptureOutput: true,
|
||||
StreamStdio: false,
|
||||
})
|
||||
if err == nil {
|
||||
dokkuRmContainer = globalRmContainer.Stdout
|
||||
}
|
||||
} else {
|
||||
dokkuRmContainer = appRmContainer.Stdout
|
||||
}
|
||||
}
|
||||
if dokkuRmContainer == "" {
|
||||
dokkuRmContainer = "true"
|
||||
}
|
||||
|
||||
rmContainer, err := strconv.ParseBool(dokkuRmContainer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error parsing DOKKU_RM_CONTAINER value as boolean: %w", err)
|
||||
}
|
||||
|
||||
labels := map[string]string{
|
||||
"dokku.com/app-name": appName,
|
||||
}
|
||||
|
||||
if os.Getenv("DOKKU_TRACE") == "1" {
|
||||
extraEnv["TRACE"] = "true"
|
||||
}
|
||||
|
||||
processType := "run"
|
||||
if os.Getenv("DOKKU_CRON_ID") != "" {
|
||||
processType = "cron"
|
||||
labels["dokku.com/cron-id"] = os.Getenv("DOKKU_CRON_ID")
|
||||
}
|
||||
|
||||
dockerArgs := []string{}
|
||||
if b, err := common.PlugnTriggerSetup("docker-args-run", []string{appName, imageTag}...).SetInput("").Output(); err == nil {
|
||||
words, err := shellquote.Split(strings.TrimSpace(string(b[:])))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dockerArgs = append(dockerArgs, words...)
|
||||
}
|
||||
|
||||
imageSourceType, err := common.DockerInspect(image, "{{ index .Config.Labels \"com.dokku.builder-type\" }}")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting image builder type: %w", err)
|
||||
}
|
||||
|
||||
if b, err := common.PlugnTriggerSetup("docker-args-process-run", []string{appName, imageSourceType, imageTag}...).SetInput("").Output(); err == nil {
|
||||
words, err := shellquote.Split(strings.TrimSpace(string(b[:])))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dockerArgs = append(dockerArgs, words...)
|
||||
}
|
||||
|
||||
// todo: do something with docker args
|
||||
command := args
|
||||
if len(args) == 0 {
|
||||
command = []string{"/bin/bash"}
|
||||
if globalShell, err := common.PlugnTriggerOutputAsString("config-get-global", []string{"DOKKU_APP_SHELL"}...); err == nil && globalShell != "" {
|
||||
command = []string{globalShell}
|
||||
}
|
||||
if appShell, err := common.PlugnTriggerOutputAsString("config-get", []string{appName, "DOKKU_APP_SHELL"}...); err == nil && appShell != "" {
|
||||
command = []string{appShell}
|
||||
}
|
||||
} else if len(args) == 1 {
|
||||
resp, err := common.CallPlugnTrigger(common.PlugnTriggerInput{
|
||||
Trigger: "procfile-get-command",
|
||||
Args: []string{appName, args[0], "5000"},
|
||||
CaptureOutput: true,
|
||||
StreamStdio: false,
|
||||
})
|
||||
if err == nil && resp.Stdout != "" {
|
||||
common.LogInfo1Quiet(fmt.Sprintf("Found '%s' in Procfile, running that command", args[0]))
|
||||
return err
|
||||
}
|
||||
// todo: run command in procfile
|
||||
}
|
||||
|
||||
entrypoint := ""
|
||||
if imageSourceType == "herokuish" {
|
||||
entrypoint = "/exec"
|
||||
}
|
||||
|
||||
namespace := common.PropertyGetDefault("scheduler-k3s", appName, "namespace", "default")
|
||||
helmAgent, err := NewHelmAgent(namespace, DevNullPrinter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating helm agent: %w", err)
|
||||
}
|
||||
|
||||
values, err := helmAgent.GetValues(fmt.Sprintf("dokku-%s", appName))
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting helm values: %w", err)
|
||||
}
|
||||
|
||||
deploymentIDValue, ok := values["deploment_id"].(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("Deployment ID is not a string")
|
||||
}
|
||||
if len(deploymentIDValue) == 0 {
|
||||
return fmt.Errorf("Deployment ID is empty")
|
||||
}
|
||||
deploymentID, err := strconv.ParseInt(deploymentIDValue, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error parsing deployment ID: %w", err)
|
||||
}
|
||||
|
||||
attachToPod := os.Getenv("DOKKU_DETACH_CONTAINER") != "1"
|
||||
imagePullSecrets := common.PropertyGetDefault("scheduler-k3s", appName, "image-pull-secrets", "")
|
||||
workingDir := common.GetWorkingDir(appName, image)
|
||||
job, err := templateKubernetesJob(Job{
|
||||
AppName: appName,
|
||||
Command: command,
|
||||
DeploymentID: deploymentID,
|
||||
Entrypoint: entrypoint,
|
||||
Env: extraEnv,
|
||||
Image: image,
|
||||
ImagePullSecrets: imagePullSecrets,
|
||||
ImageSourceType: imageSourceType,
|
||||
Interactive: attachToPod,
|
||||
Labels: labels,
|
||||
Namespace: namespace,
|
||||
ProcessType: processType,
|
||||
RemoveContainer: rmContainer,
|
||||
WorkingDir: workingDir,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error templating job: %w", err)
|
||||
}
|
||||
|
||||
if os.Getenv("FORCE_TTY") == "1" {
|
||||
color.NoColor = false
|
||||
}
|
||||
|
||||
err = writeResourceToFile(WriteResourceInput{
|
||||
Object: &job,
|
||||
Path: "/tmp/job.yaml",
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error writing job: %w", err)
|
||||
}
|
||||
common.CatFile("/tmp/job.yaml")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, os.Interrupt, syscall.SIGHUP,
|
||||
syscall.SIGINT,
|
||||
syscall.SIGQUIT,
|
||||
syscall.SIGTERM)
|
||||
go func() {
|
||||
<-signals
|
||||
cancel()
|
||||
}()
|
||||
|
||||
createdJob, err := createKubernetesJob(ctx, job)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating job: %w", err)
|
||||
}
|
||||
|
||||
clientset, err := NewKubernetesClient()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error creating kubernetes client: %w", err)
|
||||
}
|
||||
|
||||
batchJobSelector := fmt.Sprintf("batch.kubernetes.io/job-name=%s", createdJob.Name)
|
||||
podList, err := WaitForPodToExist(ctx, WaitForPodToExistInput{
|
||||
Clientset: clientset,
|
||||
Namespace: namespace,
|
||||
RetryCount: 3,
|
||||
Selector: batchJobSelector,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error waiting for pod to exist: %w", err)
|
||||
}
|
||||
|
||||
for _, pod := range podList.Items {
|
||||
common.LogQuiet(pod.Name)
|
||||
}
|
||||
|
||||
if !attachToPod {
|
||||
return nil
|
||||
}
|
||||
|
||||
err = WaitForPodBySelectorRunning(ctx, WaitForPodBySelectorRunningInput{
|
||||
Clientset: clientset,
|
||||
Namespace: namespace,
|
||||
Selector: batchJobSelector,
|
||||
Timeout: 300,
|
||||
Waiter: isPodReady,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, conditions.ErrPodCompleted) {
|
||||
podList, podErr := GetPod(ctx, GetPodInput{
|
||||
Clientset: clientset,
|
||||
Namespace: namespace,
|
||||
Selector: batchJobSelector,
|
||||
})
|
||||
if podErr != nil {
|
||||
return fmt.Errorf("Error completed pod: %w", err)
|
||||
}
|
||||
selectedPod := podList.Items[0]
|
||||
if selectedPod.Status.Phase == v1.PodFailed {
|
||||
for _, status := range selectedPod.Status.ContainerStatuses {
|
||||
if status.Name != fmt.Sprintf("%s-%s", appName, processType) {
|
||||
continue
|
||||
}
|
||||
if status.State.Terminated == nil {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("Unable to attach as the pod has already exited with a failed exit code: %s", status.State.Terminated.Message)
|
||||
}
|
||||
|
||||
return fmt.Errorf("Unable to attach as the pod has already exited with a failed exit code")
|
||||
} else if selectedPod.Status.Phase == v1.PodSucceeded {
|
||||
return errors.New("Unable to attach as the pod has already exited with a successful exit code")
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("Error waiting for pod to be running: %w", err)
|
||||
}
|
||||
|
||||
podList, err = GetPod(ctx, GetPodInput{
|
||||
Clientset: clientset,
|
||||
Namespace: namespace,
|
||||
Selector: batchJobSelector,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error getting pod: %w", err)
|
||||
}
|
||||
selectedPod := podList.Items[0]
|
||||
|
||||
switch selectedPod.Status.Phase {
|
||||
case v1.PodFailed, v1.PodSucceeded:
|
||||
if selectedPod.Status.Phase == v1.PodFailed {
|
||||
for _, status := range selectedPod.Status.ContainerStatuses {
|
||||
if status.Name != fmt.Sprintf("%s-%s", appName, processType) {
|
||||
continue
|
||||
}
|
||||
if status.State.Terminated == nil {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("Unable to attach as the pod has already exited with a failed exit code: %s", status.State.Terminated.Message)
|
||||
}
|
||||
|
||||
return fmt.Errorf("Unable to attach as the pod has already exited with a failed exit code")
|
||||
} else if selectedPod.Status.Phase == v1.PodSucceeded {
|
||||
return errors.New("Unable to attach as the pod has already exited with a successful exit code")
|
||||
}
|
||||
case v1.PodRunning:
|
||||
err := enterPod(ctx, EnterPodInput{
|
||||
AppName: appName,
|
||||
Clientset: clientset,
|
||||
Command: command,
|
||||
Entrypoint: entrypoint,
|
||||
ProcessType: processType,
|
||||
SelectedPod: selectedPod,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = clientset.Client.BatchV1().Jobs(namespace).Delete(ctx, createdJob.Name, metav1.DeleteOptions{
|
||||
PropagationPolicy: ptr.To(metav1.DeletePropagationForeground),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error deleting pod: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("Unable to attach as the pod is in an unknown state: %s", selectedPod.Status.Phase)
|
||||
}
|
||||
// todo: support scheduler-post-run
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isPodReady(ctx context.Context, clientset KubernetesClient, podName, namespace string) wait.ConditionWithContextFunc {
|
||||
return func(ctx context.Context) (bool, error) {
|
||||
fmt.Printf(".") // progress bar!
|
||||
|
||||
pod, err := clientset.Client.CoreV1().Pods(namespace).Get(ctx, podName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
switch pod.Status.Phase {
|
||||
case v1.PodRunning:
|
||||
return true, nil
|
||||
case v1.PodFailed, v1.PodSucceeded:
|
||||
return false, conditions.ErrPodCompleted
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func isPodComplete(ctx context.Context, clientset KubernetesClient, podName, namespace string) wait.ConditionWithContextFunc {
|
||||
return func(ctx context.Context) (bool, error) {
|
||||
fmt.Printf(".") // progress bar!
|
||||
|
||||
pod, err := clientset.Client.CoreV1().Pods(namespace).Get(ctx, podName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
switch pod.Status.Phase {
|
||||
case v1.PodFailed, v1.PodSucceeded:
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
type WaitForPodBySelectorRunningInput struct {
|
||||
Clientset KubernetesClient
|
||||
Namespace string
|
||||
Selector string
|
||||
Timeout int
|
||||
Waiter func(ctx context.Context, clientset KubernetesClient, podName, namespace string) wait.ConditionWithContextFunc
|
||||
}
|
||||
|
||||
type WaitForPodToExistInput struct {
|
||||
Clientset KubernetesClient
|
||||
Namespace string
|
||||
RetryCount int
|
||||
Selector string
|
||||
}
|
||||
|
||||
func WaitForPodToExist(ctx context.Context, input WaitForPodToExistInput) (v1.PodList, error) {
|
||||
var podList v1.PodList
|
||||
var err error
|
||||
for i := 0; i < input.RetryCount; i++ {
|
||||
podList, err = GetPod(ctx, GetPodInput{
|
||||
Clientset: input.Clientset,
|
||||
Namespace: input.Namespace,
|
||||
Selector: input.Selector,
|
||||
})
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
return podList, fmt.Errorf("Error listing pods: %w", err)
|
||||
}
|
||||
return podList, nil
|
||||
}
|
||||
|
||||
type GetPodInput struct {
|
||||
Clientset KubernetesClient
|
||||
Namespace string
|
||||
Selector string
|
||||
}
|
||||
|
||||
func GetPod(ctx context.Context, input GetPodInput) (v1.PodList, error) {
|
||||
listOptions := metav1.ListOptions{LabelSelector: input.Selector}
|
||||
podList, err := input.Clientset.Client.CoreV1().Pods(input.Namespace).List(ctx, listOptions)
|
||||
return *podList, err
|
||||
}
|
||||
|
||||
func WaitForPodBySelectorRunning(ctx context.Context, input WaitForPodBySelectorRunningInput) error {
|
||||
podList, err := WaitForPodToExist(ctx, WaitForPodToExistInput{
|
||||
Clientset: input.Clientset,
|
||||
Namespace: input.Namespace,
|
||||
RetryCount: 3,
|
||||
Selector: input.Selector,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error waiting for pod to exist: %w", err)
|
||||
}
|
||||
|
||||
if len(podList.Items) == 0 {
|
||||
return fmt.Errorf("no pods in %s with selector %s", input.Namespace, input.Selector)
|
||||
}
|
||||
|
||||
timeout := time.Duration(input.Timeout) * time.Second
|
||||
for _, pod := range podList.Items {
|
||||
if err := wait.PollUntilContextTimeout(ctx, time.Second, timeout, false, input.Waiter(ctx, input.Clientset, pod.Name, pod.Namespace)); err != nil {
|
||||
print("\n")
|
||||
return err
|
||||
}
|
||||
}
|
||||
print("\n")
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user