-
Notifications
You must be signed in to change notification settings - Fork 55
/
worker.go
170 lines (140 loc) · 3.25 KB
/
worker.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/jpillora/backoff"
"golang.org/x/net/context"
)
// Backoff for fetching. It starts by waiting the minimum duration after a
// failed fetch, doubling it each time (with a bitter of jitter) up to max
// duration between requests.
var defaultBackoff = backoff.Backoff{
Min: 1 * time.Second,
Max: 5 * time.Minute,
Jitter: true,
Factor: 2,
}
// Worker is responsible for fetching data via SQL Agent
type Worker struct {
query *Query
payload []byte
client *http.Client
result *QueryResult
log *log.Logger
backoff backoff.Backoff
ctx context.Context
}
func (w *Worker) setQueryResultMetrics(recs records) {
err := w.result.SetMetrics(recs, w.query.ValueOnError)
if err != nil {
w.log.Printf("Error setting metrics: %s", err)
return
}
}
func (w *Worker) queryResultError() {
w.setQueryResultMetrics(nil)
}
func (w *Worker) fetchRecords(url string) error {
var (
t time.Time
err error
req *http.Request
resp *http.Response
)
for {
t = time.Now()
req, err = http.NewRequest("POST", url, bytes.NewBuffer(w.payload))
if err != nil {
panic(err)
}
req = req.WithContext(w.ctx)
// Set the content-type of the request body and accept LD-JSON.
req.Header.Set("content-type", "application/json")
req.Header.Set("accept", "application/json")
resp, err = w.client.Do(req)
// No formal error, but a non-successful status code. Construct an error.
if err == nil && resp.StatusCode != 200 {
b, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
err = fmt.Errorf("%s: %s", resp.Status, string(b))
}
// No error, break to read the data.
if err == nil {
break
}
w.log.Print(err)
w.queryResultError()
// Backoff on an error.
d := w.backoff.Duration()
w.log.Printf("Backing off for %s", d)
select {
case <-time.After(d):
continue
case <-w.ctx.Done():
return errors.New("Execution was canceled")
}
}
w.backoff.Reset()
w.log.Printf("Fetch took %s", time.Now().Sub(t))
var recs []record
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&recs); err != nil {
return err
}
w.setQueryResultMetrics(recs)
return nil
}
// Start fetching data from specified URL
func (w *Worker) Start(url string, wg *sync.WaitGroup) {
tick := func() {
err := w.fetchRecords(url)
if err != nil {
w.log.Printf("Error fetching records: %s", err)
return
}
}
tick()
ticker := time.NewTicker(w.query.Interval)
for {
select {
case <-w.ctx.Done():
wg.Done()
w.log.Printf("Stopping worker")
return
case <-ticker.C:
tick()
}
}
}
// NewWorker creates a new worker for a query.
func NewWorker(ctx context.Context, q *Query) *Worker {
// Encode the payload once for all subsequent requests.
payload, err := json.Marshal(map[string]interface{}{
"driver": q.Driver,
"connection": q.Connection,
"sql": q.SQL,
"params": q.Params,
})
if err != nil {
panic(err)
}
return &Worker{
query: q,
result: NewQueryResult(q),
payload: payload,
backoff: defaultBackoff,
log: log.New(os.Stderr, fmt.Sprintf("[%s] ", q.Name), log.LstdFlags),
client: &http.Client{
Timeout: q.Timeout,
},
ctx: ctx,
}
}