forked from grafana/loki
/
reader.go
231 lines (201 loc) · 5.06 KB
/
reader.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package reader
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/grafana/loki/pkg/logproto"
"github.com/grafana/loki/pkg/querier"
)
var (
reconnects = promauto.NewCounter(prometheus.CounterOpts{
Namespace: "loki_canary",
Name: "ws_reconnects",
Help: "counts every time the websocket connection has to reconnect",
})
)
type LokiReader interface {
Query(start time.Time, end time.Time) ([]time.Time, error)
}
type Reader struct {
header http.Header
tls bool
addr string
user string
pass string
lName string
lVal string
conn *websocket.Conn
w io.Writer
recv chan time.Time
quit chan struct{}
shuttingDown bool
done chan struct{}
}
func NewReader(writer io.Writer, receivedChan chan time.Time, tls bool,
address string, user string, pass string, labelName string, labelVal string) *Reader {
h := http.Header{}
if user != "" {
h = http.Header{"Authorization": {"Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))}}
}
rd := Reader{
header: h,
tls: tls,
addr: address,
user: user,
pass: pass,
lName: labelName,
lVal: labelVal,
w: writer,
recv: receivedChan,
quit: make(chan struct{}),
done: make(chan struct{}),
shuttingDown: false,
}
go rd.run()
go func() {
<-rd.quit
if rd.conn != nil {
_, _ = fmt.Fprintf(rd.w, "shutting down reader\n")
rd.shuttingDown = true
_ = rd.conn.Close()
}
}()
return &rd
}
func (r *Reader) Stop() {
if r.quit != nil {
close(r.quit)
<-r.done
r.quit = nil
}
}
func (r *Reader) Query(start time.Time, end time.Time) ([]time.Time, error) {
scheme := "http"
if r.tls {
scheme = "https"
}
u := url.URL{
Scheme: scheme,
Host: r.addr,
Path: "/api/prom/query",
RawQuery: fmt.Sprintf("start=%d&end=%d", start.UnixNano(), end.UnixNano()) +
"&query=" + url.QueryEscape(fmt.Sprintf("{stream=\"stdout\",%v=\"%v\"}", r.lName, r.lVal)) +
"&limit=1000",
}
_, _ = fmt.Fprintf(r.w, "Querying loki for missing values with query: %v\n", u.String())
client := &http.Client{}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(r.user, r.pass)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Println("error closing body", err)
}
}()
if resp.StatusCode/100 != 2 {
buf, _ := ioutil.ReadAll(resp.Body)
return nil, fmt.Errorf("error response from server: %s (%v)", string(buf), err)
}
var decoded logproto.QueryResponse
err = json.NewDecoder(resp.Body).Decode(&decoded)
if err != nil {
return nil, err
}
tss := []time.Time{}
for _, stream := range decoded.Streams {
for _, entry := range stream.Entries {
ts, err := parseResponse(&entry)
if err != nil {
_, _ = fmt.Fprint(r.w, err)
continue
}
tss = append(tss, *ts)
}
}
return tss, nil
}
func (r *Reader) run() {
r.closeAndReconnect()
tailResponse := &querier.TailResponse{}
for {
err := r.conn.ReadJSON(tailResponse)
if err != nil {
if r.shuttingDown {
close(r.done)
return
}
_, _ = fmt.Fprintf(r.w, "error reading websocket: %s\n", err)
r.closeAndReconnect()
continue
}
for _, stream := range tailResponse.Streams {
for _, entry := range stream.Entries {
ts, err := parseResponse(&entry)
if err != nil {
_, _ = fmt.Fprint(r.w, err)
continue
}
r.recv <- *ts
}
}
}
}
func (r *Reader) closeAndReconnect() {
if r.conn != nil {
_ = r.conn.Close()
r.conn = nil
// By incrementing reconnects here we should only count a failure followed by a successful reconnect.
// Initial connections and reconnections from failed tries will not be counted.
reconnects.Inc()
}
for r.conn == nil {
scheme := "ws"
if r.tls {
scheme = "wss"
}
u := url.URL{
Scheme: scheme,
Host: r.addr,
Path: "/api/prom/tail",
RawQuery: "query=" + url.QueryEscape(fmt.Sprintf("{stream=\"stdout\",%v=\"%v\"}", r.lName, r.lVal)),
}
_, _ = fmt.Fprintf(r.w, "Connecting to loki at %v, querying for label '%v' with value '%v'\n", u.String(), r.lName, r.lVal)
c, _, err := websocket.DefaultDialer.Dial(u.String(), r.header)
if err != nil {
_, _ = fmt.Fprintf(r.w, "failed to connect to %s with err %s\n", u.String(), err)
<-time.After(5 * time.Second)
continue
}
r.conn = c
}
}
func parseResponse(entry *logproto.Entry) (*time.Time, error) {
sp := strings.Split(entry.Line, " ")
if len(sp) != 2 {
return nil, errors.Errorf("received invalid entry: %s\n", entry.Line)
}
ts, err := strconv.ParseInt(sp[0], 10, 64)
if err != nil {
return nil, errors.Errorf("failed to parse timestamp: %s\n", sp[0])
}
t := time.Unix(0, ts)
return &t, nil
}