使用 Go 客户端将本地文件复制到 minikube 集群中的 pod 容器的方法
来源:stackoverflow
时间:2024-03-20 18:39:26 385浏览 收藏
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《使用 Go 客户端将本地文件复制到 minikube 集群中的 pod 容器的方法》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
我的查询与标题差不多,我有一个本地文件 file.txt ,我想将其复制到 pod1 的容器 container1 中。
如果我使用 kubectl 来执行此操作,适当的命令是:
kubectl cp file.txt pod1:file.txt -c container1
但是,如何使用 kubectl 的 go 客户端来实现呢?
我尝试了两种方法,但都不起作用:
import (
"fmt"
"context"
"log"
"os"
"path/filepath"
g "github.com/sdslabs/katana/configs"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
//"k8s.io/kubectl/pkg/cmd/exec"
)
func copyintopod(namespace string, podname string, containername string, srcpath string, dstpath string) {
// create a kubernetes client
config, err := getkubeconfig()
if err != nil {
log.fatal(err)
}
client, err := kubernetes.newforconfig(config)
if err != nil {
log.fatal(err)
}
// build the command to execute
cmd := []string{"cp", srcpath, dstpath}
// use the podexecoptions struct to specify the options for the exec request
options := v1.podexecoptions{
container: containername,
command: cmd,
stdin: false,
stdout: true,
stderr: true,
tty: false,
}
log.println("options set!")
// use the corev1api.exec method to execute the command inside the container
req := client.corev1().restclient().post().
namespace(namespace).
name(podname).
resource("pods").
subresource("exec").
versionedparams(&options, metav1.parametercodec)
log.println("request generated")
exec, err := req.stream(context.todo())
if err != nil {
log.fatal(err)
}
defer exec.close()
// read the response from the exec command
var result []byte
if _, err := exec.read(result); err != nil {
log.fatal(err)
}
fmt.println("file copied successfully!")
}
这给了我错误消息:
no 类型已在方案“pkg/runtime/scheme.go:100” 中为 v1.podexecoptions 类型注册
我无法弄清楚,所以我尝试了另一种方法:
type PodExec struct {
RestConfig *rest.Config
*kubernetes.Clientset
}
func NewPodExec(config *rest.Config, clientset *kubernetes.Clientset) *PodExec {
config.APIPath = "/api" // Make sure we target /api and not just /
config.GroupVersion = &schema.GroupVersion{Version: "v1"} // this targets the core api groups so the url path will be /api/v1
config.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: scheme.Codecs}
return &PodExec{
RestConfig: config,
Clientset: clientset,
}
}
func (p *PodExec) PodCopyFile(src string, dst string, containername string, podNamespace string) (*bytes.Buffer, *bytes.Buffer, *bytes.Buffer, error) {
ioStreams, in, out, errOut := genericclioptions.NewTestIOStreams()
copyOptions := cp.NewCopyOptions(ioStreams)
copyOptions.Clientset = p.Clientset
copyOptions.ClientConfig = p.RestConfig
copyOptions.Container = containername
copyOptions.Namespace = podNamespace
err := copyOptions.Run()
if err != nil {
return nil, nil, nil, fmt.Errorf("could not run copy operation: %v", err)
}
return in, out, errOut, nil
}
但是,copyoptions.run()命令存在一些问题,它尝试在copyoptions内查找o.args[0]和o.args[0],但o未导入,因此无法导入进行修改。
上下文:https://pkg.go.dev/k8s.io/kubectl/pkg/cmd/cp#copyoptions.run
所以,现在我真的很迷失和困惑。任何帮助,将不胜感激。谢谢。
编辑:我确实想到了一个可行的方法,我们可以直接调用 cmd.exec() 并直接运行 kubectl cp 命令,但看起来有点老套,我不确定它是否有效,有什么想法吗?
正确答案
这就是我最终成功做到这一点的方法:
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/remotecommand"
)
func CopyIntoPod(podName string, namespace string, containerName string, srcPath string, dstPath string) {
// Get the default kubeconfig file
kubeConfig := filepath.Join(homedir.HomeDir(), ".kube", "config")
// Create a config object using the kubeconfig file
config, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
if err != nil {
fmt.Printf("Error creating config: %s\n", err)
return
}
// Create a Kubernetes client
client, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Printf("Error creating client: %s\n", err)
return
}
// Open the file to copy
localFile, err := os.Open(srcPath)
if err != nil {
fmt.Printf("Error opening local file: %s\n", err)
return
}
defer localFile.Close()
pod, err := client.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error getting pod: %s\n", err)
return
}
// Find the container in the pod
var container *corev1.Container
for _, c := range pod.Spec.Containers {
if c.Name == containerName {
container = &c
break
}
}
if container == nil {
fmt.Printf("Container not found in pod\n")
return
}
// Create a stream to the container
req := client.CoreV1().RESTClient().Post().
Resource("pods").
Name(podName).
Namespace(namespace).
SubResource("exec").
Param("container", containerName)
req.VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: []string{"bash", "-c", "cat > " + dstPath},
Stdin: true,
Stdout: true,
Stderr: true,
}, scheme.ParameterCodec)
exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
fmt.Printf("Error creating executor: %s\n", err)
return
}
// Create a stream to the container
err = exec.StreamWithContext(context.TODO(), remotecommand.StreamOptions{
Stdin: localFile,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
})
if err != nil {
fmt.Printf("Error streaming: %s\n", err)
return
}
fmt.Println("File copied successfully")
}文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Go 客户端将本地文件复制到 minikube 集群中的 pod 容器的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习