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
|
// mmap_v1_engine.cpp
/**
* Copyright (C) 2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#include "mongo/db/storage/mmap_v1/mmap_v1_engine.h"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <fstream>
#include "mongo/db/mongod_options.h"
#include "mongo/db/storage/mmap_v1/data_file_sync.h"
#include "mongo/db/storage/mmap_v1/dur.h"
#include "mongo/db/storage/mmap_v1/dur_journal.h"
#include "mongo/db/storage/mmap_v1/dur_recover.h"
#include "mongo/db/storage/mmap_v1/dur_recovery_unit.h"
#include "mongo/db/storage/mmap_v1/mmap_v1_database_catalog_entry.h"
#include "mongo/db/storage/mmap_v1/mmap_v1_options.h"
#include "mongo/db/storage/storage_engine_lock_file.h"
#include "mongo/db/storage_options.h"
#include "mongo/util/file_allocator.h"
#include "mongo/util/log.h"
#include "mongo/util/mmap.h"
namespace mongo {
using std::endl;
using std::ifstream;
using std::string;
using std::stringstream;
using std::vector;
namespace {
#if !defined(__sunos__)
// if doingRepair is true don't consider unclean shutdown an error
void acquirePathLock(MMAPV1Engine* storageEngine,
bool doingRepair,
const StorageEngineLockFile& lockFile) {
string name = lockFile.getFilespec();
bool oldFile = lockFile.createdByUncleanShutdown();
if ( oldFile ) {
// we check this here because we want to see if we can get the lock
// if we can't, then its probably just another mongod running
string errmsg;
if (doingRepair && dur::haveJournalFiles()) {
errmsg = "************** \n"
"You specified --repair but there are dirty journal files. Please\n"
"restart without --repair to allow the journal files to be replayed.\n"
"If you wish to repair all databases, please shutdown cleanly and\n"
"run with --repair again.\n"
"**************";
}
else if (storageGlobalParams.dur) {
if (!dur::haveJournalFiles(/*anyFiles=*/true)) {
// Passing anyFiles=true as we are trying to protect against starting in an
// unclean state with the journal directory unmounted. If there are any files,
// even prealloc files, then it means that it is mounted so we can continue.
// Previously there was an issue (SERVER-5056) where we would fail to start up
// if killed during prealloc.
vector<string> dbnames;
storageEngine->listDatabases( &dbnames );
if ( dbnames.size() == 0 ) {
// this means that mongod crashed
// between initial startup and when journaling was initialized
// it is safe to continue
}
else {
errmsg = str::stream()
<< "************** \n"
<< "old lock file: " << name << ". probably means unclean shutdown,\n"
<< "but there are no journal files to recover.\n"
<< "this is likely human error or filesystem corruption.\n"
<< "please make sure that your journal directory is mounted.\n"
<< "found " << dbnames.size() << " dbs.\n"
<< "see: http://dochub.mongodb.org/core/repair for more information\n"
<< "*************";
}
}
}
else {
if (!dur::haveJournalFiles() && !doingRepair) {
errmsg = str::stream()
<< "************** \n"
<< "Unclean shutdown detected.\n"
<< "Please visit http://dochub.mongodb.org/core/repair for recovery instructions.\n"
<< "*************";
}
}
if (!errmsg.empty()) {
log() << errmsg << endl;
uassert( 12596 , "old lock file" , 0 );
}
}
// Not related to lock file, but this is where we handle unclean shutdown
if (!storageGlobalParams.dur && dur::haveJournalFiles()) {
log() << "**************" << endl;
log() << "Error: journal files are present in journal directory, yet starting without journaling enabled." << endl;
log() << "It is recommended that you start with journaling enabled so that recovery may occur." << endl;
log() << "**************" << endl;
uasserted(13597, "can't start without --journal enabled when journal/ files are present");
}
}
#else
void acquirePathLock(MMAPV1Engine* storageEngine,
bool doingRepair,
const StorageEngineLockFile& lockFile) {
// TODO - this is very bad that the code above not running here.
// Not related to lock file, but this is where we handle unclean shutdown
if (!storageGlobalParams.dur && dur::haveJournalFiles()) {
log() << "**************" << endl;
log() << "Error: journal files are present in journal directory, yet starting without --journal enabled." << endl;
log() << "It is recommended that you start with journaling enabled so that recovery may occur." << endl;
log() << "Alternatively (not recommended), you can backup everything, then delete the journal files, and run --repair" << endl;
log() << "**************" << endl;
uasserted(13618, "can't start without --journal enabled when journal/ files are present");
}
}
#endif // !defined(__sunos__)
/// warn if readahead > 256KB (gridfs chunk size)
void checkReadAhead(const string& dir) {
#ifdef __linux__
try {
const dev_t dev = getPartition(dir);
// This path handles the case where the filesystem uses the whole device (including LVM)
string path = str::stream() <<
"/sys/dev/block/" << major(dev) << ':' << minor(dev) << "/queue/read_ahead_kb";
if (!boost::filesystem::exists(path)){
// This path handles the case where the filesystem is on a partition.
path = str::stream()
<< "/sys/dev/block/" << major(dev) << ':' << minor(dev) // this is a symlink
<< "/.." // parent directory of a partition is for the whole device
<< "/queue/read_ahead_kb";
}
if (boost::filesystem::exists(path)) {
ifstream file (path.c_str());
if (file.is_open()) {
int kb;
file >> kb;
if (kb > 256) {
log() << startupWarningsLog;
log() << "** WARNING: Readahead for " << dir << " is set to " << kb << "KB"
<< startupWarningsLog;
log() << "** We suggest setting it to 256KB (512 sectors) or less"
<< startupWarningsLog;
log() << "** http://dochub.mongodb.org/core/readahead"
<< startupWarningsLog;
}
}
}
}
catch (const std::exception& e) {
log() << "unable to validate readahead settings due to error: " << e.what()
<< startupWarningsLog;
log() << "for more information, see http://dochub.mongodb.org/core/readahead"
<< startupWarningsLog;
}
#endif // __linux__
}
// This is unrelated to the _tmp directory in dbpath.
void clearTmpFiles() {
boost::filesystem::path path(storageGlobalParams.dbpath);
for ( boost::filesystem::directory_iterator i( path );
i != boost::filesystem::directory_iterator(); ++i ) {
string fileName = boost::filesystem::path(*i).leaf().string();
if ( boost::filesystem::is_directory( *i ) &&
fileName.length() && fileName[ 0 ] == '$' )
boost::filesystem::remove_all( *i );
}
}
} // namespace
MMAPV1Engine::MMAPV1Engine(const StorageEngineLockFile& lockFile) {
// TODO check non-journal subdirs if using directory-per-db
checkReadAhead(storageGlobalParams.dbpath);
acquirePathLock(this, storageGlobalParams.repair, lockFile);
FileAllocator::get()->start();
MONGO_ASSERT_ON_EXCEPTION_WITH_MSG( clearTmpFiles(), "clear tmp files" );
}
void MMAPV1Engine::finishInit() {
dataFileSync.go();
// Replays the journal (if needed) and starts the background thread. This requires the
// ability to create OperationContexts.
dur::startup();
}
MMAPV1Engine::~MMAPV1Engine() {
for ( EntryMap::const_iterator it = _entryMap.begin(); it != _entryMap.end(); ++it ) {
delete it->second;
}
_entryMap.clear();
}
RecoveryUnit* MMAPV1Engine::newRecoveryUnit() {
return new DurRecoveryUnit();
}
void MMAPV1Engine::listDatabases( std::vector<std::string>* out ) const {
_listDatabases( storageGlobalParams.dbpath, out );
}
DatabaseCatalogEntry* MMAPV1Engine::getDatabaseCatalogEntry( OperationContext* opCtx,
const StringData& db ) {
{
boost::mutex::scoped_lock lk(_entryMapMutex);
EntryMap::const_iterator iter = _entryMap.find(db.toString());
if (iter != _entryMap.end()) {
return iter->second;
}
}
// This is an on-demand database create/open. At this point, we are locked under X lock for
// the database (MMAPV1DatabaseCatalogEntry's constructor checks that) so no two threads
// can be creating the same database concurrenty. We need to create the database outside of
// the _entryMapMutex so we do not deadlock (see SERVER-15880).
MMAPV1DatabaseCatalogEntry* entry =
new MMAPV1DatabaseCatalogEntry(opCtx,
db,
storageGlobalParams.dbpath,
storageGlobalParams.directoryperdb,
false);
boost::mutex::scoped_lock lk(_entryMapMutex);
// Sanity check that we are not overwriting something
invariant(_entryMap.insert(EntryMap::value_type(db.toString(), entry)).second);
return entry;
}
Status MMAPV1Engine::closeDatabase( OperationContext* txn, const StringData& db ) {
// Before the files are closed, flush any potentially outstanding changes, which might
// reference this database. Otherwise we will assert when subsequent applications of the
// global journal entries occur, which happen to have write intents for the removed files.
getDur().syncDataAndTruncateJournal(txn);
boost::mutex::scoped_lock lk( _entryMapMutex );
MMAPV1DatabaseCatalogEntry* entry = _entryMap[db.toString()];
delete entry;
_entryMap.erase( db.toString() );
return Status::OK();
}
Status MMAPV1Engine::dropDatabase( OperationContext* txn, const StringData& db ) {
Status status = closeDatabase( txn, db );
if ( !status.isOK() )
return status;
_deleteDataFiles( db.toString() );
return Status::OK();
}
void MMAPV1Engine::_listDatabases( const std::string& directory,
std::vector<std::string>* out ) {
boost::filesystem::path path( directory );
for ( boost::filesystem::directory_iterator i( path );
i != boost::filesystem::directory_iterator();
++i ) {
if (storageGlobalParams.directoryperdb) {
boost::filesystem::path p = *i;
string dbName = p.leaf().string();
p /= ( dbName + ".ns" );
if ( exists( p ) )
out->push_back( dbName );
}
else {
string fileName = boost::filesystem::path(*i).leaf().string();
if ( fileName.length() > 3 && fileName.substr( fileName.length() - 3, 3 ) == ".ns" )
out->push_back( fileName.substr( 0, fileName.length() - 3 ) );
}
}
}
int MMAPV1Engine::flushAllFiles( bool sync ) {
return MongoFile::flushAll( sync );
}
bool MMAPV1Engine::isDurable() const {
return getDur().isDurable();
}
RecordAccessTracker& MMAPV1Engine::getRecordAccessTracker() {
return _recordAccessTracker;
}
void MMAPV1Engine::cleanShutdown() {
// wait until file preallocation finishes
// we would only hang here if the file_allocator code generates a
// synchronous signal, which we don't expect
log() << "shutdown: waiting for fs preallocator..." << endl;
FileAllocator::get()->waitUntilFinished();
if (storageGlobalParams.dur) {
log() << "shutdown: final commit..." << endl;
getDur().commitAndStopDurThread();
flushAllFiles(true);
}
log() << "shutdown: closing all files..." << endl;
stringstream ss3;
MemoryMappedFile::closeAllFiles( ss3 );
log() << ss3.str() << endl;
if (storageGlobalParams.dur) {
dur::journalCleanup(true);
}
}
}
|