This repository has been archived by the owner on Aug 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 266
/
store.go
480 lines (402 loc) · 11.6 KB
/
store.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Copyright 2016 Attic Labs, Inc. All rights reserved.
// Licensed under the Apache License, version 2.0:
// http://www.apache.org/licenses/LICENSE-2.0
package nbs
import (
"fmt"
"sort"
"sync"
"time"
"github.com/attic-labs/noms/go/chunks"
"github.com/attic-labs/noms/go/constants"
"github.com/attic-labs/noms/go/d"
"github.com/attic-labs/noms/go/hash"
humanize "github.com/dustin/go-humanize"
)
// The root of a Noms Chunk Store is stored in a 'manifest', along with the
// names of the tables that hold all the chunks in the store. The number of
// chunks in each table is also stored in the manifest.
const (
// StorageVersion is the version of the on-disk Noms Chunks Store data format.
StorageVersion = "4"
defaultMemTableSize uint64 = (1 << 20) * 128 // 128MB
defaultMaxTables = 192
defaultIndexCacheSize = (1 << 20) * 8 // 8MB
defaultManifestCacheSize = 1 << 23 // 8MB
preflushChunkCount = 8
)
var (
cacheOnce = sync.Once{}
globalIndexCache *indexCache
makeManifestManager func(manifest) manifestManager
globalFDCache *fdCache
)
func makeGlobalCaches() {
globalIndexCache = newIndexCache(defaultIndexCacheSize)
globalFDCache = newFDCache(defaultMaxTables)
manifestCache := newManifestCache(defaultManifestCacheSize)
manifestLocks := newManifestLocks()
makeManifestManager = func(m manifest) manifestManager { return manifestManager{m, manifestCache, manifestLocks} }
}
type NomsBlockStore struct {
mm manifestManager
p tablePersister
c conjoiner
mu sync.RWMutex // protects the following state
mt *memTable
tables tableSet
upstream manifestContents
mtSize uint64
putCount uint64
stats *Stats
}
func NewAWSStore(table, ns, bucket string, s3 s3svc, ddb ddbsvc, memTableSize uint64) *NomsBlockStore {
cacheOnce.Do(makeGlobalCaches)
readRateLimiter := make(chan struct{}, 32)
p := &awsTablePersister{
s3,
bucket,
readRateLimiter,
nil,
&ddbTableStore{ddb, table, readRateLimiter, nil},
awsLimits{defaultS3PartSize, minS3PartSize, maxS3PartSize, maxDynamoItemSize, maxDynamoChunks},
globalIndexCache,
}
mm := makeManifestManager(newDynamoManifest(table, ns, ddb))
return newNomsBlockStore(mm, p, inlineConjoiner{defaultMaxTables}, memTableSize)
}
func NewLocalStore(dir string, memTableSize uint64) *NomsBlockStore {
cacheOnce.Do(makeGlobalCaches)
d.PanicIfError(checkDir(dir))
mm := makeManifestManager(fileManifest{dir})
p := newFSTablePersister(dir, globalFDCache, globalIndexCache)
return newNomsBlockStore(mm, p, inlineConjoiner{defaultMaxTables}, memTableSize)
}
func newNomsBlockStore(mm manifestManager, p tablePersister, c conjoiner, memTableSize uint64) *NomsBlockStore {
if memTableSize == 0 {
memTableSize = defaultMemTableSize
}
nbs := &NomsBlockStore{
mm: mm,
p: p,
c: c,
tables: newTableSet(p),
upstream: manifestContents{vers: constants.NomsVersion},
mtSize: memTableSize,
stats: NewStats(),
}
t1 := time.Now()
defer nbs.stats.OpenLatency.SampleTimeSince(t1)
if exists, contents := nbs.mm.Fetch(nbs.stats); exists {
nbs.upstream = contents
nbs.tables = nbs.tables.Rebase(contents.specs, nbs.stats)
}
return nbs
}
func newNomsBlockStoreWithContents(mm manifestManager, mc manifestContents, p tablePersister, c conjoiner, memTableSize uint64) *NomsBlockStore {
if memTableSize == 0 {
memTableSize = defaultMemTableSize
}
stats := NewStats()
return &NomsBlockStore{
mm: mm,
p: p,
c: c,
mtSize: memTableSize,
stats: stats,
upstream: mc,
tables: newTableSet(p).Rebase(mc.specs, stats),
}
}
func (nbs *NomsBlockStore) Put(c chunks.Chunk) {
t1 := time.Now()
a := addr(c.Hash())
d.PanicIfFalse(nbs.addChunk(a, c.Data()))
nbs.putCount++
nbs.stats.PutLatency.SampleTimeSince(t1)
}
// TODO: figure out if there's a non-error reason for this to return false. If not, get rid of return value.
func (nbs *NomsBlockStore) addChunk(h addr, data []byte) bool {
nbs.mu.Lock()
defer nbs.mu.Unlock()
if nbs.mt == nil {
nbs.mt = newMemTable(nbs.mtSize)
}
if !nbs.mt.addChunk(h, data) {
nbs.tables = nbs.tables.Prepend(nbs.mt, nbs.stats)
nbs.mt = newMemTable(nbs.mtSize)
return nbs.mt.addChunk(h, data)
}
return true
}
func (nbs *NomsBlockStore) Get(h hash.Hash) chunks.Chunk {
t1 := time.Now()
defer func() {
nbs.stats.GetLatency.SampleTimeSince(t1)
nbs.stats.ChunksPerGet.Sample(1)
}()
a := addr(h)
data, tables := func() (data []byte, tables chunkReader) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
if nbs.mt != nil {
data = nbs.mt.get(a, nbs.stats)
}
return data, nbs.tables
}()
if data != nil {
return chunks.NewChunkWithHash(h, data)
}
if data := tables.get(a, nbs.stats); data != nil {
return chunks.NewChunkWithHash(h, data)
}
return chunks.EmptyChunk
}
func (nbs *NomsBlockStore) GetMany(hashes hash.HashSet, foundChunks chan *chunks.Chunk) {
t1 := time.Now()
reqs := toGetRecords(hashes)
defer func() {
if len(hashes) > 0 {
nbs.stats.GetLatency.SampleTimeSince(t1)
nbs.stats.ChunksPerGet.Sample(uint64(len(reqs)))
}
}()
wg := &sync.WaitGroup{}
tables, remaining := func() (tables chunkReader, remaining bool) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
tables = nbs.tables
remaining = true
if nbs.mt != nil {
remaining = nbs.mt.getMany(reqs, foundChunks, nil, nbs.stats)
}
return
}()
if remaining {
tables.getMany(reqs, foundChunks, wg, nbs.stats)
wg.Wait()
}
}
func toGetRecords(hashes hash.HashSet) []getRecord {
reqs := make([]getRecord, len(hashes))
idx := 0
for h := range hashes {
a := addr(h)
reqs[idx] = getRecord{
a: &a,
prefix: a.Prefix(),
}
idx++
}
sort.Sort(getRecordByPrefix(reqs))
return reqs
}
func (nbs *NomsBlockStore) CalcReads(hashes hash.HashSet, blockSize uint64) (reads int, split bool) {
reqs := toGetRecords(hashes)
tables := func() (tables tableSet) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
tables = nbs.tables
return
}()
reads, split, remaining := tables.calcReads(reqs, blockSize)
d.Chk.False(remaining)
return
}
func (nbs *NomsBlockStore) extractChunks(chunkChan chan<- *chunks.Chunk) {
ch := make(chan extractRecord, 1)
go func() {
defer close(ch)
nbs.mu.RLock()
defer nbs.mu.RUnlock()
// Chunks in nbs.tables were inserted before those in nbs.mt, so extract chunks there _first_
nbs.tables.extract(ch)
if nbs.mt != nil {
nbs.mt.extract(ch)
}
}()
for rec := range ch {
c := chunks.NewChunkWithHash(hash.Hash(rec.a), rec.data)
chunkChan <- &c
}
}
func (nbs *NomsBlockStore) Count() uint32 {
count, tables := func() (count uint32, tables chunkReader) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
if nbs.mt != nil {
count = nbs.mt.count()
}
return count, nbs.tables
}()
return count + tables.count()
}
func (nbs *NomsBlockStore) Has(h hash.Hash) bool {
t1 := time.Now()
defer func() {
nbs.stats.HasLatency.SampleTimeSince(t1)
nbs.stats.AddressesPerHas.Sample(1)
}()
a := addr(h)
has, tables := func() (bool, chunkReader) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
return nbs.mt != nil && nbs.mt.has(a), nbs.tables
}()
has = has || tables.has(a)
return has
}
func (nbs *NomsBlockStore) HasMany(hashes hash.HashSet) hash.HashSet {
t1 := time.Now()
reqs := toHasRecords(hashes)
tables, remaining := func() (tables chunkReader, remaining bool) {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
tables = nbs.tables
remaining = true
if nbs.mt != nil {
remaining = nbs.mt.hasMany(reqs)
}
return
}()
if remaining {
tables.hasMany(reqs)
}
if len(hashes) > 0 {
nbs.stats.HasLatency.SampleTimeSince(t1)
nbs.stats.AddressesPerHas.SampleLen(len(reqs))
}
absent := hash.HashSet{}
for _, r := range reqs {
if !r.has {
absent.Insert(hash.New(r.a[:]))
}
}
return absent
}
func toHasRecords(hashes hash.HashSet) []hasRecord {
reqs := make([]hasRecord, len(hashes))
idx := 0
for h := range hashes {
a := addr(h)
reqs[idx] = hasRecord{
a: &a,
prefix: a.Prefix(),
order: idx,
}
idx++
}
sort.Sort(hasRecordByPrefix(reqs))
return reqs
}
func (nbs *NomsBlockStore) Rebase() {
nbs.mu.Lock()
defer nbs.mu.Unlock()
if exists, contents := nbs.mm.Fetch(nbs.stats); exists {
nbs.upstream = contents
nbs.tables = nbs.tables.Rebase(contents.specs, nbs.stats)
}
}
func (nbs *NomsBlockStore) Root() hash.Hash {
nbs.mu.RLock()
defer nbs.mu.RUnlock()
return nbs.upstream.root
}
func (nbs *NomsBlockStore) Commit(current, last hash.Hash) bool {
t1 := time.Now()
defer nbs.stats.CommitLatency.SampleTimeSince(t1)
anyPossiblyNovelChunks := func() bool {
nbs.mu.Lock()
defer nbs.mu.Unlock()
return nbs.mt != nil || nbs.tables.Novel() > 0
}
if !anyPossiblyNovelChunks() && current == last {
nbs.Rebase()
return true
}
func() {
// This is unfortunate. We want to serialize commits to the same store
// so that we avoid writing a bunch of unreachable small tables which result
// from optismistic lock failures. However, this means that the time to
// write tables is included in "commit" time and if all commits are
// serialized, it means alot more waiting. Allow "non-trivial" tables to be
// persisted outside of the commit-lock.
nbs.mu.Lock()
defer nbs.mu.Unlock()
if nbs.mt != nil && nbs.mt.count() > preflushChunkCount {
nbs.tables = nbs.tables.Prepend(nbs.mt, nbs.stats)
nbs.mt = nil
}
}()
nbs.mm.LockForUpdate()
defer nbs.mm.UnlockForUpdate()
for {
if err := nbs.updateManifest(current, last); err == nil {
return true
} else if err == errOptimisticLockFailedRoot || err == errLastRootMismatch {
return false
}
}
}
var (
errLastRootMismatch = fmt.Errorf("last does not match nbs.Root()")
errOptimisticLockFailedRoot = fmt.Errorf("Root moved")
errOptimisticLockFailedTables = fmt.Errorf("Tables changed")
)
func (nbs *NomsBlockStore) updateManifest(current, last hash.Hash) error {
nbs.mu.Lock()
defer nbs.mu.Unlock()
if nbs.upstream.root != last {
return errLastRootMismatch
}
handleOptimisticLockFailure := func(upstream manifestContents) error {
nbs.upstream = upstream
nbs.tables = nbs.tables.Rebase(upstream.specs, nbs.stats)
if last != upstream.root {
return errOptimisticLockFailedRoot
}
return errOptimisticLockFailedTables
}
if cached, doomed := nbs.mm.updateWillFail(nbs.upstream.lock); doomed {
// Pre-emptive optimistic lock failure. Someone else in-process moved to the root, the set of tables, or both out from under us.
return handleOptimisticLockFailure(cached)
}
if nbs.mt != nil && nbs.mt.count() > 0 {
nbs.tables = nbs.tables.Prepend(nbs.mt, nbs.stats)
nbs.mt = nil
}
if nbs.c.ConjoinRequired(nbs.tables) {
nbs.upstream = nbs.c.Conjoin(nbs.upstream, nbs.mm, nbs.p, nbs.stats)
nbs.tables = nbs.tables.Rebase(nbs.upstream.specs, nbs.stats)
return errOptimisticLockFailedTables
}
specs := nbs.tables.ToSpecs()
newContents := manifestContents{
vers: constants.NomsVersion,
root: current,
lock: generateLockHash(current, specs),
specs: specs,
}
upstream := nbs.mm.Update(nbs.upstream.lock, newContents, nbs.stats, nil)
if newContents.lock != upstream.lock {
// Optimistic lock failure. Someone else moved to the root, the set of tables, or both out from under us.
return handleOptimisticLockFailure(upstream)
}
nbs.upstream = newContents
nbs.tables = nbs.tables.Flatten()
return nil
}
func (nbs *NomsBlockStore) Version() string {
return nbs.upstream.vers
}
func (nbs *NomsBlockStore) Close() (err error) {
return
}
func (nbs *NomsBlockStore) Stats() interface{} {
return *nbs.stats
}
func (nbs *NomsBlockStore) StatsSummary() string {
nbs.mu.Lock()
defer nbs.mu.Unlock()
return fmt.Sprintf("Root: %s; Chunk Count %d; Physical Bytes %s", nbs.upstream.root, nbs.tables.count(), humanize.Bytes(nbs.tables.physicalLen()))
}