forked from mongodb/mongo-tools
/
restore.go
408 lines (357 loc) · 12.7 KB
/
restore.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
// Copyright (C) MongoDB, Inc. 2014-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package mongorestore
import (
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/mongodb/mongo-tools-common/bsonutil"
"github.com/mongodb/mongo-tools-common/db"
"github.com/mongodb/mongo-tools-common/intents"
"github.com/mongodb/mongo-tools-common/log"
"github.com/mongodb/mongo-tools-common/progress"
"github.com/mongodb/mongo-tools-common/util"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
const insertBufferFactor = 16
// Result encapsulates the outcome of a particular restore attempt.
type Result struct {
Successes int64
Failures int64
Err error
}
// log pretty-prints the result, associated with restoring the given namespace
func (result *Result) log(ns string) {
log.Logvf(log.Always, "finished restoring %v (%v %v, %v %v)",
ns, result.Successes, util.Pluralize(int(result.Successes), "document", "documents"),
result.Failures, util.Pluralize(int(result.Failures), "failure", "failures"))
}
// combineWith sums the successes and failures from both results and the overwrites the existing Err with the Err from
// the provided result.
func (result *Result) combineWith(other Result) {
result.Successes += other.Successes
result.Failures += other.Failures
result.Err = other.Err
}
// withErr returns a copy of the current result with the provided error
func (result Result) withErr(err error) Result {
result.Err = err
return result
}
func NewResultFromBulkResult(result *mongo.BulkWriteResult, err error) Result {
if result == nil {
return Result{}
}
nSuccess := result.InsertedCount
var nFailure int64
// if a write concern error is encountered, the failure count may be inaccurate.
if bwe, ok := err.(mongo.BulkWriteException); ok {
nFailure = int64(len(bwe.WriteErrors))
}
return Result{nSuccess, nFailure, err}
}
// RestoreIntents iterates through all of the intents stored in the IntentManager, and restores them.
func (restore *MongoRestore) RestoreIntents() Result {
log.Logvf(log.DebugLow, "restoring up to %v collections in parallel", restore.OutputOptions.NumParallelCollections)
if restore.OutputOptions.NumParallelCollections > 0 {
resultChan := make(chan Result)
// start a goroutine for each job thread
for i := 0; i < restore.OutputOptions.NumParallelCollections; i++ {
go func(id int) {
var workerResult Result
log.Logvf(log.DebugHigh, "starting restore routine with id=%v", id)
var ioBuf []byte
for {
intent := restore.manager.Pop()
if intent == nil {
log.Logvf(log.DebugHigh, "ending restore routine with id=%v, no more work to do", id)
resultChan <- workerResult // done
return
}
if fileNeedsIOBuffer, ok := intent.BSONFile.(intents.FileNeedsIOBuffer); ok {
if ioBuf == nil {
ioBuf = make([]byte, db.MaxBSONSize)
}
fileNeedsIOBuffer.TakeIOBuffer(ioBuf)
}
result := restore.RestoreIntent(intent)
result.log(intent.Namespace())
workerResult.combineWith(result)
if result.Err != nil {
resultChan <- workerResult.withErr(fmt.Errorf("%v: %v", intent.Namespace(), result.Err))
return
}
restore.manager.Finish(intent)
if fileNeedsIOBuffer, ok := intent.BSONFile.(intents.FileNeedsIOBuffer); ok {
fileNeedsIOBuffer.ReleaseIOBuffer()
}
}
}(i)
}
var totalResult Result
var totalErr error
// wait until all goroutines are done or one of them errors out
for i := 0; i < restore.OutputOptions.NumParallelCollections; i++ {
result := <-resultChan
totalResult.combineWith(result)
if totalErr == nil && totalResult.Err != nil {
totalErr = totalResult.Err
}
}
return totalResult.withErr(totalErr)
}
var totalResult Result
// single-threaded
for {
intent := restore.manager.Pop()
if intent == nil {
break
}
result := restore.RestoreIntent(intent)
result.log(intent.Namespace())
totalResult.combineWith(result)
if result.Err != nil {
return totalResult.withErr(fmt.Errorf("%v: %v", intent.Namespace(), result.Err))
}
restore.manager.Finish(intent)
}
return totalResult
}
// RestoreIntent attempts to restore a given intent into MongoDB.
func (restore *MongoRestore) RestoreIntent(intent *intents.Intent) Result {
collectionExists, err := restore.CollectionExists(intent)
if err != nil {
return Result{Err: fmt.Errorf("error reading database: %v", err)}
}
if !restore.OutputOptions.Drop && collectionExists {
log.Logvf(log.Always, "restoring to existing collection %v without dropping", intent.Namespace())
}
if restore.OutputOptions.Drop {
if collectionExists {
if strings.HasPrefix(intent.C, "system.") {
log.Logvf(log.Always, "cannot drop system collection %v, skipping", intent.Namespace())
} else {
log.Logvf(log.Info, "dropping collection %v before restoring", intent.Namespace())
err = restore.DropCollection(intent)
if err != nil {
return Result{Err: err} // no context needed
}
collectionExists = false
}
} else {
log.Logvf(log.DebugLow, "collection %v doesn't exist, skipping drop command", intent.Namespace())
}
}
var options bson.D
var indexes []IndexDocument
var uuid string
// get indexes from system.indexes dump if we have it but don't have metadata files
if intent.MetadataFile == nil {
if _, ok := restore.dbCollectionIndexes[intent.DB]; ok {
if indexes, ok = restore.dbCollectionIndexes[intent.DB][intent.C]; ok {
log.Logvf(log.Always, "no metadata; falling back to system.indexes")
}
}
}
logMessageSuffix := "with no metadata"
var hasNonSimpleCollation bool
// first create the collection with options from the metadata file
if intent.MetadataFile != nil {
logMessageSuffix = "using options from metadata"
err = intent.MetadataFile.Open()
if err != nil {
return Result{Err: err}
}
defer intent.MetadataFile.Close()
log.Logvf(log.Always, "reading metadata for %v from %v", intent.Namespace(), intent.MetadataLocation)
metadataJSON, err := ioutil.ReadAll(intent.MetadataFile)
if err != nil {
return Result{Err: fmt.Errorf("error reading metadata from %v: %v", intent.MetadataLocation, err)}
}
metadata, err := restore.MetadataFromJSON(metadataJSON)
if err != nil {
return Result{Err: fmt.Errorf("error parsing metadata from %v: %v", intent.MetadataLocation, err)}
}
if metadata != nil {
options = metadata.Options
indexes = metadata.Indexes
if restore.OutputOptions.PreserveUUID {
if metadata.UUID == "" {
return Result{Err: fmt.Errorf("--preserveUUID used but no UUID found in %v", intent.MetadataLocation)}
}
uuid = metadata.UUID
}
collation, err := bsonutil.FindSubdocumentByKey("collation", &options)
if err == nil {
localeValue, err := bsonutil.FindValueByKey("locale", &collation)
if err == nil {
hasNonSimpleCollation = localeValue != "simple"
}
}
}
// The only way to specify options on the idIndex is at collection creation time.
// This loop pulls out the idIndex from `indexes` and sets it in `options`.
for i, index := range indexes {
// The index with the name "_id_" will always be the idIndex.
if index.Options["name"].(string) == "_id_" {
// Remove the index version (to use the default) unless otherwise specified.
// If preserving UUID, we have to create a collection via
// applyops, which requires the "v" key.
if !restore.OutputOptions.KeepIndexVersion && !restore.OutputOptions.PreserveUUID {
delete(index.Options, "v")
}
index.Options["ns"] = intent.Namespace()
// If the collection has an idIndex, then we are about to create it, so
// ignore the value of autoIndexId.
for j, opt := range options {
if opt.Key == "autoIndexId" {
options = append(options[:j], options[j+1:]...)
}
}
options = append(options, bson.E{"idIndex", index})
indexes = append(indexes[:i], indexes[i+1:]...)
break
}
}
if restore.OutputOptions.NoOptionsRestore {
log.Logv(log.Info, "not restoring collection options")
logMessageSuffix = "with no collection options"
options = nil
}
}
if !collectionExists {
log.Logvf(log.Info, "creating collection %v %s", intent.Namespace(), logMessageSuffix)
log.Logvf(log.DebugHigh, "using collection options: %#v", options)
err = restore.CreateCollection(intent, options, uuid)
if err != nil {
return Result{Err: fmt.Errorf("error creating collection %v: %v", intent.Namespace(), err)}
}
} else {
log.Logvf(log.Info, "collection %v already exists - skipping collection create", intent.Namespace())
}
var result Result
if intent.BSONFile != nil {
err = intent.BSONFile.Open()
if err != nil {
return Result{Err: err}
}
defer intent.BSONFile.Close()
log.Logvf(log.Always, "restoring %v from %v", intent.Namespace(), intent.Location)
bsonSource := db.NewDecodedBSONSource(db.NewBSONSource(intent.BSONFile))
defer bsonSource.Close()
result = restore.RestoreCollectionToDB(intent.DB, intent.C, bsonSource, intent.BSONFile, intent.Size)
if result.Err != nil {
result.Err = fmt.Errorf("error restoring from %v: %v", intent.Location, result.Err)
return result
}
}
// finally, add indexes
if len(indexes) > 0 && !restore.OutputOptions.NoIndexRestore {
log.Logvf(log.Always, "restoring indexes for collection %v from metadata", intent.Namespace())
err = restore.CreateIndexes(intent, indexes, hasNonSimpleCollation)
if err != nil {
result.Err = fmt.Errorf("error creating indexes for %v: %v", intent.Namespace(), err)
return result
}
} else {
log.Logv(log.Always, "no indexes to restore")
}
return result
}
// RestoreCollectionToDB pipes the given BSON data into the database.
// Returns the number of documents restored and any errors that occurred.
func (restore *MongoRestore) RestoreCollectionToDB(dbName, colName string,
bsonSource *db.DecodedBSONSource, file PosReader, fileSize int64) Result {
var termErr error
session, err := restore.SessionProvider.GetSession()
if err != nil {
return Result{Err: fmt.Errorf("error establishing connection: %v", err)}
}
collection := session.Database(dbName).Collection(colName)
documentCount := int64(0)
watchProgressor := progress.NewCounter(fileSize)
if restore.ProgressManager != nil {
name := fmt.Sprintf("%v.%v", dbName, colName)
restore.ProgressManager.Attach(name, watchProgressor)
defer restore.ProgressManager.Detach(name)
}
maxInsertWorkers := restore.OutputOptions.NumInsertionWorkers
docChan := make(chan bson.Raw, insertBufferFactor)
resultChan := make(chan Result, maxInsertWorkers)
// stream documents for this collection on docChan
go func() {
for {
doc := bsonSource.LoadNext()
if doc == nil {
break
}
select {
case <-restore.termChan:
log.Logvf(log.Always, "terminating read on %v.%v", dbName, colName)
termErr = util.ErrTerminated
close(docChan)
return
default:
rawBytes := make([]byte, len(doc))
copy(rawBytes, doc)
docChan <- bson.Raw(rawBytes)
documentCount++
}
}
close(docChan)
}()
log.Logvf(log.DebugLow, "using %v insertion workers", maxInsertWorkers)
for i := 0; i < maxInsertWorkers; i++ {
go func() {
var result Result
bulk := db.NewUnorderedBufferedBulkInserter(collection, restore.OutputOptions.BulkBufferSize).
SetOrdered(restore.OutputOptions.MaintainInsertionOrder)
bulk.SetBypassDocumentValidation(restore.OutputOptions.BypassDocumentValidation)
for rawDoc := range docChan {
if restore.objCheck {
result.Err = bson.Unmarshal(rawDoc, &bson.D{})
if result.Err != nil {
resultChan <- result
return
}
}
result.combineWith(NewResultFromBulkResult(bulk.InsertRaw(rawDoc)))
result.Err = db.FilterError(restore.OutputOptions.StopOnError, result.Err)
if result.Err != nil {
resultChan <- result
return
}
watchProgressor.Set(file.Pos())
}
// flush the remaining docs
result.combineWith(NewResultFromBulkResult(bulk.Flush()))
resultChan <- result.withErr(db.FilterError(restore.OutputOptions.StopOnError, result.Err))
return
}()
// sleep to prevent all threads from inserting at the same time at start
time.Sleep(time.Duration(i) * 10 * time.Millisecond)
}
var totalResult Result
var finalErr error
// wait until all insert jobs finish
for done := 0; done < maxInsertWorkers; done++ {
totalResult.combineWith(<-resultChan)
if finalErr == nil && totalResult.Err != nil {
finalErr = totalResult.Err
close(restore.termChan)
}
}
if finalErr != nil {
totalResult.Err = finalErr
} else if err = bsonSource.Err(); err != nil {
totalResult.Err = fmt.Errorf("reading bson input: %v", err)
} else if termErr != nil {
totalResult.Err = termErr
}
return totalResult
}