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
|
/**
* Copyright (C) 2016 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::kSharding
#include "mongo/platform/basic.h"
#include "mongo/db/s/metadata_manager.h"
#include "mongo/bson/simple_bsonobj_comparator.h"
#include "mongo/db/range_arithmetic.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/stdx/memory.h"
#include "mongo/util/log.h"
namespace mongo {
using CallbackArgs = executor::TaskExecutor::CallbackArgs;
MetadataManager::MetadataManager(ServiceContext* sc, NamespaceString nss)
: _nss(std::move(nss)),
_serviceContext(sc),
_activeMetadataTracker(stdx::make_unique<CollectionMetadataTracker>(nullptr)),
_receivingChunks(
SimpleBSONObjComparator::kInstance.makeBSONObjIndexedMap<CachedChunkInfo>()) {}
MetadataManager::~MetadataManager() {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
invariant(!_activeMetadataTracker || _activeMetadataTracker->usageCounter == 0);
}
ScopedCollectionMetadata MetadataManager::getActiveMetadata(std::shared_ptr<MetadataManager> self) {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
if (!_activeMetadataTracker) {
return ScopedCollectionMetadata();
}
return ScopedCollectionMetadata(std::move(self), _activeMetadataTracker.get());
}
void MetadataManager::refreshActiveMetadata(std::unique_ptr<CollectionMetadata> remoteMetadata) {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
// Collection was never sharded in the first place. This check is necessary in order to avoid
// extraneous logging in the not-a-shard case, because all call sites always try to get the
// collection sharding information regardless of whether the node is sharded or not.
if (!remoteMetadata && !_activeMetadataTracker->metadata) {
invariant(_receivingChunks.empty());
return;
}
// Collection is becoming unsharded
if (!remoteMetadata) {
log() << "Marking collection " << _nss.ns() << " with "
<< _activeMetadataTracker->metadata->toStringBasic() << " as no longer sharded";
_receivingChunks.clear();
_setActiveMetadata_inlock(nullptr);
return;
}
// We should never be setting unsharded metadata
invariant(!remoteMetadata->getCollVersion().isWriteCompatibleWith(ChunkVersion::UNSHARDED()));
invariant(!remoteMetadata->getShardVersion().isWriteCompatibleWith(ChunkVersion::UNSHARDED()));
// Collection is becoming sharded
if (!_activeMetadataTracker->metadata) {
log() << "Marking collection " << _nss.ns() << " as sharded with "
<< remoteMetadata->toStringBasic();
invariant(_receivingChunks.empty());
_setActiveMetadata_inlock(std::move(remoteMetadata));
return;
}
// If the metadata being installed has a different epoch from ours, this means the collection
// was dropped and recreated, so we must entirely reset the metadata state
if (_activeMetadataTracker->metadata->getCollVersion().epoch() !=
remoteMetadata->getCollVersion().epoch()) {
log() << "Overwriting metadata for collection " << _nss.ns() << " from "
<< _activeMetadataTracker->metadata->toStringBasic() << " to "
<< remoteMetadata->toStringBasic() << " due to epoch change";
_receivingChunks.clear();
_setActiveMetadata_inlock(std::move(remoteMetadata));
return;
}
// We already have newer version
if (_activeMetadataTracker->metadata->getCollVersion() >= remoteMetadata->getCollVersion()) {
LOG(1) << "Ignoring refresh of active metadata "
<< _activeMetadataTracker->metadata->toStringBasic() << " with an older "
<< remoteMetadata->toStringBasic();
return;
}
log() << "Refreshing metadata for collection " << _nss.ns() << " from "
<< _activeMetadataTracker->metadata->toStringBasic() << " to "
<< remoteMetadata->toStringBasic();
// Resolve any receiving chunks, which might have completed by now
for (auto it = _receivingChunks.begin(); it != _receivingChunks.end();) {
const BSONObj min = it->first;
const BSONObj max = it->second.getMaxKey();
// Our pending range overlaps at least one chunk
if (rangeMapContains(remoteMetadata->getChunks(), min, max)) {
// The remote metadata contains a chunk we were earlier in the process of receiving, so
// we deem it successfully received.
LOG(2) << "Verified chunk " << redact(ChunkRange(min, max).toString())
<< " for collection " << _nss.ns() << " has been migrated to this shard earlier";
_receivingChunks.erase(it++);
continue;
} else if (!rangeMapOverlaps(remoteMetadata->getChunks(), min, max)) {
++it;
continue;
}
// Partial overlap indicates that the earlier migration has failed, but the chunk being
// migrated underwent some splits and other migrations and ended up here again. In this
// case, we will request full reload of the metadata. Currently this cannot happen, because
// all migrations are with the explicit knowledge of the recipient shard. However, we leave
// the option open so that chunk splits can do empty chunk move without having to notify the
// recipient.
RangeVector overlappedChunks;
getRangeMapOverlap(remoteMetadata->getChunks(), min, max, &overlappedChunks);
for (const auto& overlapChunkMin : overlappedChunks) {
auto itRecv = _receivingChunks.find(overlapChunkMin.first);
invariant(itRecv != _receivingChunks.end());
const ChunkRange receivingRange(itRecv->first, itRecv->second.getMaxKey());
_receivingChunks.erase(itRecv);
}
// Need to reset the iterator
it = _receivingChunks.begin();
}
// For compatibility with the current range deleter, which is driven entirely by the contents of
// the CollectionMetadata update the pending chunks
for (const auto& receivingChunk : _receivingChunks) {
ChunkType chunk;
chunk.setMin(receivingChunk.first);
chunk.setMax(receivingChunk.second.getMaxKey());
remoteMetadata = remoteMetadata->clonePlusPending(chunk);
}
_setActiveMetadata_inlock(std::move(remoteMetadata));
}
void MetadataManager::beginReceive(const ChunkRange& range) {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
// Collection is not known to be sharded if the active metadata tracker is null
invariant(_activeMetadataTracker);
// If range is contained within pending chunks, this means a previous migration must have failed
// and we need to clean all overlaps
RangeVector overlappedChunks;
getRangeMapOverlap(_receivingChunks, range.getMin(), range.getMax(), &overlappedChunks);
for (const auto& overlapChunkMin : overlappedChunks) {
auto itRecv = _receivingChunks.find(overlapChunkMin.first);
invariant(itRecv != _receivingChunks.end());
_receivingChunks.erase(itRecv);
}
// Need to ensure that the background range deleter task won't delete the range we are about to
// receive
_receivingChunks.insert(
std::make_pair(range.getMin().getOwned(),
CachedChunkInfo(range.getMax().getOwned(), ChunkVersion::IGNORED())));
// For compatibility with the current range deleter, update the pending chunks on the collection
// metadata to include the chunk being received
ChunkType chunk;
chunk.setMin(range.getMin());
chunk.setMax(range.getMax());
_setActiveMetadata_inlock(_activeMetadataTracker->metadata->clonePlusPending(chunk));
}
void MetadataManager::forgetReceive(const ChunkRange& range) {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
{
auto it = _receivingChunks.find(range.getMin());
invariant(it != _receivingChunks.end());
// Verify entire ChunkRange is identical, not just the min key.
invariant(
SimpleBSONObjComparator::kInstance.evaluate(it->second.getMaxKey() == range.getMax()));
_receivingChunks.erase(it);
}
// For compatibility with the current range deleter, update the pending chunks on the collection
// metadata to exclude the chunk being received, which was added in beginReceive
ChunkType chunk;
chunk.setMin(range.getMin());
chunk.setMax(range.getMax());
_setActiveMetadata_inlock(_activeMetadataTracker->metadata->cloneMinusPending(chunk));
}
RangeMap MetadataManager::getCopyOfReceivingChunks() {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
return _receivingChunks;
}
void MetadataManager::_setActiveMetadata_inlock(std::unique_ptr<CollectionMetadata> newMetadata) {
if (_activeMetadataTracker->usageCounter > 0) {
_metadataInUse.push_front(std::move(_activeMetadataTracker));
}
_activeMetadataTracker = stdx::make_unique<CollectionMetadataTracker>(std::move(newMetadata));
}
void MetadataManager::_removeMetadata_inlock(CollectionMetadataTracker* metadataTracker) {
invariant(metadataTracker->usageCounter == 0);
auto i = _metadataInUse.begin();
const auto e = _metadataInUse.end();
while (i != e) {
if (metadataTracker == i->get()) {
_metadataInUse.erase(i);
return;
}
++i;
}
}
MetadataManager::CollectionMetadataTracker::CollectionMetadataTracker(
std::unique_ptr<CollectionMetadata> m)
: metadata(std::move(m)) {}
ScopedCollectionMetadata::ScopedCollectionMetadata() = default;
// called in lock
ScopedCollectionMetadata::ScopedCollectionMetadata(
std::shared_ptr<MetadataManager> manager, MetadataManager::CollectionMetadataTracker* tracker)
: _manager(std::move(manager)), _tracker(tracker) {
_tracker->usageCounter++;
}
ScopedCollectionMetadata::~ScopedCollectionMetadata() {
if (!_tracker)
return;
_decrementUsageCounter();
}
CollectionMetadata* ScopedCollectionMetadata::operator->() const {
return _tracker->metadata.get();
}
CollectionMetadata* ScopedCollectionMetadata::getMetadata() const {
return _tracker->metadata.get();
}
ScopedCollectionMetadata::ScopedCollectionMetadata(ScopedCollectionMetadata&& other) {
*this = std::move(other);
}
ScopedCollectionMetadata& ScopedCollectionMetadata::operator=(ScopedCollectionMetadata&& other) {
if (this != &other) {
// If "this" was previously initialized, make sure we perform the same logic as in the
// destructor to decrement _tracker->usageCounter for the CollectionMetadata "this" had a
// reference to before replacing _tracker with other._tracker.
if (_tracker) {
_decrementUsageCounter();
}
_manager = other._manager;
_tracker = other._tracker;
other._manager = nullptr;
other._tracker = nullptr;
}
return *this;
}
void ScopedCollectionMetadata::_decrementUsageCounter() {
invariant(_manager);
invariant(_tracker);
stdx::lock_guard<stdx::mutex> scopedLock(_manager->_managerLock);
invariant(_tracker->usageCounter > 0);
if (--_tracker->usageCounter == 0) {
_manager->_removeMetadata_inlock(_tracker);
}
}
ScopedCollectionMetadata::operator bool() const {
return _tracker && _tracker->metadata.get();
}
void MetadataManager::append(BSONObjBuilder* builder) {
stdx::lock_guard<stdx::mutex> scopedLock(_managerLock);
BSONArrayBuilder pcArr(builder->subarrayStart("pendingChunks"));
for (const auto& entry : _receivingChunks) {
BSONObjBuilder obj;
ChunkRange r = ChunkRange(entry.first, entry.second.getMaxKey());
r.append(&obj);
pcArr.append(obj.done());
}
pcArr.done();
BSONArrayBuilder amrArr(builder->subarrayStart("activeMetadataRanges"));
for (const auto& entry : _activeMetadataTracker->metadata->getChunks()) {
BSONObjBuilder obj;
ChunkRange r = ChunkRange(entry.first, entry.second.getMaxKey());
r.append(&obj);
amrArr.append(obj.done());
}
amrArr.done();
}
} // namespace mongo
|