-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
streamlogs.go
56 lines (46 loc) · 1.17 KB
/
streamlogs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package streamlogs
import (
"bufio"
"context"
"strings"
"github.com/gorilla/websocket"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
)
// StreamLogs opens a log stream for the provided container and writes the
// stream to the provided WebSocket connection.
func StreamLogs(ctx context.Context, clientset *kubernetes.Clientset, conn *websocket.Conn, namespace, name, container string, since int64) error {
options := &corev1.PodLogOptions{
Container: container,
SinceSeconds: &since,
Follow: true,
}
stream, err := clientset.CoreV1().Pods(namespace).GetLogs(name, options).Stream(ctx)
if err != nil {
return err
}
defer stream.Close()
reader := bufio.NewReaderSize(stream, 16)
lastLine := ""
for {
data, isPrefix, err := reader.ReadLine()
if err != nil {
return err
}
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 {
return err
}
}
}
}