-
Notifications
You must be signed in to change notification settings - Fork 4
/
ValidateIndexes.WITHPWD.js
317 lines (292 loc) · 10.6 KB
/
ValidateIndexes.WITHPWD.js
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
/*
* ValidateIndexes.js
*
* Scans multiple nodes, gathers index information,
* and compares across other nodes.
*
* Outputs:
* 1. IndexValidationReport.<TIMESTAMP>.txt
* Human readable report of index discrepancies
* 2. IndexValidationFix.<TIMESTAMP>.js
* Script meant to run via mongo shell to
* actually fix up the index discrepancies
*
* Inputs:
* Set the connection info below
* NOTE: Wherever you run this from, it needs to be able to connect
* to the mongod nodes
*
* the 'connections' array holds all the host information
* the 'environmentMap' contains a mapping between different
* environments. This is used to check across, for example,
* PROD, DEV and TEST.
*
* Usage:
* $mongo -nodb ValidateIndexes.js > /dev/null
*
* To run the generated script:
* $mongo --nodb
*/
var checkAllReplSetMembers = true;
var connections = [
{
host : "",
username : "",
password : "",
authenticationDatabase : "admin",
dbsToCheck : [ "" ]
}
,{
host : "",
username : "",
password : "",
authenticationDatabase : "admin",
dbsToCheck : [ "" ]
}
,{
host : "",
username : "",
password : "",
authenticationDatabase : "admin",
dbsToCheck : [ "" ]
}
];
// map across environments
// the indexes in the primaries for each host will be checked against
// the hosts for each host key
var environmentMap =
{ "host1" :
[ "host2"
,"host3"
]
,"" :
[ ""
]
};
var report = [];
var printReport = function(line) { report.push(line); }
var getIndexes = function(connection,database) {
var out = {}
out.database = database;
out.indexes = [];
connection.getDB(database).getCollectionNames().forEach( function(c) {
var indexes = connection.getDB(database)[c].getIndexes();
out.indexes.push( { collection : c, indexes : indexes } );
});
return out;
}
var analyzeHost = function(connection,connInfo) {
var hostInfo = {}
hostInfo.host = connection.host;
hostInfo.databases = [];
try {
connInfo.dbsToCheck.forEach( function(database) {
hostInfo.databases.push( getIndexes(connection,database) );
});
} catch(error) {
//print("caught error = " + error);
hostInfo.error = error;
}
return hostInfo;
}
// Could have conflicts in replSet.name
// maintain global map to enforce uniqueness
var replSetNameMap = {};
// Find other members
var checkReplSet = function(connInfo) {
// need to connect to the
var conn = new Mongo(connInfo.host);
conn.getDB( connInfo.authenticationDatabase ).auth( connInfo.username, connInfo.password );
var rsInfo = conn.adminCommand({"replSetGetStatus":1});
if ( typeof(rsInfo.errmsg) !== 'undefined' ) { // some error, probably auth
printReport("Unable to run {replSetGetStatus : 1} on "+
connInfo.host +"\bError:"+rsInfo.errmsg);
return [];
}
conn.getDB( connInfo.authenticationDatabase ).logout();
conn = null;
var replSetInfo = [];
rsInfo.members.forEach( function(rsMember) {
if ( rsMember.stateStr==="ARBITER" ) {
return; /* skip them*/
}
var ci = { host : rsMember.name }
ci.username = connInfo.username;
ci.password = connInfo.password;
ci.authenticationDatabase = connInfo.authenticationDatabase;
ci.dbsToCheck = connInfo.dbsToCheck;
var i = connectAndCheckHost( ci );
// if this is the primary, check if we've seen this rsInfo.set
// =replset name before
if ( rsMember.stateStr==="PRIMARY" ) {
if ( typeof(replSetNameMap[rsInfo.set]) !== "undefined" ) {
// we have already seen this replSet!
replSetNameMap[rsInfo.set]++; // increment counter
// flip name
rsInfo.set = rsInfo.set + "." + replSetNameMap[rsInfo.set];
} else {
// initialize counter
replSetNameMap[rsInfo.set]=1;
}
}
i.replSet = rsInfo.set; /* use this to correlate members */
i.stateStr = rsMember.stateStr;
replSetInfo.push(i);
});
return replSetInfo;
}
var connectAndCheckHost = function(connInfo) {
var hostInfo = {}
hostInfo.host = connInfo.host;
hostInfo.databases = [];
try {
var conn = new Mongo(connInfo.host)
conn.getDB( connInfo.authenticationDatabase )
.auth( connInfo.username, connInfo.password );
conn.slaveOk=true;
var hostInfo = analyzeHost(conn,connInfo);
conn.getDB( connInfo.authenticationDatabase ).logout();
} catch(error ) {
hostInfo.error = error;
}
return hostInfo;
}
// spin through connections and gather data
var output = { "report" : "IndexAnalysis", "ts" : new Date() };
output.hosts = [];
for(var i=0;i<connections.length;i++) {
var connInfo = connections[i];
try {
if ( checkAllReplSetMembers ) {
var replInfo = checkReplSet(connInfo );
output.hosts.push.apply( output.hosts, replInfo );
} else {
var hostInfo = connectAndCheckHost(connInfo);
output.hosts.push( hostInfo );
}
} catch(error) {
output.hosts.push( { host : connInfo.host, error : error } );
}
}
// output has all the index info
//printjson( output );
/*
* Now the fun part - if we have replSet info
* compare across and find any missing
*/
if ( !checkAllReplSetMembers ) {
quit();
}
// global - map of hosts which need indexes fixed
var fixScripts = {};
var compareIndexes = function(i1,i2,i2Host) {
if ( typeof(i2)=='undefined' ) { return; }
// foreach indexes in i1, check there is an index in i2
// with same 'name'
i1.indexes.forEach( function(i) {
var jj=i2.indexes.filter( function(ii) { return ii.name==i.name } );
var gotName = i2.indexes.filter( function(ii) { return ii.name===i.name } ).length > 0;
if ( !gotName ) {
printReport("\tMISSING: " + i.name);
var db=i.ns.split('.')[0];
var coll = i.ns.split('.')[1];
var s = "db.getSiblingDB(\""+db+"\")[\""+coll+"\"].createIndex(";
var opts = { background : true, name : i.name };
s += JSON.stringify( i.key ) + "," + JSON.stringify(opts) +");";
if ( typeof(fixScripts[i2Host.host]) == 'undefined' ) {
// first time we've seen this host
fixScripts[i2Host.host] = [];
}
fixScripts[i2Host.host].push( s );
}
});
}
// return the indexes for a given namespace
// from the passed in host
var indexesForNamespace = function(database,coll,host) {
return host.databases.filter( function(h) { return h.database===database})[0]
.indexes.filter( function(i) { return i.collection===coll; } )[0];
}
var compareDBIndexes = function(database,primary,secondaries) {
var primaryCollections = primary.databases.filter( function(h) {
return h.database===database; } )[0]
.indexes.map( function(i) { return i.collection; });
primaryCollections.forEach( function(coll) {
var pIndexes = indexesForNamespace(database,coll,primary);
secondaries.forEach( function(secondary) {
printReport(primary.host +"\t" + secondary.host + "\t" +database +"." + coll);
var sIndexes = indexesForNamespace(database,coll,secondary);
compareIndexes(pIndexes,sIndexes,secondary);
});
});
}
// what replSet's are in the output
var replSets = output.hosts.map( function(host) { return host.replSet } )
.filter( function(val,idx,self) {
return self.indexOf(val) === idx;
});
// rs0 = { primary : host, secondary : host, ... }
printReport("MongoDB Index Validation:"+(new Date()));
printReport("Format:source\ttarget\tdb");
printReport("Section:ReplicaSet index validation");
replSets.forEach( function(replSet) {
var setHosts = output.hosts.filter( function(host) { return host.replSet===replSet; });
var primary = setHosts.filter( function(h) { return h.stateStr==="PRIMARY" } );
if ( primary.length!=1 ) {
printReport("ERROR: No primary found for replSet " + replSet);
return;
} else {
primary = primary[0];
}
var secondaries = setHosts.filter( function(h) {
if ( typeof(h.error) !== 'undefined' ) { // got error, move on
return false;
}
return (h.stateStr==="SECONDARY");
} );
primary.databases.forEach( function(database) {
compareDBIndexes(database.database,primary,secondaries);
});
});
// If we need to check across environments
if ( Object.keys( environmentMap ).length == 0 ) {
quit();
}
printReport("\nSection:Cross-environment index validation");
Object.keys( environmentMap ).forEach( function( source ) {
sget = output.hosts.filter( function(s) { return s.host===source } )[0];
environmentMap[ source ].forEach( function( target ) {
// got target name, get target dataer
tget = output.hosts.filter( function(h) { return h.host===target } );
if ( tget.length > 1 ) {
throw "Invalid environmentMap. More than one host called " + target + "found.";
}
sget.databases.forEach( function(database) {
compareDBIndexes(database.database,sget,tget);
});
});
});
// write out fix script.
var ts = (new Date().toISOString());
var fix_script = "IndexValidationFix."+ts+".js";
Object.keys( fixScripts ).forEach( function(hostToFix) {
// add connection info
var connInfo = connections.filter( function(h) { return h.host === hostToFix } )[0];
var connScript = "// Fixing indexes for " + connInfo.host + "\n";
connScript+="var conn = new Mongo(\""+connInfo.host+"\");\n";
connScript+="conn.getDB( \""+connInfo.authenticationDatabase +"\")";
connScript+=".auth( \""+connInfo.username+"\",\""+connInfo.password+"\" );\n";
connScript+="conn.slaveOk=true;\n"
runProgram("sh","-c","echo '"+connScript+"' >> " + fix_script);
// add createIndex commands
fixScripts[hostToFix].forEach( function(s) {
runProgram("sh","-c","echo '"+s+"' >> " + fix_script );
});
connScript = "conn.getDB( \""+connInfo.authenticationDatabase+"\").logout();\n";
connScript += "// End " + connInfo.host + "\n";
runProgram("sh","-c","echo '"+connScript+"' >> " + fix_script);
});
var reportOutput = "IndexValidationReport."+ts+".txt";
report.forEach( function(line) {
run("bash","-c","echo '"+line+"' >> " + reportOutput);
});