-
Notifications
You must be signed in to change notification settings - Fork 451
/
persist.go
302 lines (272 loc) · 10.6 KB
/
persist.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
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package bootstrapper
import (
"fmt"
"sync"
"github.com/m3db/m3/src/dbnode/namespace"
"github.com/m3db/m3/src/dbnode/persist"
"github.com/m3db/m3/src/dbnode/retention"
"github.com/m3db/m3/src/dbnode/storage/bootstrap/result"
"github.com/m3db/m3/src/dbnode/storage/index/compaction"
"github.com/m3db/m3/src/m3ninx/index/segment"
"github.com/m3db/m3/src/x/mmap"
xtime "github.com/m3db/m3/src/x/time"
)
const (
mmapBootstrapIndexName = "mmap.bootstrap.index"
)
// SharedPersistManager is a lockable persist manager that's safe to be shared across threads.
type SharedPersistManager struct {
sync.Mutex
Mgr persist.Manager
}
// SharedCompactor is a lockable compactor that's safe to be shared across threads.
type SharedCompactor struct {
sync.Mutex
Compactor *compaction.Compactor
}
// PersistBootstrapIndexSegment is a helper function that persists bootstrapped index segments for a ns -> block of time.
func PersistBootstrapIndexSegment(
ns namespace.Metadata,
requestedRanges result.ShardTimeRanges,
indexResults result.IndexResults,
builder segment.DocumentsBuilder,
persistManager *SharedPersistManager,
resultOpts result.Options,
) error {
// If we're performing an index run with persistence enabled
// determine if we covered a full block exactly (which should
// occur since we always group readers by block size).
min, max := requestedRanges.MinMax()
blockSize := ns.Options().IndexOptions().BlockSize()
blockStart := min.Truncate(blockSize)
blockEnd := blockStart.Add(blockSize)
expectedRangeStart, expectedRangeEnd := blockStart, blockEnd
// Index blocks can be arbitrarily larger than data blocks, but the
// retention of the namespace is based on the size of the data blocks,
// not the index blocks. As a result, it's possible that the block start
// for the earliest index block is before the earliest possible retention
// time.
// If that is the case, then we snap the expected range start to the
// earliest retention block start because that is the point in time for
// which we'll actually have data available to construct a segment from.
//
// Example:
// Index block size: 4 hours
// Data block size: 2 hours
// Retention: 6 hours
// [12PM->2PM][2PM->4PM][4PM->6PM] (Data Blocks)
// [10AM -> 2PM][2PM -> 6PM] (Index Blocks)
retentionOpts := ns.Options().RetentionOptions()
nowFn := resultOpts.ClockOptions().NowFn()
earliestRetentionTime := retention.FlushTimeStart(retentionOpts, nowFn())
if blockStart.Before(earliestRetentionTime) {
expectedRangeStart = earliestRetentionTime
}
shards := make(map[uint32]struct{})
expectedRanges := make(result.ShardTimeRanges, len(requestedRanges))
for shard := range requestedRanges {
shards[shard] = struct{}{}
expectedRanges[shard] = xtime.Ranges{}.AddRange(xtime.Range{
Start: expectedRangeStart,
End: expectedRangeEnd,
})
}
indexBlock, ok := indexResults[xtime.ToUnixNano(blockStart)]
if !ok {
// NB(bodu): We currently write empty data files to disk, which means that we can attempt to bootstrap
// time ranges that have no data and no index block.
// For example:
// - peers data bootstrap from peer nodes receives peer blocks w/ no data (empty)
// - peers data bootstrap writes empty ts data files to disk
// - peers index bootstrap reads empty ts data files md from disk
// - attempt to bootstrap time ranges that have no index results block
return fmt.Errorf("could not find index block in results: time=%s, ts=%d",
blockStart.String(), blockStart.UnixNano())
}
if len(builder.Docs()) == 0 {
// No-op if there are no documents that ned to be written for this time block (nothing to persist).
return nil
}
var (
fulfilled = indexBlock.Fulfilled()
success = false
persistedSegments []segment.Segment
)
defer func() {
if !success {
return
}
// Combine persisted and existing segments.
segments := make([]segment.Segment, 0, len(persistedSegments))
for _, pSeg := range persistedSegments {
segments = append(segments, NewSegment(pSeg, true))
}
for _, seg := range indexBlock.Segments() {
segments = append(segments, seg)
}
// Now replace the active segment with the persisted segment.
newFulfilled := fulfilled.Copy()
newFulfilled.AddRanges(expectedRanges)
replacedBlock := result.NewIndexBlock(blockStart, segments, newFulfilled)
indexResults[xtime.ToUnixNano(blockStart)] = replacedBlock
}()
// Check that we completely fulfilled all shards for the block
// and we didn't bootstrap any more/less than expected.
requireFulfilled := expectedRanges.Copy()
requireFulfilled.Subtract(fulfilled)
exactStartEnd := max.Equal(blockStart.Add(blockSize))
if !exactStartEnd || !requireFulfilled.IsEmpty() {
return fmt.Errorf("persistent fs index bootstrap invalid ranges to persist: "+
"expected=%v, actual=%v, fulfilled=%v, exactStartEnd=%v, requireFulfilledEmpty=%v",
expectedRanges.String(), requestedRanges.String(), fulfilled.String(),
exactStartEnd, requireFulfilled.IsEmpty())
}
// NB(r): Need to get an exclusive lock to actually write the segment out
// due to needing to incrementing the index file set volume index and also
// using non-thread safe resources on the persist manager.
persistManager.Lock()
defer persistManager.Unlock()
flush, err := persistManager.Mgr.StartIndexPersist()
if err != nil {
return err
}
var calledDone bool
defer func() {
if !calledDone {
flush.DoneIndex()
}
}()
preparedPersist, err := flush.PrepareIndex(persist.IndexPrepareOptions{
NamespaceMetadata: ns,
BlockStart: indexBlock.BlockStart(),
FileSetType: persist.FileSetFlushType,
Shards: shards,
})
if err != nil {
return err
}
var calledClose bool
defer func() {
if !calledClose {
preparedPersist.Close()
}
}()
if err := preparedPersist.Persist(builder); err != nil {
return err
}
calledClose = true
persistedSegments, err = preparedPersist.Close()
if err != nil {
return err
}
calledDone = true
if err := flush.DoneIndex(); err != nil {
return err
}
// Indicate the defer above should merge newly built segments w/ existing.
success = true
return nil
}
// BuildBootstrapIndexSegment is a helper function that builds (in memory) bootstrapped index segments for a ns -> block of time.
func BuildBootstrapIndexSegment(
ns namespace.Metadata,
requestedRanges result.ShardTimeRanges,
indexResults result.IndexResults,
builder segment.DocumentsBuilder,
compactor *SharedCompactor,
resultOpts result.Options,
mmapReporter mmap.Reporter,
) error {
// If we're performing an index run with persistence enabled
// determine if we covered a full block exactly (which should
// occur since we always group readers by block size).
min, _ := requestedRanges.MinMax()
blockSize := ns.Options().IndexOptions().BlockSize()
blockStart := min.Truncate(blockSize)
blockEnd := blockStart.Add(blockSize)
expectedRangeStart, expectedRangeEnd := blockStart, blockEnd
// Index blocks can be arbitrarily larger than data blocks, but the
// retention of the namespace is based on the size of the data blocks,
// not the index blocks. As a result, it's possible that the block start
// for the earliest index block is before the earliest possible retention
// time.
// If that is the case, then we snap the expected range start to the
// earliest retention block start because that is the point in time for
// which we'll actually have data available to construct a segment from.
//
// Example:
// Index block size: 4 hours
// Data block size: 2 hours
// Retention: 6 hours
// [12PM->2PM][2PM->4PM][4PM->6PM] (Data Blocks)
// [10AM -> 2PM][2PM -> 6PM] (Index Blocks)
retentionOpts := ns.Options().RetentionOptions()
nowFn := resultOpts.ClockOptions().NowFn()
earliestRetentionTime := retention.FlushTimeStart(retentionOpts, nowFn())
if blockStart.Before(earliestRetentionTime) {
expectedRangeStart = earliestRetentionTime
}
expectedRanges := make(result.ShardTimeRanges, len(requestedRanges))
for shard := range requestedRanges {
expectedRanges[shard] = xtime.Ranges{}.AddRange(xtime.Range{
Start: expectedRangeStart,
End: expectedRangeEnd,
})
}
indexBlock, ok := indexResults[xtime.ToUnixNano(blockStart)]
if !ok {
// NB(bodu): We currently write empty data files to disk, which means that we can attempt to bootstrap
// time ranges that have no data and no index block.
// For example:
// - peers data bootstrap from peer nodes receives peer blocks w/ no data (empty)
// - peers data bootstrap writes empty ts data files to disk
// - peers index bootstrap reads empty ts data files md from disk
// - attempt to bootstrap time ranges that have no index results block
return fmt.Errorf("could not find index block in results: time=%s, ts=%d",
blockStart.String(), blockStart.UnixNano())
}
if len(builder.Docs()) == 0 {
// No-op if there are no documents that ned to be written for this time block (nothing to persist).
return nil
}
compactor.Lock()
defer compactor.Unlock()
seg, err := compactor.Compactor.CompactUsingBuilder(builder, nil, mmap.ReporterOptions{
Context: mmap.Context{
Name: mmapBootstrapIndexName,
},
Reporter: mmapReporter,
})
if err != nil {
return err
}
segments := []segment.Segment{NewSegment(seg, false)}
for _, seg := range indexBlock.Segments() {
segments = append(segments, seg)
}
// Now replace the active segment with the built segment.
newFulfilled := indexBlock.Fulfilled().Copy()
newFulfilled.AddRanges(expectedRanges)
replacedBlock := result.NewIndexBlock(blockStart, segments, newFulfilled)
indexResults[xtime.ToUnixNano(blockStart)] = replacedBlock
return nil
}