ForResource waits for a Kubernetes resource to meet the specified condition. It uses the same logic as `kubectl wait`, with retry logic for resources that don't exist yet. If identifier is empty, it will wait for any resource of the given kind to exist. This function retries on cluster connection er
(ctx context.Context, kind, identifier, condition, namespace string, timeout time.Duration)
| 39 | // If identifier is empty, it will wait for any resource of the given kind to exist. |
| 40 | // This function retries on cluster connection errors, allowing it to wait for a cluster to become available. |
| 41 | func ForResource(ctx context.Context, kind, identifier, condition, namespace string, timeout time.Duration) error { |
| 42 | l := logger.From(ctx) |
| 43 | if kind == "" { |
| 44 | return errors.New("kind is required") |
| 45 | } |
| 46 | |
| 47 | waitInterval := time.Second |
| 48 | deadline := time.Now().Add(timeout) |
| 49 | |
| 50 | condition = strings.ReplaceAll(condition, "'", "") |
| 51 | |
| 52 | // Wait for the cluster to become available by polling for a successful REST config. |
| 53 | var restConfig *rest.Config |
| 54 | var clientCfg clientcmd.ClientConfig |
| 55 | var discoveryClient *discovery.DiscoveryClient |
| 56 | err := wait.PollUntilContextTimeout(ctx, waitInterval, timeout, true, func(_ context.Context) (bool, error) { |
| 57 | var err error |
| 58 | loader := clientcmd.NewDefaultClientConfigLoadingRules() |
| 59 | clientCfg = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, nil) |
| 60 | _, restConfig, err = cluster.ClientAndConfig() |
| 61 | if err != nil { |
| 62 | l.Debug("failed to get REST config, retrying", "error", err) |
| 63 | return false, nil |
| 64 | } |
| 65 | discoveryClient, err = discovery.NewDiscoveryClientForConfig(restConfig) |
| 66 | if err != nil { |
| 67 | l.Debug("failed to get discovery client, retrying", "error", err) |
| 68 | return false, nil |
| 69 | } |
| 70 | _, err = discoveryClient.ServerVersion() |
| 71 | if err != nil { |
| 72 | l.Debug("cluster not reachable, retrying", "error", err) |
| 73 | return false, nil |
| 74 | } |
| 75 | return true, nil |
| 76 | }) |
| 77 | if err != nil { |
| 78 | return fmt.Errorf("timed out waiting for REST config: %w", err) |
| 79 | } |
| 80 | |
| 81 | if condition == "" { |
| 82 | condition = "exists" |
| 83 | } |
| 84 | |
| 85 | return waitFor(ctx, restConfig, clientCfg, kind, namespace, identifier, condition, deadline) |
| 86 | } |
| 87 | |
| 88 | // ForResourceDefaultReady waits for any resource |
| 89 | // If identifier is empty, it will wait for the given kind |
no test coverage detected