搜索
首页后端开发Golang如何使用 Go 客户端将本地文件复制到 minikube 集群中的 pod 容器?

如何使用 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 容器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
您如何使用PPROF工具分析GO性能?您如何使用PPROF工具分析GO性能?Mar 21, 2025 pm 06:37 PM

本文解释了如何使用PPROF工具来分析GO性能,包括启用分析,收集数据并识别CPU和内存问题等常见的瓶颈。

Debian OpenSSL有哪些漏洞Debian OpenSSL有哪些漏洞Apr 02, 2025 am 07:30 AM

OpenSSL,作为广泛应用于安全通信的开源库,提供了加密算法、密钥和证书管理等功能。然而,其历史版本中存在一些已知安全漏洞,其中一些危害极大。本文将重点介绍Debian系统中OpenSSL的常见漏洞及应对措施。DebianOpenSSL已知漏洞:OpenSSL曾出现过多个严重漏洞,例如:心脏出血漏洞(CVE-2014-0160):该漏洞影响OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻击者可利用此漏洞未经授权读取服务器上的敏感信息,包括加密密钥等。

您如何在GO中编写单元测试?您如何在GO中编写单元测试?Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

如何编写模拟对象和存根以进行测试?如何编写模拟对象和存根以进行测试?Mar 10, 2025 pm 05:38 PM

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

如何定义GO中仿制药的自定义类型约束?如何定义GO中仿制药的自定义类型约束?Mar 10, 2025 pm 03:20 PM

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

解释GO反射软件包的目的。您什么时候使用反射?绩效有什么影响?解释GO反射软件包的目的。您什么时候使用反射?绩效有什么影响?Mar 25, 2025 am 11:17 AM

本文讨论了GO的反思软件包,用于运行时操作代码,对序列化,通用编程等有益。它警告性能成本,例如较慢的执行和更高的内存使用,建议明智的使用和最佳

如何使用跟踪工具了解GO应用程序的执行流?如何使用跟踪工具了解GO应用程序的执行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化

您如何在GO中使用表驱动测试?您如何在GO中使用表驱动测试?Mar 21, 2025 pm 06:35 PM

本文讨论了GO中使用表驱动的测试,该方法使用测试用例表来测试具有多个输入和结果的功能。它突出了诸如提高的可读性,降低重复,可伸缩性,一致性和A

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具