搜尋
首頁後端開發Golang在 pod 中執行特定命令時出現錯誤

在 pod 中运行特定命令时出现错误

php小编鱼仔在使用pod运行特定命令时遇到了错误。这个问题对于开发人员来说是非常常见的,但解决起来可能会有些困难。当我们在pod中执行特定命令时出现错误,这可能是由于多种因素引起的,比如版本不兼容、依赖关系问题等。在解决这个问题之前,我们需要先确定具体的错误信息,然后逐步排查和解决。在本文中,我们将介绍一些常见的错误情况和相应的解决方案,希望能帮助到遇到类似问题的开发人员。

问题内容

我正在尝试在正在运行的 pod 中执行命令。我正在使用 go k8sclient 来实现此目的,但遇到了问题。我也不知道解决方案是否正确。任何人都可以检查并提供正确的解决方案吗?

这是我的代码。

namespace := getnamespace()
        podname := "maxscale-0"

        config, err := rest.inclusterconfig()
        if err != nil {
                log.fatal(err)
        }

        clientset, err := kubernetes.newforconfig(config)
        if err != nil {
                log.fatal(err)
        }



        req := clientset.corev1().pods(namespace).exec(podname, &corev1.podexecoptions{
                command: []string{"sh", "-c", "grep -op '\"name\": \"\\k[^\"]*' /var/lib/maxscale/mariadb-monitor_journal.json"},
        })

        // set up a stream to capture the output
        execstream, err := req.stream()
        if err != nil {
                fmt.println(err)
                os.exit(1)
        }

        // print the output
        buf := new(bytes.buffer)
        buf.readfrom(execstream)
        fmt.println(buf.string())

我得到的错误是

clientset.CoreV1().Pods(namespace).Exec undefined (type "k8s.io/client-go/kubernetes/typed/core/v1".PodInterface has no field or method Exec)

解决方法

正如 @david maze 所分享的,要使用 k8 的 go 客户端在 pod 中执行命令,请遵循以下代码:

import (
    "io"

    v1 "k8s.io/api/core/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/kubernetes/scheme"
    restclient "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/remotecommand"
)

// ExecCmd exec command on specific pod and wait the command's output.
func ExecCmdExample(client kubernetes.Interface, config *restclient.Config, podName string,
    command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
    cmd := []string{
        "sh",
        "-c",
        command,
    }
    req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
        Namespace("default").SubResource("exec")
    option := &v1.PodExecOptions{
        Command: cmd,
        Stdin:   true,
        Stdout:  true,
        Stderr:  true,
        TTY:     true,
    }
    if stdin == nil {
        option.Stdin = false
    }
    req.VersionedParams(
        option,
        scheme.ParameterCodec,
    )
    exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    if err != nil {
        return err
    }
    err = exec.Stream(remotecommand.StreamOptions{
        Stdin:  stdin,
        Stdout: stdout,
        Stderr: stderr,
    })
    if err != nil {
        return err
    }

    return nil
}

另请参阅此链接了解更多信息

以上是在 pod 中執行特定命令時出現錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

使用微服務體系結構的好處使用微服務體系結構的好處Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具