gpt4 book ai didi

go - 如何使用kubernetes client-go将文件复制到容器?

转载 作者:数据小太阳 更新时间:2023-10-29 03:02:57 26 4
gpt4 key购买 nike

我想使用 https://github.com/kubernetes/client-go将文件从我的文件系统复制到容器,反之亦然。

kubectl cp <file-spec-src> <file-spec-dest> -c <specific-container>

go 客户端中是否有封装调用的函数?或者我可以使用类似 RESTClient 的东西吗? ?

最佳答案

由于这个问题的答案很老,所以我是这样做的:

package main

import (
"bytes"
"fmt"
"io"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/kubectl/pkg/cmd/cp"
"k8s.io/kubectl/pkg/cmd/exec"
"log"
"os"
)

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) (*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
err := copyOptions.Run([]string{src, dst})
if err != nil {
return nil, nil, nil, fmt.Errorf("Could not run copy operation: %v", err)
}
return in, out, errOut, nil
}

然后你可以像 kubectl cp 一样使用 PodCopyFile

podExec := podexec.NewPodExec(*restconfig, clientset) // Here, you need to get your restconfig and clientset from either ~/.kube/config or built-in pod config.
_, out, _, err := podExec.PodCopyFile("/srcfile", "/dstfile", "containername")
if err != nil {
fmt.Printf("%v\n", err)
}
fmt.Println("out:")
fmt.Printf("%s", out.String())

关于go - 如何使用kubernetes client-go将文件复制到容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51686986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com