我的查詢與標題差不多,我有一個本地檔案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中文網其他相關文章!

Golang和Python的主要區別在於並發模型、類型系統、性能和執行速度。 1.Golang使用CSP模型,適用於高並發任務;Python依賴多線程和GIL,適合I/O密集型任務。 2.Golang是靜態類型,Python是動態類型。 3.Golang編譯型語言執行速度快,Python解釋型語言開發速度快。

Golang通常比C 慢,但Golang在並發編程和開發效率上更具優勢:1)Golang的垃圾回收和並發模型使其在高並發場景下表現出色;2)C 通過手動內存管理和硬件優化獲得更高性能,但開發複雜度較高。

Golang在雲計算和DevOps中的應用廣泛,其優勢在於簡單性、高效性和並發編程能力。 1)在雲計算中,Golang通過goroutine和channel機制高效處理並發請求。 2)在DevOps中,Golang的快速編譯和跨平台特性使其成為自動化工具的首選。

Golang和C 在執行效率上的表現各有優勢。 1)Golang通過goroutine和垃圾回收提高效率,但可能引入暫停時間。 2)C 通過手動內存管理和優化實現高性能,但開發者需處理內存洩漏等問題。選擇時需考慮項目需求和團隊技術棧。

Golang更適合高並發任務,而Python在靈活性上更有優勢。 1.Golang通過goroutine和channel高效處理並發。 2.Python依賴threading和asyncio,受GIL影響,但提供多種並發方式。選擇應基於具體需求。

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

WebStorm Mac版
好用的JavaScript開發工具