duanjipiao7076
duanjipiao7076
2018-12-11 06:18

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

  • kubernetes
  • web
  • websocket
  • logging

I am trying to use sidecar mode in kubernetes to create a logs sidecar to expose specific container logs. And I am using kubernetes client to fetch logs from kubernetes api and send it out by websocket. The code shows below:

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('
')
        if err != nil {
            log.Fatalln(err)
        }
        conn.WriteMessage(websocket.TextMessage, []byte(line))
    }
}

I am using https://github.com/gorilla/websocket as the websocket lib. And on the browser

Is this the best way to do what I want? Is there some better way to just expose the logs api from k8s to websocket?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐