通过websocket将kubernetes日志公开到浏览器

时间:2018-12-11 06:18:03

标签: web go logging websocket kubernetes

我试图在kubernetes中使用sidecar模式来创建日志sidecar,以公开特定的容器日志。我正在使用kubernetes客户端从kubernetes api获取日志并通过websocket发送出去。代码如下所示:

func serveWs(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        if _, ok := err.(websocket.HandshakeError); !ok {
            log.Println(err)
        }
        return
    }

    defer conn.Close()

    logsClient, err := InitKubeLogsClient(config.InCluster)
    if err != nil {
        log.Fatalln(err)
    }

    stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName)
    if err != nil {
        log.Fatalln(err)
    }
    defer stream.Close()
    reader := bufio.NewReader(stream)

    for {
        line, err := reader.ReadString('\n')
        if err != nil {
            log.Fatalln(err)
        }
        conn.WriteMessage(websocket.TextMessage, []byte(line))
    }
}

我正在将https://github.com/gorilla/websocket用作websocket库。在浏览器上

这是做我想要的最好的方法吗?有什么更好的方法可以将日志api从k8s公开到websocket?

1 个答案:

答案 0 :(得分:0)

在这里输入我的最终代码,感谢@Peter的提示:

func serveWs(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        if _, ok := err.(websocket.HandshakeError); !ok {
            log.Println(err)
        }
        return
    }

    log.Println("create new connection")

    defer func() {
        conn.Close()
        log.Println("connection close")
    }()

    logsClient, err := InitKubeLogsClient(config.InCluster)
    if err != nil {
        log.Println(err)
        return
    }

    stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName)
    if err != nil {
        log.Println(err)
        return
    }
    defer stream.Close()
    reader := bufio.NewReaderSize(stream, 16)
    lastLine := ""
    for {
        data, isPrefix, err := reader.ReadLine()
        if err != nil {
            log.Println(err)
            return
        }

        lines := strings.Split(string(data), "\r")

        length := len(lines)

        if len(lastLine) > 0 {
            lines[0] = lastLine + lines[0]
            lastLine = ""
        }

        if isPrefix {
            lastLine = lines[length-1]
            lines = lines[:(length - 1)]
        }

        for _, line := range lines {
            if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
                log.Println(err)
                return
            }
        }
    }
}