This repository has been archived by the owner on Mar 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
build.go
393 lines (335 loc) · 10.1 KB
/
build.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bsm/go-sparkey"
"github.com/colinmarc/sequencefile"
"github.com/golang/snappy"
"github.com/juju/ratelimit"
"github.com/stripe/sequins/blocks"
)
var (
errWrongPartition = errors.New("the file is cleanly partitioned, but doesn't contain a partition we want")
errCanceled = errors.New("build canceled")
)
func compressionString(c sequencefile.Compression) string {
switch c {
case sequencefile.NoCompression:
return "none"
case sequencefile.RecordCompression:
return "record"
case sequencefile.BlockCompression:
return "block"
default:
return strconv.Itoa(int(c))
}
}
func compressionCodecString(c sequencefile.CompressionCodec) string {
switch c {
case sequencefile.GzipCompression:
return "gzip"
case sequencefile.SnappyCompression:
return "snappy"
default:
return strconv.Itoa(int(c))
}
}
func (vs *version) build() {
// Welcome to the sequins museum of lock acquisition. First, we grab the lock
// for this version, and check that the previous holder didn't finish
// building.
vs.buildLock.Lock()
defer vs.buildLock.Unlock()
if vs.built {
return
}
// Then the db-wide lock, and check that a newer version didn't obsolete us.
vs.db.buildLock.Lock()
defer vs.db.buildLock.Unlock()
partitions := vs.partitions.NeededLocal()
if len(partitions) == 0 {
vs.built = true
return
}
log.Println("Loading", len(partitions), "partitions of", vs.db.name, "version", vs.name,
"from", vs.sequins.backend.DisplayPath(vs.db.name, vs.name))
// We create the directory right before we load data into it, so we don't
// leave empty directories laying around.
err := os.MkdirAll(vs.path, 0755|os.ModeDir)
if err != nil && !os.IsExist(err) {
log.Printf("Error initializing version %s of %s: %s", vs.name, vs.db.name, err)
vs.setState(versionError)
return
}
err = vs.addFiles(partitions)
if err != nil {
if err != errCanceled {
log.Printf("Error building version %s of %s: %s", vs.name, vs.db.name, err)
vs.setState(versionError)
}
vs.blockStore.Revert()
return
}
vs.partitions.UpdateLocal(partitions)
vs.built = true
}
// addFiles adds the given files to the block store, selecting only the
// given partitions.
func (vs *version) addFiles(partitions map[int]bool) error {
if len(vs.files) == 0 {
log.Println("Version", vs.name, "of", vs.db.name, "has no data. Loading it anyway.")
return nil
}
var tags []string
var remaining int32
if vs.stats != nil {
tags = []string{fmt.Sprintf("sequins_db:%s", vs.db.name)}
atomic.StoreInt32(&remaining, int32(len(vs.files)))
vs.stats.Gauge("s3.queue_depth", float64(len(vs.files)), tags, 1)
}
wg := &sync.WaitGroup{}
wg.Add(len(vs.files))
errs := make(chan error, len(vs.files))
for _, file := range vs.files {
// Ensure that `file` we reference below is the `file` we observed in this loop iteration.
file := file
f := func() {
defer wg.Done()
if vs.stats != nil {
defer func() {
vs.stats.Gauge("s3.queue_depth", float64(atomic.AddInt32(&remaining, -1)), tags, 1)
}()
}
defer func() {
if r := recover(); r != nil {
errs <- fmt.Errorf("panic in addFiles[%q] task: %v", file, r)
}
}()
select {
case <-vs.cancel:
return
default:
}
err := vs.addFile(file, partitions)
if err != nil {
errs <- fmt.Errorf("addFiles[%q]: %v", file, err)
return
}
}
vs.sequins.workQueue.Schedule(f)
}
c := make(chan interface{}, 1)
go func() {
wg.Wait()
close(c)
}()
select {
case <-vs.cancel:
return errCanceled
case err := <-errs:
return err
case <-c:
return vs.blockStore.Save(vs.partitions.SelectedLocal())
}
}
// Create a ratelimited download stream
func (vs *version) rateLimitedDownloadStream(r io.Reader) io.Reader {
if vs.sequins.downloadRateLimitBucket == nil {
return r
}
return ratelimit.Reader(r, vs.sequins.downloadRateLimitBucket)
}
// Download a sparkey file into a local file
func (vs *version) sparkeyDownload(src, dst, fileType string, transform func(io.Reader) io.Reader) error {
disp := vs.sequins.backend.DisplayPath(vs.db.name, vs.name, src)
log.Printf("downloading sparkey %s file %s\n", fileType, disp)
stream, err := vs.sequins.backend.Open(vs.db.name, vs.name, src)
if err != nil {
return fmt.Errorf("opening sparkey %s file for %s: %s", fileType, disp, err)
}
defer stream.Close()
var trStream = vs.rateLimitedDownloadStream(stream)
if transform != nil {
trStream = transform(trStream)
}
err = WriteFileAligned(dst, trStream, vs.sequins.config.WriteBufferSize)
if err != nil {
return fmt.Errorf("copying sparkey %s file %s: %s", fileType, disp, err)
}
return nil
}
// Add a Sparkey file to this version.
func (vs *version) addSparkeyFile(file string, disp string, partition int) error {
success := false
tmp, err := ioutil.TempFile(vs.path, ".sparkey")
if err != nil {
return fmt.Errorf("creating temporary sparkey file for %s: %s", disp, err)
}
logPath := sparkey.LogFileName(tmp.Name())
idxPath := sparkey.HashFileName(logPath)
defer func() {
os.Remove(tmp.Name())
if !success {
os.Remove(logPath)
os.Remove(idxPath)
}
}()
err = vs.sparkeyDownload(file, logPath, "log", nil)
if err != nil {
return err
}
idxSrc := strings.TrimSuffix(file, ".spl") + ".spi.sz"
err = vs.sparkeyDownload(idxSrc, idxPath, "index", func(r io.Reader) io.Reader {
return snappy.NewReader(r)
})
if err != nil {
return err
}
return vs.blockStore.AddSparkeyBlock(logPath, partition)
}
// Add a sequencefile to this version.
func (vs *version) addSequenceFile(file string, disp string, partitions map[int]bool) error {
log.Println("Reading records from", disp)
stream, err := vs.sequins.backend.Open(vs.db.name, vs.name, file)
if err != nil {
return fmt.Errorf("reading %s: %s", disp, err)
}
defer stream.Close()
rateLimitedStream := vs.rateLimitedDownloadStream(stream)
sf := sequencefile.NewReader(bufio.NewReader(rateLimitedStream))
err = sf.ReadHeader()
if err != nil {
return fmt.Errorf("reading header from %s: %s", disp, err)
}
log.Printf(
"sequencefile header: db=%q version=%q file=%q sequencefile_version=%d compression=%q compression_codec=%q compression_codec_class_name=%q key_class_name=%q value_class_name=%q metadata=%q",
vs.db.name, vs.name, file, sf.Header.Version, compressionString(sf.Header.Compression), compressionCodecString(sf.Header.CompressionCodec),
sf.Header.CompressionCodecClassName, sf.Header.KeyClassName, sf.Header.ValueClassName, fmt.Sprintf("%v", sf.Header.Metadata))
err = vs.addFileKeys(sf, partitions)
if err == errWrongPartition {
log.Println("Skipping", disp, "because it contains no relevant partitions")
} else if err != nil {
return fmt.Errorf("reading %s: %s", disp, err)
}
return nil
}
func (vs *version) addFile(file string, partitions map[int]bool) error {
disp := vs.sequins.backend.DisplayPath(vs.db.name, vs.name, file)
raw, partition := isSparkeyFile(file)
if raw && !partitions[partition] {
// Since we already know the partition, we can skip this right away.
log.Printf("Skipping sparkey file %s\n", disp)
return nil
}
if vs.stats != nil {
start := time.Now()
defer func() {
duration := time.Since(start)
tags := []string{fmt.Sprintf("sequins_db:%s", vs.db.name)}
vs.stats.Timing("s3.download_duration", duration, tags, 1)
}()
}
var err error
if raw {
err = vs.addSparkeyFile(file, disp, partition)
} else {
err = vs.addSequenceFile(file, disp, partitions)
}
if err != nil {
return err
}
// Intentionally hang, for tests.
hang := &vs.sequins.config.Test.Hang
if hang.Version == vs.name && hang.File == file {
time.Sleep(time.Hour)
}
return nil
}
func (vs *version) addFileKeys(reader *sequencefile.Reader, partitions map[int]bool) error {
throttle := vs.sequins.config.ThrottleLoads.Duration
canAssumePartition := true
assumedPartition := -1
assumedFor := 0
for reader.Scan() {
if throttle != 0 {
time.Sleep(throttle)
}
key, value, err := unwrapKeyValue(reader)
if err != nil {
return err
}
partition, alternatePartition := blocks.KeyPartition(key, vs.numPartitions)
// If we see the same partition (which is based on the hash) for the first
// 5000 keys, it's safe to assume that this file only contains that
// partition. This is often the case if the data has been shuffled by the
// output key in a way that aligns with our own partitioning scheme.
if canAssumePartition {
if assumedPartition == -1 {
assumedPartition = partition
} else if partition != assumedPartition {
if alternatePartition == assumedPartition {
partition = alternatePartition
} else {
canAssumePartition = false
}
} else {
assumedFor += 1
}
}
if !partitions[partition] {
// Once we see 5000 keys from the same partition, and it's a partition we
// don't want, it's safe to assume the whole file is like that, and we can
// skip the rest.
if canAssumePartition && assumedFor > 5000 {
return errWrongPartition
}
continue
}
err = vs.blockStore.Add(key, value)
if err != nil {
return err
}
}
if reader.Err() != nil {
return reader.Err()
}
return nil
}
// unwrapKeyValue correctly prepares a key and value for storage, depending on
// how they are serialized in the original file; namely, BytesWritable and Text
// keys and values are unwrapped.
func unwrapKeyValue(reader *sequencefile.Reader) (key []byte, value []byte, err error) {
// sequencefile.Text or sequencefile.BytesWritable can panic if the data is corrupted.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("sequencefile: record deserialization failed: %s", r)
}
}()
switch reader.Header.KeyClassName {
case sequencefile.BytesWritableClassName:
key = sequencefile.BytesWritable(reader.Key())
case sequencefile.TextClassName:
key = []byte(sequencefile.Text(reader.Key()))
default:
key = reader.Key()
}
switch reader.Header.ValueClassName {
case sequencefile.BytesWritableClassName:
value = sequencefile.BytesWritable(reader.Value())
case sequencefile.TextClassName:
value = []byte(sequencefile.Text(reader.Value()))
default:
value = reader.Value()
}
return
}