forked from mongodb/mongo
/
commands_admin.cpp
2929 lines (2497 loc) · 125 KB
/
commands_admin.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2008 10gen 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/>.
*/
#include "pch.h"
#include <boost/thread/thread.hpp>
#include "mongo/db/commands.h"
#include "mongo/client/connpool.h"
#include "mongo/client/dbclientcursor.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/dbmessage.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/repl/rs_optime.h"
#include "mongo/s/chunk.h"
#include "mongo/s/client_info.h"
#include "mongo/s/config.h"
#include "mongo/s/d_logic.h"
#include "mongo/s/field_parser.h"
#include "mongo/s/grid.h"
#include "mongo/db/oplogreader.h"
#include "mongo/s/strategy.h"
#include "mongo/s/type_chunk.h"
#include "mongo/s/type_database.h"
#include "mongo/s/type_shard.h"
#include "mongo/s/type_settings.h"
#include "mongo/s/writeback_listener.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/net/message.h"
#include "mongo/util/processinfo.h"
#include "mongo/util/ramlog.h"
#include "mongo/util/stringutils.h"
#include "mongo/util/timer.h"
#include "mongo/util/version.h"
namespace mongo {
namespace dbgrid_cmds {
class GridAdminCmd : public Command {
public:
GridAdminCmd( const char * n ) : Command( n , false, tolowerString(n).c_str() ) {
}
virtual bool slaveOk() const {
return true;
}
virtual bool adminOnly() const {
return true;
}
// all grid commands are designed not to lock
virtual LockType locktype() const { return NONE; }
bool okForConfigChanges( string& errmsg ) {
string e;
if ( ! configServer.allUp(e) ) {
errmsg = str::stream() << "not all config servers are up: " << e;
return false;
}
return true;
}
};
// --------------- misc commands ----------------------
class NetStatCmd : public GridAdminCmd {
public:
NetStatCmd() : GridAdminCmd("netstat") { }
virtual void help( stringstream& help ) const {
help << " shows status/reachability of servers in the cluster";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::netstat);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
result.append("configserver", configServer.getPrimary().getConnString() );
result.append("isdbgrid", 1);
return true;
}
} netstat;
class FlushRouterConfigCmd : public GridAdminCmd {
public:
FlushRouterConfigCmd() : GridAdminCmd("flushRouterConfig") { }
virtual void help( stringstream& help ) const {
help << "flush all router config";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::flushRouterConfig);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
grid.flushConfig();
result.appendBool( "flushed" , true );
return true;
}
} flushRouterConfigCmd;
class FsyncCommand : public GridAdminCmd {
public:
FsyncCommand() : GridAdminCmd( "fsync" ) {}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::fsync);
out->push_back(Privilege(AuthorizationManager::SERVER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
if ( cmdObj["lock"].trueValue() ) {
errmsg = "can't do lock through mongos";
return false;
}
BSONObjBuilder sub;
bool ok = true;
int numFiles = 0;
vector<Shard> shards;
Shard::getAllShards( shards );
for ( vector<Shard>::iterator i=shards.begin(); i!=shards.end(); i++ ) {
Shard s = *i;
BSONObj x = s.runCommand( "admin" , "fsync" );
sub.append( s.getName() , x );
if ( ! x["ok"].trueValue() ) {
ok = false;
errmsg = x["errmsg"].String();
}
numFiles += x["numFiles"].numberInt();
}
result.append( "numFiles" , numFiles );
result.append( "all" , sub.obj() );
return ok;
}
} fsyncCmd;
// ------------ database level commands -------------
class MoveDatabasePrimaryCommand : public GridAdminCmd {
public:
MoveDatabasePrimaryCommand() : GridAdminCmd("movePrimary") { }
virtual void help( stringstream& help ) const {
help << " example: { moveprimary : 'foo' , to : 'localhost:9999' }";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::movePrimary);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string dbname = cmdObj.firstElement().valuestrsafe();
if ( dbname.size() == 0 ) {
errmsg = "no db";
return false;
}
if ( dbname == "config" ) {
errmsg = "can't move config db";
return false;
}
// Flush the configuration
// This can't be perfect, but it's better than nothing.
grid.flushConfig();
DBConfigPtr config = grid.getDBConfig( dbname , false );
if ( ! config ) {
errmsg = "can't find db!";
return false;
}
string to = cmdObj["to"].valuestrsafe();
if ( ! to.size() ) {
errmsg = "you have to specify where you want to move it";
return false;
}
Shard s = Shard::make( to );
if ( config->getPrimary() == s.getConnString() ) {
errmsg = "it is already the primary";
return false;
}
if ( ! grid.knowAboutShard( s.getConnString() ) ) {
errmsg = "that server isn't known to me";
return false;
}
log() << "Moving " << dbname << " primary from: " << config->getPrimary().toString()
<< " to: " << s.toString() << endl;
// Locking enabled now...
DistributedLock lockSetup( configServer.getConnectionString(), dbname + "-movePrimary" );
dist_lock_try dlk;
// Distributed locking added.
try{
dlk = dist_lock_try( &lockSetup , string("Moving primary shard of ") + dbname );
}
catch( LockException& e ){
errmsg = str::stream() << "error locking distributed lock to move primary shard of " << dbname << causedBy( e );
warning() << errmsg << endl;
return false;
}
if ( ! dlk.got() ) {
errmsg = (string)"metadata lock is already taken for moving " + dbname;
return false;
}
set<string> shardedColls;
config->getAllShardedCollections( shardedColls );
BSONArrayBuilder barr;
barr.append( shardedColls );
scoped_ptr<ScopedDbConnection> toconn(
ScopedDbConnection::getScopedDbConnection( s.getConnString() ) );
// TODO ERH - we need a clone command which replays operations from clone start to now
// can just use local.oplog.$main
BSONObj cloneRes;
bool worked = toconn->get()->runCommand(
dbname.c_str(),
BSON( "clone" << config->getPrimary().getConnString() <<
"collsToIgnore" << barr.arr() ),
cloneRes );
toconn->done();
if ( ! worked ) {
log() << "clone failed" << cloneRes << endl;
errmsg = "clone failed";
return false;
}
string oldPrimary = config->getPrimary().getConnString();
scoped_ptr<ScopedDbConnection> fromconn(
ScopedDbConnection::getScopedDbConnection( config->getPrimary()
.getConnString() ) );
config->setPrimary( s.getConnString() );
if( shardedColls.empty() ){
// TODO: Collections can be created in the meantime, and we should handle in the future.
log() << "movePrimary dropping database on " << oldPrimary << ", no sharded collections in " << dbname << endl;
try {
fromconn->get()->dropDatabase( dbname.c_str() );
}
catch( DBException& e ){
e.addContext( str::stream() << "movePrimary could not drop the database " << dbname << " on " << oldPrimary );
throw;
}
}
else if( cloneRes["clonedColls"].type() != Array ){
// Legacy behavior from old mongod with sharded collections, *do not* delete database,
// but inform user they can drop manually (or ignore).
warning() << "movePrimary legacy mongod behavior detected, user must manually remove unsharded collections in "
<< "database " << dbname << " on " << oldPrimary << endl;
}
else {
// We moved some unsharded collections, but not all
BSONObjIterator it( cloneRes["clonedColls"].Obj() );
while( it.more() ){
BSONElement el = it.next();
if( el.type() == String ){
try {
log() << "movePrimary dropping cloned collection " << el.String() << " on " << oldPrimary << endl;
fromconn->get()->dropCollection( el.String() );
}
catch( DBException& e ){
e.addContext( str::stream() << "movePrimary could not drop the cloned collection " << el.String() << " on " << oldPrimary );
throw;
}
}
}
}
fromconn->done();
result << "primary " << s.toString();
return true;
}
} movePrimary;
class EnableShardingCmd : public GridAdminCmd {
public:
EnableShardingCmd() : GridAdminCmd( "enableSharding" ) {}
virtual void help( stringstream& help ) const {
help
<< "Enable sharding for a db. (Use 'shardcollection' command afterwards.)\n"
<< " { enablesharding : \"<dbname>\" }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::enableSharding);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
string dbname = cmdObj.firstElement().valuestrsafe();
if ( dbname.size() == 0 ) {
errmsg = "no db";
return false;
}
if ( dbname == "admin" ) {
errmsg = "can't shard the admin db";
return false;
}
if ( dbname == "local" ) {
errmsg = "can't shard the local db";
return false;
}
DBConfigPtr config = grid.getDBConfig( dbname );
if ( config->isShardingEnabled() ) {
errmsg = "already enabled";
return false;
}
if ( ! okForConfigChanges( errmsg ) )
return false;
log() << "enabling sharding on: " << dbname << endl;
config->enableSharding();
return true;
}
} enableShardingCmd;
// ------------ collection level commands -------------
class ShardCollectionCmd : public GridAdminCmd {
public:
ShardCollectionCmd() : GridAdminCmd( "shardCollection" ) {}
virtual void help( stringstream& help ) const {
help
<< "Shard a collection. Requires key. Optional unique. Sharding must already be enabled for the database.\n"
<< " { enablesharding : \"<dbname>\" }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::shardCollection);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
const string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "no ns";
return false;
}
const NamespaceString nsStr( ns );
if ( !nsStr.isValid() ){
errmsg = str::stream() << "bad ns[" << ns << "]";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isShardingEnabled() ) {
errmsg = "sharding not enabled for db";
return false;
}
if ( config->isSharded( ns ) ) {
errmsg = "already sharded";
return false;
}
BSONObj proposedKey = cmdObj.getObjectField( "key" );
if ( proposedKey.isEmpty() ) {
errmsg = "no shard key";
return false;
}
// Currently the allowable shard keys are either
// i) a hashed single field, e.g. { a : "hashed" }, or
// ii) a compound list of ascending fields, e.g. { a : 1 , b : 1 }
if ( proposedKey.firstElementType() == mongo::String ) {
// case i)
if ( !str::equals( proposedKey.firstElement().valuestrsafe() , "hashed" ) ) {
errmsg = "unrecognized string: " + proposedKey.firstElement().str();
return false;
}
if ( proposedKey.nFields() > 1 ) {
errmsg = "hashed shard keys currently only support single field keys";
return false;
}
if ( cmdObj["unique"].trueValue() ) {
// it's possible to ensure uniqueness on the hashed field by
// declaring an additional (non-hashed) unique index on the field,
// but the hashed shard key itself should not be declared unique
errmsg = "hashed shard keys cannot be declared unique.";
return false;
}
} else {
// case ii)
BSONForEach(e, proposedKey) {
if (!e.isNumber() || e.number() != 1.0) {
errmsg = str::stream() << "Unsupported shard key pattern. Pattern must"
<< " either be a single hashed field, or a list"
<< " of ascending fields.";
return false;
}
}
}
if ( ns.find( ".system." ) != string::npos ) {
errmsg = "can't shard system namespaces";
return false;
}
if ( ! okForConfigChanges( errmsg ) )
return false;
//the rest of the checks require a connection to the primary db
scoped_ptr<ScopedDbConnection> conn(
ScopedDbConnection::getScopedDbConnection(
config->getPrimary().getConnString() ) );
//check that collection is not capped
BSONObj res = conn->get()->findOne( config->getName() + ".system.namespaces",
BSON( "name" << ns ) );
if ( res["options"].type() == Object &&
res["options"].embeddedObject()["capped"].trueValue() ) {
errmsg = "can't shard capped collection";
conn->done();
return false;
}
// The proposed shard key must be validated against the set of existing indexes.
// In particular, we must ensure the following constraints
//
// 1. All existing unique indexes, except those which start with the _id index,
// must contain the proposed key as a prefix (uniqueness of the _id index is
// ensured by the _id generation process or guaranteed by the user).
//
// 2. If the collection is not empty, there must exist at least one index that
// is "useful" for the proposed key. A "useful" index is defined as follows
// Useful Index:
// i. contains proposedKey as a prefix
// ii. is not sparse
// iii. contains no null values
// iv. is not multikey (maybe lift this restriction later)
//
// 3. If the proposed shard key is specified as unique, there must exist a useful,
// unique index exactly equal to the proposedKey (not just a prefix).
//
// After validating these constraint:
//
// 4. If there is no useful index, and the collection is non-empty, we
// must fail.
//
// 5. If the collection is empty, and it's still possible to create an index
// on the proposed key, we go ahead and do so.
string indexNS = config->getName() + ".system.indexes";
// 1. Verify consistency with existing unique indexes
BSONObj uniqueQuery = BSON( "ns" << ns << "unique" << true );
auto_ptr<DBClientCursor> uniqueQueryResult =
conn->get()->query( indexNS , uniqueQuery );
ShardKeyPattern proposedShardKey( proposedKey );
while ( uniqueQueryResult->more() ) {
BSONObj idx = uniqueQueryResult->next();
BSONObj currentKey = idx["key"].embeddedObject();
if( ! proposedShardKey.isUniqueIndexCompatible( currentKey ) ) {
errmsg = str::stream() << "can't shard collection '" << ns << "' "
<< "with unique index on " << currentKey << " "
<< "and proposed shard key " << proposedKey << ". "
<< "Uniqueness can't be maintained unless "
<< "shard key is a prefix";
conn->done();
return false;
}
}
// 2. Check for a useful index
bool hasUsefulIndexForKey = false;
BSONObj allQuery = BSON( "ns" << ns );
auto_ptr<DBClientCursor> allQueryResult =
conn->get()->query( indexNS , allQuery );
BSONArrayBuilder allIndexes;
while ( allQueryResult->more() ) {
BSONObj idx = allQueryResult->next();
allIndexes.append( idx );
BSONObj currentKey = idx["key"].embeddedObject();
// Check 2.i. and 2.ii.
if ( ! idx["sparse"].trueValue() && proposedKey.isPrefixOf( currentKey ) ) {
hasUsefulIndexForKey = true;
}
}
// 3. If proposed key is required to be unique, additionally check for exact match.
bool careAboutUnique = cmdObj["unique"].trueValue();
if ( hasUsefulIndexForKey && careAboutUnique ) {
BSONObj eqQuery = BSON( "ns" << ns << "key" << proposedKey );
BSONObj eqQueryResult = conn->get()->findOne( indexNS, eqQuery );
if ( eqQueryResult.isEmpty() ) {
hasUsefulIndexForKey = false; // if no exact match, index not useful,
// but still possible to create one later
}
else {
bool isExplicitlyUnique = eqQueryResult["unique"].trueValue();
BSONObj currKey = eqQueryResult["key"].embeddedObject();
bool isCurrentID = str::equals( currKey.firstElementFieldName() , "_id" );
if ( ! isExplicitlyUnique && ! isCurrentID ) {
errmsg = str::stream() << "can't shard collection " << ns << ", "
<< proposedKey << " index not unique, "
<< "and unique index explicitly specified";
conn->done();
return false;
}
}
}
if ( hasUsefulIndexForKey ) {
// Check 2.iii and 2.iv. Make sure no null entries in the sharding index
// and that there is a useful, non-multikey index available
BSONObjBuilder cmd;
cmd.append( "checkShardingIndex" , ns );
cmd.append( "keyPattern" , proposedKey );
BSONObj cmdObj = cmd.obj();
if ( ! conn->get()->runCommand( "admin" , cmdObj , res ) ) {
errmsg = res["errmsg"].str();
conn->done();
return false;
}
}
// 4. if no useful index, and collection is non-empty, fail
else if ( conn->get()->count( ns ) != 0 ) {
errmsg = str::stream() << "please create an index that starts with the "
<< "shard key before sharding.";
result.append( "proposedKey" , proposedKey );
result.appendArray( "curIndexes" , allIndexes.done() );
conn->done();
return false;
}
// 5. If no useful index exists, and collection empty, create one on proposedKey.
// Only need to call ensureIndex on primary shard, since indexes get copied to
// receiving shard whenever a migrate occurs.
else {
// call ensureIndex with cache=false, see SERVER-1691
bool ensureSuccess = conn->get()->ensureIndex( ns ,
proposedKey ,
careAboutUnique ,
"" ,
false );
if ( ! ensureSuccess ) {
errmsg = "ensureIndex failed to create index on primary shard";
conn->done();
return false;
}
}
bool isEmpty = ( conn->get()->count( ns ) == 0 );
conn->done();
// Pre-splitting:
// For new collections which use hashed shard keys, we can can pre-split the
// range of possible hashes into a large number of chunks, and distribute them
// evenly at creation time. Until we design a better initialization scheme, the
// safest way to pre-split is to
// 1. make one big chunk for each shard
// 2. move them one at a time
// 3. split the big chunks to achieve the desired total number of initial chunks
vector<Shard> shards;
Shard primary = config->getPrimary();
primary.getAllShards( shards );
int numShards = shards.size();
vector<BSONObj> initSplits; // there will be at most numShards-1 of these
vector<BSONObj> allSplits; // all of the initial desired split points
bool isHashedShardKey =
str::equals(proposedKey.firstElement().valuestrsafe(), "hashed");
// only pre-split when using a hashed shard key and collection is still empty
if ( isHashedShardKey && isEmpty ){
int numChunks = cmdObj["numInitialChunks"].numberInt();
if ( numChunks <= 0 )
numChunks = 2*numShards; // default number of initial chunks
// hashes are signed, 64-bit ints. So we divide the range (-MIN long, +MAX long)
// into intervals of size (2^64/numChunks) and create split points at the
// boundaries. The logic below ensures that initial chunks are all
// symmetric around 0.
long long intervalSize = ( std::numeric_limits<long long>::max()/ numChunks )*2;
long long current = 0;
if( numChunks % 2 == 0 ){
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << current) );
current += intervalSize;
} else {
current += intervalSize/2;
}
for( int i=0; i < (numChunks-1)/2; i++ ){
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << current) );
allSplits.push_back( BSON(proposedKey.firstElementFieldName() << -current));
current += intervalSize;
}
sort( allSplits.begin() , allSplits.end() );
// 1. the initial splits define the "big chunks" that we will subdivide later
int lastIndex = -1;
for ( int i = 1; i < numShards; i++ ){
if ( lastIndex < (i*numChunks)/numShards - 1 ){
lastIndex = (i*numChunks)/numShards - 1;
initSplits.push_back( allSplits[ lastIndex ] );
}
}
}
tlog() << "CMD: shardcollection: " << cmdObj << endl;
config->shardCollection( ns , proposedKey , careAboutUnique , &initSplits );
result << "collectionsharded" << ns;
// only initially move chunks when using a hashed shard key
if (isHashedShardKey) {
// Reload the new config info. If we created more than one initial chunk, then
// we need to move them around to balance.
ChunkManagerPtr chunkManager = config->getChunkManager( ns , true );
ChunkMap chunkMap = chunkManager->getChunkMap();
// 2. Move and commit each "big chunk" to a different shard.
int i = 0;
for ( ChunkMap::const_iterator c = chunkMap.begin(); c != chunkMap.end(); ++c,++i ){
Shard to = shards[ i % numShards ];
ChunkPtr chunk = c->second;
// can't move chunk to shard it's already on
if ( to == chunk->getShard() )
continue;
BSONObj moveResult;
if (!chunk->moveAndCommit(to, Chunk::MaxChunkSize,
false, true, moveResult)) {
warning() << "Couldn't move chunk " << chunk << " to shard " << to
<< " while sharding collection " << ns << ". Reason: "
<< moveResult << endl;
}
}
if (allSplits.empty()) {
return true;
}
// Reload the config info, after all the migrations
chunkManager = config->getChunkManager( ns , true );
// 3. Subdivide the big chunks by splitting at each of the points in "allSplits"
// that we haven't already split by.
ChunkPtr currentChunk = chunkManager->findIntersectingChunk( allSplits[0] );
vector<BSONObj> subSplits;
for ( unsigned i = 0 ; i <= allSplits.size(); i++){
if ( i == allSplits.size() || ! currentChunk->containsPoint( allSplits[i] ) ) {
if ( ! subSplits.empty() ){
BSONObj splitResult;
if ( ! currentChunk->multiSplit( subSplits , splitResult ) ){
warning() << "Couldn't split chunk " << currentChunk
<< " while sharding collection " << ns << ". Reason: "
<< splitResult << endl;
}
subSplits.clear();
}
if ( i < allSplits.size() )
currentChunk = chunkManager->findIntersectingChunk( allSplits[i] );
} else {
subSplits.push_back( allSplits[i] );
}
}
// Proactively refresh the chunk manager. Not really necessary, but this way it's
// immediately up-to-date the next time it's used.
config->getChunkManager( ns , true );
}
return true;
}
} shardCollectionCmd;
class ReShardCollectionCmd : public GridAdminCmd {
public:
ReShardCollectionCmd() : GridAdminCmd( "reShardCollection" ) {}
virtual void help( stringstream& help ) const {
help
<< "Shard a collection with a new key. Requires new key. Optional unique. Sharding must already be enabled for the database.\n"
<< " { enablesharding : \"<dbname>\" }\n";
}
virtual void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) {
ActionSet actions;
actions.addAction(ActionType::reShardCollection);
out->push_back(Privilege(AuthorizationManager::CLUSTER_RESOURCE_NAME, actions));
}
bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool) {
Timer t;
const string ns = cmdObj.firstElement().valuestrsafe();
if ( ns.size() == 0 ) {
errmsg = "no ns";
return false;
}
const NamespaceString nsStr( ns );
if ( !nsStr.isValid() ){
errmsg = str::stream() << "bad ns[" << ns << "]";
return false;
}
DBConfigPtr config = grid.getDBConfig( ns );
if ( ! config->isShardingEnabled() ) {
errmsg = "sharding not enabled for db";
return false;
}
if ( !config->isSharded( ns ) ) {
errmsg = "already not sharded";
return false;
}
BSONObj proposedKey = cmdObj.getObjectField( "key" );
if ( proposedKey.isEmpty() ) {
errmsg = "no shard key";
return false;
}
// Currently the allowable shard keys are either
// i) a hashed single field, e.g. { a : "hashed" }, or
// ii) a compound list of ascending fields, e.g. { a : 1 , b : 1 }
if ( proposedKey.firstElementType() == mongo::String ) {
// case i)
if ( !str::equals( proposedKey.firstElement().valuestrsafe() , "hashed" ) ) {
errmsg = "unrecognized string: " + proposedKey.firstElement().str();
return false;
}
if ( proposedKey.nFields() > 1 ) {
errmsg = "hashed shard keys currently only support single field keys";
return false;
}
if ( cmdObj["unique"].trueValue() ) {
// it's possible to ensure uniqueness on the hashed field by
// declaring an additional (non-hashed) unique index on the field,
// but the hashed shard key itself should not be declared unique
errmsg = "hashed shard keys cannot be declared unique.";
return false;
}
} else {
// case ii)
BSONForEach(e, proposedKey) {
if (!e.isNumber() || e.number() != 1.0) {
errmsg = str::stream() << "Unsupported shard key pattern. Pattern must"
<< " either be a single hashed field, or a list"
<< " of ascending fields.";
return false;
}
}
}
ChunkManagerPtr manager = grid.getDBConfig(ns)->getChunkManager(ns);
ShardKeyPattern shardKeyPattern = manager->getShardKey();
if (shardKeyPattern.hasShardKey(proposedKey))
{
errmsg = "shard key already in use";
return false;
}
if ( ns.find( ".system." ) != string::npos ) {
errmsg = "can't shard system namespaces";
return false;
}
if ( ! okForConfigChanges( errmsg ) )
return false;
//the rest of the checks require a connection to the primary db
scoped_ptr<ScopedDbConnection> conn(
ScopedDbConnection::getScopedDbConnection(
config->getPrimary().getConnString() ) );
//check that collection is not capped
BSONObj res = conn->get()->findOne( config->getName() + ".system.namespaces",
BSON( "name" << ns ) );
if ( res["options"].type() == Object &&
res["options"].embeddedObject()["capped"].trueValue() ) {
errmsg = "can't shard capped collection";
conn->done();
return false;
}
// The proposed shard key must be validated against the set of existing indexes.
// In particular, we must ensure the following constraints
//
// 1. All existing unique indexes, except those which start with the _id index,
// must contain the proposed key as a prefix (uniqueness of the _id index is
// ensured by the _id generation process or guaranteed by the user).
//
// 2. If the collection is not empty, there must exist at least one index that
// is "useful" for the proposed key. A "useful" index is defined as follows
// Useful Index:
// i. contains proposedKey as a prefix
// ii. is not sparse
// iii. contains no null values
// iv. is not multikey (maybe lift this restriction later)
//
// 3. If the proposed shard key is specified as unique, there must exist a useful,
// unique index exactly equal to the proposedKey (not just a prefix).
//
// After validating these constraint:
//
// 4. If there is no useful index, and the collection is non-empty, we
// must fail.
//
// 5. If the collection is empty, and it's still possible to create an index
// on the proposed key, we go ahead and do so.
string indexNS = config->getName() + ".system.indexes";
// 1. Verify consistency with existing unique indexes
BSONObj uniqueQuery = BSON( "ns" << ns << "unique" << true );
auto_ptr<DBClientCursor> uniqueQueryResult =
conn->get()->query( indexNS , uniqueQuery );
ShardKeyPattern proposedShardKey( proposedKey );
while ( uniqueQueryResult->more() ) {
BSONObj idx = uniqueQueryResult->next();
BSONObj currentKey = idx["key"].embeddedObject();
if( ! proposedShardKey.isUniqueIndexCompatible( currentKey ) ) {
errmsg = str::stream() << "can't shard collection '" << ns << "' "
<< "with unique index on " << currentKey << " "
<< "and proposed shard key " << proposedKey << ". "
<< "Uniqueness can't be maintained unless "
<< "shard key is a prefix";
conn->done();
return false;
}
}
// 2. Check for a useful index
bool hasUsefulIndexForKey = false;
BSONObj allQuery = BSON( "ns" << ns );
auto_ptr<DBClientCursor> allQueryResult =
conn->get()->query( indexNS , allQuery );
BSONArrayBuilder allIndexes;
while ( allQueryResult->more() ) {
BSONObj idx = allQueryResult->next();
allIndexes.append( idx );
BSONObj currentKey = idx["key"].embeddedObject();
// Check 2.i. and 2.ii.
if ( ! idx["sparse"].trueValue() && proposedKey.isPrefixOf( currentKey ) ) {
hasUsefulIndexForKey = true;
}
}
// 3. If proposed key is required to be unique, additionally check for exact match.
bool careAboutUnique = cmdObj["unique"].trueValue();
if ( hasUsefulIndexForKey && careAboutUnique ) {
BSONObj eqQuery = BSON( "ns" << ns << "key" << proposedKey );
BSONObj eqQueryResult = conn->get()->findOne( indexNS, eqQuery );
if ( eqQueryResult.isEmpty() ) {
hasUsefulIndexForKey = false; // if no exact match, index not useful,
// but still possible to create one later
}
else {
bool isExplicitlyUnique = eqQueryResult["unique"].trueValue();
BSONObj currKey = eqQueryResult["key"].embeddedObject();
bool isCurrentID = str::equals( currKey.firstElementFieldName() , "_id" );
if ( ! isExplicitlyUnique && ! isCurrentID ) {
errmsg = str::stream() << "can't shard collection " << ns << ", "
<< proposedKey << " index not unique, "
<< "and unique index explicitly specified";
conn->done();
return false;
}
}
}
if ( hasUsefulIndexForKey ) {
// Check 2.iii and 2.iv. Make sure no null entries in the sharding index
// and that there is a useful, non-multikey index available
BSONObjBuilder cmd;
cmd.append( "checkShardingIndex" , ns );
cmd.append( "keyPattern" , proposedKey );
BSONObj cmdObj = cmd.obj();
if ( ! conn->get()->runCommand( "admin" , cmdObj , res ) ) {
errmsg = res["errmsg"].str();
conn->done();
return false;
}
}
// 4. if no useful index, and collection is non-empty, fail
else if ( conn->get()->count( ns ) != 0 ) {
errmsg = str::stream() << "please create an index that starts with the "
<< "shard key before sharding.";
result.append( "proposedKey" , proposedKey );
result.appendArray( "curIndexes" , allIndexes.done() );
conn->done();
return false;
}
// 5. If no useful index exists, and collection empty, create one on proposedKey.
// Only need to call ensureIndex on primary shard, since indexes get copied to
// receiving shard whenever a migrate occurs.
else {
// call ensureIndex with cache=false, see SERVER-1691
bool ensureSuccess = conn->get()->ensureIndex( ns ,
proposedKey ,
careAboutUnique ,
"" ,
false );
if ( ! ensureSuccess ) {
errmsg = "ensureIndex failed to create index on primary shard";
conn->done();
return false;
}
}
conn->done();
// 1. Calculate the splits for the new shard key
log() << "[MYCODE_TIME] Split Chunks min:" << proposedShardKey.globalMin() << "\tmax:" << proposedShardKey.globalMax() << "\tmillis:" << t.millis() << "\n";
BSONObjSet splitPoints;
int numChunk = manager->numChunks();
vector<Shard> shards;
Shard primary = grid.getDBConfig(ns)->getPrimary();
primary.getAllShards( shards );
int numShards = shards.size();
long long rowCount = 0;
for (int i = 0; i < numShards; i++)
{
log() << "[MYCODE] Shard Info: " << shards[i].toString() << endl;
scoped_ptr<ScopedDbConnection> shardconn(
ScopedDbConnection::getScopedDbConnection(
shards[i].getConnString() ) );
rowCount += shardconn->get()->count(ns);
shardconn->done();
}
log() << "[MYCODE_TIME] rowCount: " << rowCount << endl;
long long maxObjectPerChunk = rowCount / numChunk;
//if (maxObjectPerChunk > Chunk::MaxObjectPerChunk)
// maxObjectPerChunk = Chunk::MaxObjectPerChunk;