summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/mobile/mobile_kv_engine.cpp
blob: 34b40d96c71c17359eb358f4a0b40eefefddf776 (plain)
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
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    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 Server Side 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/platform/basic.h"

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/system/error_code.hpp>
#include <memory>
#include <vector>

#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/storage/mobile/mobile_index.h"
#include "mongo/db/storage/mobile/mobile_kv_engine.h"
#include "mongo/db/storage/mobile/mobile_record_store.h"
#include "mongo/db/storage/mobile/mobile_recovery_unit.h"
#include "mongo/db/storage/mobile/mobile_session.h"
#include "mongo/db/storage/mobile/mobile_sqlite_statement.h"
#include "mongo/db/storage/mobile/mobile_util.h"
#include "mongo/stdx/memory.h"
#include "mongo/util/log.h"
#include "mongo/util/scopeguard.h"

namespace mongo {

class MobileSession;
class SqliteStatement;

MobileKVEngine::MobileKVEngine(const std::string& path) {
    _initDBPath(path);

    // Initialize the database to be in WAL mode.
    sqlite3* initSession;
    int status = sqlite3_open(_path.c_str(), &initSession);
    checkStatus(status, SQLITE_OK, "sqlite3_open");

    // Guarantees that sqlite3_close() will be called when the function returns.
    ON_BLOCK_EXIT([&initSession] { sqlite3_close(initSession); });

    // Ensure SQLite is operating in the WAL mode.
    {
        sqlite3_stmt* stmt;
        status = sqlite3_prepare_v2(initSession, "PRAGMA journal_mode=WAL;", -1, &stmt, NULL);
        checkStatus(status, SQLITE_OK, "sqlite3_prepare_v2");

        status = sqlite3_step(stmt);
        checkStatus(status, SQLITE_ROW, "sqlite3_step");

        // Pragma returns current mode in SQLite, ensure it is "wal" mode.
        const void* colText = sqlite3_column_text(stmt, 0);
        const char* mode = reinterpret_cast<const char*>(colText);
        fassert(37001, !strcmp(mode, "wal"));
        status = sqlite3_finalize(stmt);
        checkStatus(status, SQLITE_OK, "sqlite3_finalize");

        LOG(MOBILE_LOG_LEVEL_LOW) << "MobileSE: Confirmed SQLite database opened in WAL mode";
    }

    // Ensure SQLite is operating with "synchronous" flag set to FULL.
    {
#define PRAGMA_SYNC_FULL 2

        sqlite3_stmt* stmt;
        status = sqlite3_prepare_v2(initSession, "PRAGMA main.synchronous;", -1, &stmt, NULL);
        checkStatus(status, SQLITE_OK, "sqlite3_prepare_v2");

        status = sqlite3_step(stmt);
        checkStatus(status, SQLITE_ROW, "sqlite3_step");

        // Pragma returns current "synchronous" setting, ensure it is FULL.
        int sync_val = sqlite3_column_int(stmt, 0);
        fassert(50869, sync_val == PRAGMA_SYNC_FULL);
        status = sqlite3_finalize(stmt);
        checkStatus(status, SQLITE_OK, "sqlite3_finalize");

        LOG(MOBILE_LOG_LEVEL_LOW) << "MobileSE: Confirmed SQLite database has synchronous "
                                  << "set to FULL";
    }

    // Set and ensure SQLite is operating with F_FULLFSYNC if the platform permits.
    {
        // Set to use F_FULLFSYNC
        char* errMsg = NULL;
        status = sqlite3_exec(initSession, "PRAGMA fullfsync = 1;", NULL, NULL, &errMsg);
        checkStatus(status, SQLITE_OK, "sqlite3_exec", errMsg);
        // When the error message is not NULL, it is allocated through sqlite3_malloc and must be
        // freed before exiting the method. If the error message is NULL, sqlite3_free is a no-op.
        sqlite3_free(errMsg);

        // Confirm that the setting holds
        sqlite3_stmt* stmt;
        status = sqlite3_prepare_v2(initSession, "PRAGMA fullfsync;", -1, &stmt, NULL);
        checkStatus(status, SQLITE_OK, "sqlite3_prepare_v2");

        status = sqlite3_step(stmt);
        checkStatus(status, SQLITE_ROW, "sqlite3_step");

        // Pragma returns current fullsync setting, ensure it is enabled.
        int fullfsync_val = sqlite3_column_int(stmt, 0);
        fassert(50868, fullfsync_val == 1);
        status = sqlite3_finalize(stmt);
        checkStatus(status, SQLITE_OK, "sqlite3_finalize");

        LOG(MOBILE_LOG_LEVEL_LOW) << "MobileSE: Confirmed SQLite database is set to fsync "
                                  << "with F_FULLFSYNC if the platform supports"
                                  << ". Val: " << fullfsync_val;
    }

    _sessionPool.reset(new MobileSessionPool(_path));
}

void MobileKVEngine::_initDBPath(const std::string& path) {
    boost::system::error_code err;
    boost::filesystem::path dbPath(path);

    if (!boost::filesystem::exists(dbPath, err)) {
        if (err) {
            uasserted(4085, err.message());
        }
        std::string errMsg("DB path not found: ");
        errMsg += dbPath.generic_string();
        uasserted(4086, errMsg);

    } else if (!boost::filesystem::is_directory(dbPath, err)) {
        if (err) {
            uasserted(4087, err.message());
        }
        std::string errMsg("DB path is not a valid directory: ");
        errMsg += dbPath.generic_string();
        uasserted(4088, errMsg);
    }

    dbPath /= "mobile.sqlite";

    if (boost::filesystem::exists(dbPath, err)) {
        if (err) {
            uasserted(4089, err.message());
        } else if (!boost::filesystem::is_regular_file(dbPath)) {
            std::string errMsg("Failed to open " + dbPath.generic_string() +
                               ": not a regular file");
            uasserted(4090, errMsg);
        }
    }
    _path = dbPath.generic_string();
}

RecoveryUnit* MobileKVEngine::newRecoveryUnit() {
    return new MobileRecoveryUnit(_sessionPool.get());
}

Status MobileKVEngine::createRecordStore(OperationContext* opCtx,
                                         StringData ns,
                                         StringData ident,
                                         const CollectionOptions& options) {
    // TODO: eventually will support file renaming but otherwise do not use collection options.

    // Mobile SE doesn't support creating an oplog
    if (NamespaceString::oplog(ns)) {
        return Status(ErrorCodes::InvalidOptions,
                      "Replication is not supported by the mobile storage engine");
    }

    // Mobile doesn't support capped collections
    if (options.capped) {
        return Status(ErrorCodes::InvalidOptions,
                      "Capped collections are not supported by the mobile storage engine");
    }

    MobileRecordStore::create(opCtx, ident.toString());
    return Status::OK();
}

std::unique_ptr<RecordStore> MobileKVEngine::getRecordStore(OperationContext* opCtx,
                                                            StringData ns,
                                                            StringData ident,
                                                            const CollectionOptions& options) {
    return stdx::make_unique<MobileRecordStore>(opCtx, ns, _path, ident.toString(), options);
}

std::unique_ptr<RecordStore> MobileKVEngine::makeTemporaryRecordStore(OperationContext* opCtx,
                                                                      StringData ident) {
    MobileRecordStore::create(opCtx, ident.toString());
    return std::make_unique<MobileRecordStore>(
        opCtx, "", _path, ident.toString(), CollectionOptions());
}


Status MobileKVEngine::createSortedDataInterface(OperationContext* opCtx,
                                                 StringData ident,
                                                 const IndexDescriptor* desc) {
    return MobileIndex::create(opCtx, ident.toString());
}

SortedDataInterface* MobileKVEngine::getSortedDataInterface(OperationContext* opCtx,
                                                            StringData ident,
                                                            const IndexDescriptor* desc) {
    if (desc->unique()) {
        return new MobileIndexUnique(opCtx, desc, ident.toString());
    }
    return new MobileIndexStandard(opCtx, desc, ident.toString());
}

Status MobileKVEngine::dropIdent(OperationContext* opCtx, StringData ident) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSessionNoTxn(opCtx);
    std::string dropQuery = "DROP TABLE IF EXISTS \"" + ident + "\";";

    try {
        SqliteStatement::execQuery(session, dropQuery.c_str());
    } catch (const WriteConflictException&) {
        // It is possible that this drop fails because of transaction running in parallel.
        // We pretend that it succeeded, queue it for now and keep retrying later.
        LOG(MOBILE_LOG_LEVEL_LOW)
            << "MobileSE: Caught WriteConflictException while dropping table, "
               "queuing to retry later";
        MobileRecoveryUnit::get(opCtx)->enqueueFailedDrop(dropQuery);
    }
    return Status::OK();
}

/**
 * Note: this counts the total number of bytes in the key and value columns, not the actual number
 * of bytes on disk used by this ident.
 */
int64_t MobileKVEngine::getIdentSize(OperationContext* opCtx, StringData ident) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    // Get key-value column names.
    std::string colNameQuery = "PRAGMA table_info(\"" + ident + "\")";
    SqliteStatement colNameStmt(*session, colNameQuery);

    colNameStmt.step(SQLITE_ROW);
    std::string keyColName(static_cast<const char*>(colNameStmt.getColText(1)));
    colNameStmt.step(SQLITE_ROW);
    std::string valueColName(static_cast<const char*>(colNameStmt.getColText(1)));
    colNameStmt.step(SQLITE_DONE);

    // Get total data size of key-value columns.
    str::stream dataSizeQuery;
    dataSizeQuery << "SELECT IFNULL(SUM(LENGTH(" << keyColName << ")), 0) + "
                  << "IFNULL(SUM(LENGTH(" << valueColName << ")), 0) FROM \"" << ident + "\";";
    SqliteStatement dataSizeStmt(*session, dataSizeQuery);

    dataSizeStmt.step(SQLITE_ROW);
    return dataSizeStmt.getColInt(0);
}

bool MobileKVEngine::hasIdent(OperationContext* opCtx, StringData ident) const {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    std::string findTableQuery = "SELECT * FROM sqlite_master WHERE type='table' AND name = ?;";
    SqliteStatement findTableStmt(*session, findTableQuery);
    findTableStmt.bindText(0, ident.rawData(), ident.size());

    int status = findTableStmt.step();
    if (status == SQLITE_DONE) {
        return false;
    }
    checkStatus(status, SQLITE_ROW, "sqlite3_step");

    return true;
}

std::vector<std::string> MobileKVEngine::getAllIdents(OperationContext* opCtx) const {
    std::vector<std::string> idents;
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);
    std::string getTablesQuery = "SELECT name FROM sqlite_master WHERE type='table';";
    SqliteStatement getTablesStmt(*session, getTablesQuery);

    int status;
    while ((status = getTablesStmt.step()) == SQLITE_ROW) {
        std::string tableName(reinterpret_cast<const char*>(getTablesStmt.getColText(0)));
        idents.push_back(tableName);
    }
    checkStatus(status, SQLITE_DONE, "sqlite3_step");
    return idents;
}

}  // namespace mongo