execCommandOnce performs a single kubectl exec operation without retries
( ctx context.Context, client kubernetes.Interface, config *rest.Config, pod corev1.Pod, targetContainer int, timeout *time.Duration, command ...string, )
| 186 | |
| 187 | // execCommandOnce performs a single kubectl exec operation without retries |
| 188 | func execCommandOnce( |
| 189 | ctx context.Context, |
| 190 | client kubernetes.Interface, |
| 191 | config *rest.Config, |
| 192 | pod corev1.Pod, |
| 193 | targetContainer int, |
| 194 | timeout *time.Duration, |
| 195 | command ...string, |
| 196 | ) (string, string, error) { |
| 197 | req := client.CoreV1().RESTClient().Post(). |
| 198 | Resource("pods"). |
| 199 | Name(pod.Name). |
| 200 | Namespace(pod.Namespace). |
| 201 | SubResource("exec"). |
| 202 | Param("container", pod.Spec.Containers[targetContainer].Name) |
| 203 | |
| 204 | newConfig := *config // local copy avoids modifying the passed config arg |
| 205 | if timeout != nil { |
| 206 | req.Timeout(*timeout) |
| 207 | newConfig.Timeout = *timeout |
| 208 | } |
| 209 | |
| 210 | req.VersionedParams(&corev1.PodExecOptions{ |
| 211 | Container: pod.Spec.Containers[targetContainer].Name, |
| 212 | Command: command, |
| 213 | Stdout: true, |
| 214 | Stderr: true, |
| 215 | }, scheme.ParameterCodec) |
| 216 | |
| 217 | wsExecutor, err := remotecommand.NewWebSocketExecutor(&newConfig, "POST", req.URL().String()) |
| 218 | if err != nil { |
| 219 | return "", "", err |
| 220 | } |
| 221 | spdyExecutor, err := remotecommand.NewSPDYExecutor(&newConfig, "POST", req.URL()) |
| 222 | if err != nil { |
| 223 | return "", "", err |
| 224 | } |
| 225 | executor, err := remotecommand.NewFallbackExecutor(wsExecutor, spdyExecutor, shouldFallbackToSPDY) |
| 226 | if err != nil { |
| 227 | return "", "", err |
| 228 | } |
| 229 | |
| 230 | var stdout, stderr bytes.Buffer |
| 231 | err = executor.StreamWithContext(ctx, remotecommand.StreamOptions{ |
| 232 | Stdout: &stdout, |
| 233 | Stderr: &stderr, |
| 234 | }) |
| 235 | if err != nil { |
| 236 | retErr := fmt.Errorf("cmd: %s\nerror: %w\nstdErr: %v", command, err, stderr.String()) |
| 237 | return stdout.String(), stderr.String(), retErr |
| 238 | } |
| 239 | |
| 240 | return stdout.String(), stderr.String(), nil |
| 241 | } |
no test coverage detected