Skip to content

Commit

Permalink
Read websocket close in tail handler (#1383)
Browse files Browse the repository at this point in the history
* Read websocket close in tail handler

* Send close message to websocket on quit signals
  • Loading branch information
beornf authored and cyriltovena committed Jan 10, 2020
1 parent 8369f74 commit 88681a9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/logcli/query/tail.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ package query
import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"

"github.com/fatih/color"
"github.com/gorilla/websocket"
"github.com/grafana/loki/pkg/logcli/client"
"github.com/grafana/loki/pkg/logcli/output"
"github.com/grafana/loki/pkg/loghttp"
Expand All @@ -18,6 +22,16 @@ func (q *Query) TailQuery(delayFor int, c *client.Client, out output.LogOutput)
log.Fatalf("Tailing logs failed: %+v", err)
}

go func() {
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)
<-stopChan
if err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
log.Println("Error closing websocket:", err)
}
os.Exit(0)
}()

tailReponse := new(loghttp.TailResponse)

if len(q.IgnoreLabelsKey) > 0 {
Expand Down
19 changes: 19 additions & 0 deletions pkg/querier/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,23 @@ func (q *Querier) TailHandler(w http.ResponseWriter, r *http.Request) {
responseChan := tailer.getResponseChan()
closeErrChan := tailer.getCloseErrorChan()

doneChan := make(chan struct{})
go func() {
for {
_, _, err := conn.ReadMessage()
if err != nil {
if closeErr, ok := err.(*websocket.CloseError); ok {
if closeErr.Code == websocket.CloseNormalClosure {
break
}
level.Error(util.Logger).Log("msg", "Error from client", "err", err)
break
}
}
}
doneChan <- struct{}{}
}()

for {
select {
case response = <-responseChan:
Expand Down Expand Up @@ -214,6 +231,8 @@ func (q *Querier) TailHandler(w http.ResponseWriter, r *http.Request) {
}
return
}
case <-doneChan:
return
}
}
}
Expand Down

0 comments on commit 88681a9

Please sign in to comment.