This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathingest.go
252 lines (194 loc) · 5.75 KB
/
ingest.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"context"
"encoding/json"
"net/url"
"strconv"
"sync"
"time"
"github.com/gammazero/workerpool"
"github.com/packethost/cacher/hardware"
"github.com/packethost/packngo"
"github.com/packethost/pkg/env"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
func fetchFacilityPage(ctx context.Context, client *packngo.Client, u string) ([]map[string]interface{}, uint, error) {
req, err := client.NewRequest("GET", u, nil)
if err != nil {
return nil, 0, errors.Wrap(err, "failed to create fetch request")
}
req = req.WithContext(ctx)
req.Header.Add("X-Packet-Staff", "true")
r := struct {
Meta struct {
CurrentPage int `json:"current_page"`
LastPage int `json:"last_page"`
Total int `json:"total"`
}
Hardware []map[string]interface{}
}{}
_, err = client.Do(req, &r)
if err != nil {
return nil, 0, errors.Wrap(err, "failed to fetch page")
}
return r.Hardware, uint(r.Meta.Total), nil
}
func fetchFacility(ctx context.Context, client *packngo.Client, api *url.URL, facility string, data chan<- []map[string]interface{}) error {
logger.Info("fetch start")
labels := prometheus.Labels{"method": "Ingest", "op": "fetch"}
ingestCount.With(labels).Inc()
timer := prometheus.NewTimer(prometheus.ObserverFunc(ingestDuration.With(labels).Set))
concurrentFetches := env.Int("CACHER_CONCURRENT_FETCHES", 4)
pool := workerpool.New(concurrentFetches)
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.Int("CACHER_CONCURRENT_FETCHES", concurrentFetches))
defer close(data)
api.Path = "/staff/cacher/hardware"
// this query is used to fetch the first page then mutated later to paginate
q := api.Query()
q.Set("facility", facility)
q.Set("sort_by", "created_at")
q.Set("sort_direction", "asc")
q.Set("per_page", "1")
api.RawQuery = q.Encode()
_, total, err := fetchFacilityPage(ctx, client, api.String())
if err != nil {
return errors.Wrap(err, "failed to fetch initial page")
}
perPage := env.Int("CACHER_FETCH_PER_PAGE", 50)
if perPage > 1000 {
logger.Info("limiting per_page to 1000")
perPage = 1000
}
iterations := int(total) / perPage
if int(total)%perPage != 0 {
iterations++
}
span.SetAttributes(
attribute.String("fetchFacility.path", api.Path),
attribute.String("fetchFacility.base.query", q.Encode()),
attribute.Int("CACHER_FETCH_PER_PAGE", perPage),
attribute.Int("fetchFacility.paging.total", int(total)),
attribute.Int("fetchFacility.paging.iterations", iterations),
)
q.Set("per_page", strconv.Itoa(perPage))
tStart := time.Now()
for i := 1; i <= iterations; i++ {
q.Set("page", strconv.Itoa(i))
api.RawQuery = q.Encode()
u := api.String()
page := i
span.AddEvent("fetching page",
trace.WithAttributes(attribute.Int("page", page)),
trace.WithAttributes(attribute.String("query", api.RawQuery)),
)
pool.Submit(func() {
logger.With("page", page).Info("fetching a page")
tPageStart := time.Now()
hw, _, err := fetchFacilityPage(ctx, client, u)
if err != nil {
logger.Fatal(errors.Wrapf(err, "failed to fetch page"))
return
}
logger.With("page", page, "pages", iterations, "duration", time.Since(tPageStart)).Info("fetched a page")
data <- hw
})
}
pool.StopWait()
timer.ObserveDuration()
logger.With("duration", time.Since(tStart)).Info("fetch done")
return nil
}
func copyin(hw *hardware.Hardware, data <-chan []map[string]interface{}) error {
for hws := range data {
if err := copyInEach(hw, hws); err != nil {
return err
}
}
return nil
}
func copyInEach(hw *hardware.Hardware, data []map[string]interface{}) error {
logger.Info("copy start")
labels := prometheus.Labels{"method": "Ingest", "op": "copy"}
ingestCount.With(labels).Inc()
timer := prometheus.NewTimer(prometheus.ObserverFunc(ingestDuration.With(labels).Set))
now := time.Now()
for _, j := range data {
var q []byte
q, err := json.Marshal(j)
if err != nil {
return errors.Wrap(err, "marshal json")
}
_, err = hw.Add(string(q))
if err != nil {
logger.With("json", string(q)).Error(err)
return err
}
}
timer.ObserveDuration()
logger.With("duration", time.Since(now)).Info("copy done")
return nil
}
func (s *server) ingest(ctx context.Context, api *url.URL, facility string) error { //nolint:nolintlint,revive
if env.Bool("CACHER_NO_INGEST") {
cacherState.Set(2)
s.ingestReadyLock.Lock()
s.ingestDone = true
s.ingestReadyLock.Unlock()
return nil
}
logger.Info("ingestion is starting")
defer logger.Info("ingestion is done")
cacherState.Set(1)
labels := prometheus.Labels{"method": "Ingest", "op": ""}
cacheInFlight.With(labels).Inc()
defer cacheInFlight.With(labels).Dec()
ctx, cancel := context.WithCancel(ctx)
var wg sync.WaitGroup
wg.Add(2)
ch := make(chan []map[string]interface{}, 1)
errCh := make(chan error, 1)
tStart := time.Now()
go func() {
defer wg.Done()
if err := fetchFacility(ctx, s.packet, api, facility, ch); err != nil {
labels := prometheus.Labels{"method": "Ingest", "op": "fetch"}
ingestErrors.With(labels).Inc()
logger.Error(err)
if errors.Is(ctx.Err(), context.Canceled) {
return
}
cancel()
errCh <- err
}
}()
go func() {
defer wg.Done()
if err := copyin(s.hw, ch); err != nil {
labels := prometheus.Labels{"method": "Ingest", "op": "copy"}
ingestErrors.With(labels).Inc()
// logging is already taken care of
if errors.Is(ctx.Err(), context.Canceled) {
return
}
cancel()
errCh <- err
}
}()
wg.Wait()
logger.With("duration", time.Since(tStart)).Info("ingest done")
cacherState.Set(2)
cancel()
select {
case err := <-errCh:
return err
default:
}
s.ingestReadyLock.Lock()
s.ingestDone = true
s.ingestReadyLock.Unlock()
return nil
}