-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add possibility to exec a command in a pod. (#158)
* Add possibility to exec a command in a pod. * Add possibility to exec a command in a pod.
- Loading branch information
Christian Bianchi
committed
Mar 11, 2024
1 parent
ad32e68
commit d64f5ba
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package client | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
|
||
corev1 "k8s.io/api/core/v1" | ||
"k8s.io/client-go/kubernetes" | ||
"k8s.io/client-go/tools/remotecommand" | ||
"k8s.io/kubectl/pkg/scheme" | ||
|
||
"github.com/giantswarm/clustertest/pkg/logger" | ||
) | ||
|
||
func (c *Client) ExecInPod(ctx context.Context, podName, namespace, containerName string, command []string) (string, string, error) { | ||
logger.Log("Running %v in container %q in pod %q", command, containerName, podName) | ||
|
||
tty := true | ||
|
||
coreClient, err := kubernetes.NewForConfig(c.config) | ||
if err != nil { | ||
return "", "", fmt.Errorf("failed initializing kubernetes core client - %v", err) | ||
} | ||
|
||
req := coreClient.CoreV1().RESTClient().Post(). | ||
Resource("pods"). | ||
Name(podName). | ||
Namespace(namespace). | ||
SubResource("exec"). | ||
Param("container", containerName) | ||
req.VersionedParams(&corev1.PodExecOptions{ | ||
Container: containerName, | ||
Command: command, | ||
Stdin: false, | ||
Stdout: true, | ||
Stderr: true, | ||
TTY: tty, | ||
}, scheme.ParameterCodec) | ||
|
||
var stdout, stderr bytes.Buffer | ||
exec, err := remotecommand.NewSPDYExecutor(c.config, "POST", req.URL()) | ||
if err != nil { | ||
return "", "", fmt.Errorf("failed to exec command in pod - %v", err) | ||
} | ||
|
||
err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{ | ||
Stdin: nil, | ||
Stdout: &stdout, | ||
Stderr: &stderr, | ||
Tty: tty, | ||
}) | ||
if err != nil { | ||
return "", "", fmt.Errorf("failed to exec command in pod - %v", err) | ||
} | ||
|
||
return stdout.String(), stderr.String(), err | ||
} |