forked from apple/foundationdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadSafeTransaction.actor.cpp
409 lines (335 loc) · 13 KB
/
ThreadSafeTransaction.actor.cpp
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
/*
* ThreadSafeTransaction.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fdbclient/ThreadSafeTransaction.h"
#include "fdbclient/ReadYourWrites.h"
#include "fdbclient/DatabaseContext.h"
#if defined(CMAKE_BUILD) || !defined(WIN32)
#include "versions.h"
#endif
#include <new>
// Users of ThreadSafeTransaction might share Reference<ThreadSafe...> between different threads as long as they don't call addRef (e.g. C API follows this).
// Therefore, it is unsafe to call (explicitly or implicitly) this->addRef in any of these functions.
ThreadFuture<Void> ThreadSafeDatabase::onConnected() {
DatabaseContext *db = this->db;
return onMainThread( [db]() -> Future<Void> {
db->checkDeferredError();
return db->onConnected();
} );
}
ThreadFuture<Reference<IDatabase>> ThreadSafeDatabase::createFromExistingDatabase(Database db) {
return onMainThread( [db](){
db->checkDeferredError();
DatabaseContext *cx = db.getPtr();
cx->addref();
return Future<Reference<IDatabase>>(Reference<IDatabase>(new ThreadSafeDatabase(cx)));
});
}
Reference<ITransaction> ThreadSafeDatabase::createTransaction() {
return Reference<ITransaction>(new ThreadSafeTransaction(db));
}
void ThreadSafeDatabase::setOption( FDBDatabaseOptions::Option option, Optional<StringRef> value) {
auto itr = FDBDatabaseOptions::optionInfo.find(option);
if(itr != FDBDatabaseOptions::optionInfo.end()) {
TraceEvent("SetDatabaseOption").detail("Option", itr->second.name);
}
else {
TraceEvent("UnknownDatabaseOption").detail("Option", option);
throw invalid_option();
}
DatabaseContext *db = this->db;
Standalone<Optional<StringRef>> passValue = value;
// ThreadSafeDatabase is not allowed to do anything with options except pass them through to RYW.
onMainThreadVoid( [db, option, passValue](){
db->checkDeferredError();
db->setOption(option, passValue.contents());
}, &db->deferredError );
}
ThreadSafeDatabase::ThreadSafeDatabase(std::string connFilename, int apiVersion) {
ClusterConnectionFile *connFile = new ClusterConnectionFile(ClusterConnectionFile::lookupClusterFileName(connFilename).first);
// Allocate memory for the Database from this thread (so the pointer is known for subsequent method calls)
// but run its constructor on the main thread
DatabaseContext *db = this->db = DatabaseContext::allocateOnForeignThread();
onMainThreadVoid([db, connFile, apiVersion](){
try {
Database::createDatabase(Reference<ClusterConnectionFile>(connFile), apiVersion, false, LocalityData(), db).extractPtr();
}
catch(Error &e) {
new (db) DatabaseContext(e);
}
catch(...) {
new (db) DatabaseContext(unknown_error());
}
}, NULL);
}
ThreadSafeDatabase::~ThreadSafeDatabase() {
DatabaseContext *db = this->db;
onMainThreadVoid( [db](){ db->delref(); }, NULL );
}
ThreadSafeTransaction::ThreadSafeTransaction(DatabaseContext* cx) {
// Allocate memory for the transaction from this thread (so the pointer is known for subsequent method calls)
// but run its constructor on the main thread
// It looks strange that the DatabaseContext::addref is deferred by the onMainThreadVoid call, but it is safe
// because the reference count of the DatabaseContext is solely managed from the main thread. If cx is destructed
// immediately after this call, it will defer the DatabaseContext::delref (and onMainThread preserves the order of
// these operations).
ReadYourWritesTransaction *tr = this->tr = ReadYourWritesTransaction::allocateOnForeignThread();
// No deferred error -- if the construction of the RYW transaction fails, we have no where to put it
onMainThreadVoid(
[tr, cx]() {
cx->addref();
new (tr) ReadYourWritesTransaction(Database(cx));
},
NULL);
}
ThreadSafeTransaction::~ThreadSafeTransaction() {
ReadYourWritesTransaction *tr = this->tr;
if (tr)
onMainThreadVoid( [tr](){ tr->delref(); }, NULL );
}
void ThreadSafeTransaction::cancel() {
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr](){ tr->cancel(); }, NULL );
}
void ThreadSafeTransaction::setVersion( Version v ) {
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, v](){ tr->setVersion(v); }, &tr->deferredError );
}
ThreadFuture<Version> ThreadSafeTransaction::getReadVersion() {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr]() -> Future<Version> {
tr->checkDeferredError();
return tr->getReadVersion();
} );
}
ThreadFuture< Optional<Value> > ThreadSafeTransaction::get( const KeyRef& key, bool snapshot ) {
Key k = key;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, k, snapshot]() -> Future< Optional<Value> > {
tr->checkDeferredError();
return tr->get(k, snapshot);
} );
}
ThreadFuture< Key > ThreadSafeTransaction::getKey( const KeySelectorRef& key, bool snapshot ) {
KeySelector k = key;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, k, snapshot]() -> Future< Key > {
tr->checkDeferredError();
return tr->getKey(k, snapshot);
} );
}
ThreadFuture< Standalone<RangeResultRef> > ThreadSafeTransaction::getRange( const KeySelectorRef& begin, const KeySelectorRef& end, int limit, bool snapshot, bool reverse ) {
KeySelector b = begin;
KeySelector e = end;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, b, e, limit, snapshot, reverse]() -> Future< Standalone<RangeResultRef> > {
tr->checkDeferredError();
return tr->getRange(b, e, limit, snapshot, reverse);
} );
}
ThreadFuture< Standalone<RangeResultRef> > ThreadSafeTransaction::getRange( const KeySelectorRef& begin, const KeySelectorRef& end, GetRangeLimits limits, bool snapshot, bool reverse ) {
KeySelector b = begin;
KeySelector e = end;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, b, e, limits, snapshot, reverse]() -> Future< Standalone<RangeResultRef> > {
tr->checkDeferredError();
return tr->getRange(b, e, limits, snapshot, reverse);
} );
}
ThreadFuture<Standalone<VectorRef<const char*>>> ThreadSafeTransaction::getAddressesForKey( const KeyRef& key ) {
Key k = key;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, k]() -> Future< Standalone<VectorRef<const char*> >> {
tr->checkDeferredError();
return tr->getAddressesForKey(k);
} );
}
void ThreadSafeTransaction::addReadConflictRange( const KeyRangeRef& keys) {
KeyRange r = keys;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, r](){ tr->addReadConflictRange(r); }, &tr->deferredError );
}
void ThreadSafeTransaction::makeSelfConflicting() {
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr](){ tr->makeSelfConflicting(); }, &tr->deferredError );
}
void ThreadSafeTransaction::atomicOp( const KeyRef& key, const ValueRef& value, uint32_t operationType ) {
Key k = key;
Value v = value;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, k, v, operationType](){ tr->atomicOp(k, v, operationType); }, &tr->deferredError );
}
void ThreadSafeTransaction::set( const KeyRef& key, const ValueRef& value ) {
Key k = key;
Value v = value;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, k, v](){ tr->set(k, v); }, &tr->deferredError );
}
void ThreadSafeTransaction::clear( const KeyRangeRef& range ) {
KeyRange r = range;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, r](){ tr->clear(r); }, &tr->deferredError );
}
void ThreadSafeTransaction::clear( const KeyRef& begin, const KeyRef& end ) {
Key b = begin;
Key e = end;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, b, e](){
if(b > e)
throw inverted_range();
tr->clear(KeyRangeRef(b, e));
}, &tr->deferredError );
}
void ThreadSafeTransaction::clear( const KeyRef& key ) {
Key k = key;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, k](){ tr->clear(k); }, &tr->deferredError );
}
ThreadFuture< Void > ThreadSafeTransaction::watch( const KeyRef& key ) {
Key k = key;
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, k]() -> Future< Void > {
tr->checkDeferredError();
return tr->watch(k);
});
}
void ThreadSafeTransaction::addWriteConflictRange( const KeyRangeRef& keys) {
KeyRange r = keys;
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr, r](){ tr->addWriteConflictRange(r); }, &tr->deferredError );
}
ThreadFuture< Void > ThreadSafeTransaction::commit() {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr]() -> Future< Void > {
tr->checkDeferredError();
return tr->commit();
} );
}
Version ThreadSafeTransaction::getCommittedVersion() {
// This should be thread safe when called legally, but it is fragile
return tr->getCommittedVersion();
}
ThreadFuture<int64_t> ThreadSafeTransaction::getApproximateSize() {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread([tr]() -> Future<int64_t> { return tr->getApproximateSize(); });
}
ThreadFuture<Standalone<StringRef>> ThreadSafeTransaction::getVersionstamp() {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread([tr]() -> Future < Standalone<StringRef> > {
return tr->getVersionstamp();
});
}
void ThreadSafeTransaction::setOption( FDBTransactionOptions::Option option, Optional<StringRef> value ) {
auto itr = FDBTransactionOptions::optionInfo.find(option);
if(itr == FDBTransactionOptions::optionInfo.end()) {
TraceEvent("UnknownTransactionOption").detail("Option", option);
throw invalid_option();
}
ReadYourWritesTransaction *tr = this->tr;
Standalone<Optional<StringRef>> passValue = value;
// ThreadSafeTransaction is not allowed to do anything with options except pass them through to RYW.
onMainThreadVoid( [tr, option, passValue](){ tr->setOption(option, passValue.contents()); }, &tr->deferredError );
}
ThreadFuture<Void> ThreadSafeTransaction::checkDeferredError() {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr](){
try {
tr->checkDeferredError();
} catch (Error &e) {
tr->deferredError = Error();
return Future<Void>(e);
}
return Future<Void>(Void());
} );
}
ThreadFuture<Void> ThreadSafeTransaction::onError( Error const& e ) {
ReadYourWritesTransaction *tr = this->tr;
return onMainThread( [tr, e](){ return tr->onError(e); } );
}
void ThreadSafeTransaction::operator=(ThreadSafeTransaction&& r) BOOST_NOEXCEPT {
tr = r.tr;
r.tr = NULL;
}
ThreadSafeTransaction::ThreadSafeTransaction(ThreadSafeTransaction&& r) BOOST_NOEXCEPT {
tr = r.tr;
r.tr = NULL;
}
void ThreadSafeTransaction::reset() {
ReadYourWritesTransaction *tr = this->tr;
onMainThreadVoid( [tr](){ tr->reset(); }, NULL );
}
extern const char* getHGVersion();
ThreadSafeApi::ThreadSafeApi() : apiVersion(-1), clientVersion(format("%s,%s,%llx", FDB_VT_VERSION, getHGVersion(), currentProtocolVersion)), transportId(0) {}
void ThreadSafeApi::selectApiVersion(int apiVersion) {
this->apiVersion = apiVersion;
}
const char* ThreadSafeApi::getClientVersion() {
// There is only one copy of the ThreadSafeAPI, and it never gets deleted. Also, clientVersion is never modified.
return clientVersion.c_str();
}
void ThreadSafeApi::setNetworkOption(FDBNetworkOptions::Option option, Optional<StringRef> value) {
if (option == FDBNetworkOptions::EXTERNAL_CLIENT_TRANSPORT_ID) {
if(value.present()) {
transportId = std::stoull(value.get().toString().c_str());
}
}
else {
::setNetworkOption(option, value);
}
}
void ThreadSafeApi::setupNetwork() {
::setupNetwork(transportId);
}
void ThreadSafeApi::runNetwork() {
Optional<Error> runErr;
try {
::runNetwork();
}
catch(Error &e) {
runErr = e;
}
for(auto &hook : threadCompletionHooks) {
try {
hook.first(hook.second);
}
catch(Error &e) {
TraceEvent(SevError, "NetworkShutdownHookError").error(e);
}
catch(...) {
TraceEvent(SevError, "NetworkShutdownHookError").error(unknown_error());
}
}
if(runErr.present()) {
throw runErr.get();
}
}
void ThreadSafeApi::stopNetwork() {
::stopNetwork();
}
Reference<IDatabase> ThreadSafeApi::createDatabase(const char *clusterFilePath) {
return Reference<IDatabase>(new ThreadSafeDatabase(clusterFilePath, apiVersion));
}
void ThreadSafeApi::addNetworkThreadCompletionHook(void (*hook)(void*), void *hookParameter) {
if (!g_network) {
throw network_not_setup();
}
MutexHolder holder(lock); // We could use the network thread to protect this action, but then we can't guarantee upon return that the hook is set.
threadCompletionHooks.push_back(std::make_pair(hook, hookParameter));
}
IClientApi* ThreadSafeApi::api = new ThreadSafeApi();